简体   繁体   中英

I just cant figure out why my code throws a syntax error when I add int() to a input

first off here is my code:

def main():
    def add(x,y):

        return x + y

    def subtract(x,y):

        return x - y

    def multiple(x,y):

        return x * y

    def divide(x,y):

        return x / y

user_choice = int(input("Choose calculation: 1. add 2. subtract 3. divide 4. multiple \n")

dog = int(input("Enter first number: "))
cat = int(input("Enter second number: "))


if user_choice == '1':
   print(dog,"+",cat,"=", add(dog,cat))

elif user_choice == '2':
   print(dog,"-",cat,"=", subtract(dog,cat))

elif user_choice == '3':
   print(dog,"*",cat,"=", multiply(dog,cat))

elif user_choice == '4':
   print(dog,"/",cat,"=", divide(dog,cat))
else:
   print("Invalid input")

main()
while True:
    restart = input("Would you like to restart? (y/n)")
    if restart == 'y':
         main()

    elif restart == 'n':
        print('have a nice day!')
        break
    else:
        print("invalid input. Please enter y or n.")

So i built a pretty simple calculator that does addition, multiplication, subtraction, and division. Now, the problem is when I run this exact code I get a syntax error calling out line 20

dog = int(input("Enter first number: "))
  ^
SyntaxError: invalid syntax

I couldn't figure out why this line was wrong since i looked at another small program i built and it had basically the same line. After fiddling around a bit I managed to fix the program, by removing int() from the user_choice input. I just want to know why exactly this fixed that problem? and is there a different reason that line wasnt working? Thanks for any input!

You are missing a bracket at the end of this line (fixed below):

user_choice = int(input("Choose calculation: 1. add 2. subtract 3. divide 4. multiple \n"))

Also, the multiply function is misspelled.

Just noticed another one, the if user_choice checks should be checking for ints not strings if user_choice == 1 not if user_choice == '1'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM