简体   繁体   English

python 3中的elif错误

[英]elif error in python 3

I started python a couple of days back..now learning to use 'if' and 'elif'...created a basic program....when I use elif, it shows me 我几天前开始使用python。现在学习使用'if'和'elif'...创建了一个基本程序....当我使用elif时,它向我显示了

syntax error:invalid syntax 语法错误:语法无效

print('welcome to my calculator')
num1 = int(input('enter the first number:'))
num2 = int(input('enter the second number:'))
print('select options')
functions = ['Add','Sub','Mul','Div']
print (functions)
options = input("enter the desired option:")
if options == 'Add':
    print(num1+num2)
print('num1+num2=', num1+num2) 
elif options == 'Sub':
    print(num1-num2)
print('num1-num2=', (num1-num2))

when I ran this, I got the following error 当我运行它时,出现以下错误

elif options == 'Sub':
       ^
SyntaxError: invalid syntax

Process finished with exit code 1

Can anyone help me solve this error? 谁能帮我解决这个错误?

For python you need to have everything inside of your if, elif and else at the same indention. 对于python,您需要将if,elif和else的所有内容都放在相同的缩进中。 Change it to 更改为

if options == 'Add':
    print(num1+num2)
    print('num1+num2', num1+num2)
elif options == 'Sub':
print('welcome to my calculator')
num1 = int(input('enter the first number:'))
num2 = int(input('enter the second number:'))
print('select options')
functions = ['Add','Sub','Mul','Div']
print (functions)
options = input("enter the desired option:")
if options == 'Add':
    print(num1+num2)
    print('num1+num2=', num1+num2) 
elif options == 'Sub':
    print(num1-num2)
    print('num1-num2=', (num1-num2))
else:                    # you need this line as well
    print("continue... remaining logic")

The problem in your script is in the indetention. 您的脚本中的问题在于居留权。 Basically, in order to fix the problem, you should change your code in this way: 基本上,为了解决问题,您应该以这种方式更改代码:

options = input("enter the desired option:")
if options == 'Add':
    print(num1+num2)
    print('num1+num2=', num1+num2) 
elif options == 'Sub':
    print(num1-num2)
    print('num1-num2=', (num1-num2))

In your code, the line print('num1+num2=', num1+num2) ended the if statement, and so elif doesn't have any meaning 在您的代码中, print('num1+num2=', num1+num2)结束了if语句,因此elif没有任何意义

Put the "prints" inside the "if" statements and that's it. 将“打印”放入“ if”语句中,仅此而已。 It worked for me: 它为我工作:

welcome to my calculator
enter the first number:3
enter the second number:2
select options
['Add', 'Sub', 'Mul', 'Div']
enter the desired option:Sub
1
num1-num2= 1

Tried also the 'Add' option. 还尝试了“添加”选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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