Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def main(expression: str): # Expects user's input in the function (string)
- if len(expression) == 0:
- return "Empty string." # Output when user's input is empty
- first = expression[0]
- signs = {'+', '-', '*'}
- if first.isspace() or first in signs:
- return "Invalid expression." # Output when first character is space or any of signs
- splits = [first] # We populate splits list with the first character of the expression
- for i in expression[1:]: # Start the loop from second character
- if splits[-1] == '*':
- if i.isdigit():
- splits.append(i)
- else:
- return "Invalid expression." # Output when signs are next to each other
- elif i.isdigit():
- splits[-1] += i # If current character is a digit, add it onto the last element of list
- else:
- if splits[-1] in signs:
- return "Invalid expression." # Output when signs are next to each other
- else:
- splits.append(i) # If current character is + or -, we append a new element onto the list
- j = 0 # Counter
- while j < len(splits):
- if splits[j] == '*':
- splits[j - 1] = int(splits[j - 1]) * int(splits[j + 1]) # Multiply left, right hand of the multiply index
- del splits[j: j + 2] # Delete multiply index and right hand index, result is stored on left hand
- else:
- j += 1 # Otherwise increment if no multiply sign is found
- # Sum of all elements in the list, we use list comprehension here to convert all elements with type 'str' to 'int'
- return sum([int(x) for x in splits])
- user_input = input("Please enter an arithmetic expression: ")
- result = main(user_input)
- if type(result) == int:
- # Format is used here so I can put a full-stop straight after the variable without having a space dividing it
- print("The result is {0}.\nGoodbye.".format(result))
- else:
- print(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement