[英]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 现在,问题是当我运行此确切代码时,出现语法错误,调出第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. 经过一番摆弄之后,我设法通过从user_choice输入中删除int()来修复了该程序。 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. 此外, multiply
功能拼写错误。
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'
刚刚注意到了另一个问题, if user_choice == 1
,则if user_choice
检查应该检查整数而不是字符串if user_choice == 1
if user_choice == '1'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.