简体   繁体   English

else & elif 语句在 Python 中不起作用

[英]else & elif statements not working in Python

I'm a newbie to Python and currently learning Control Flow commands like if , else , etc.我是 Python 的新手,目前正在学习ifelse等控制流命令。

The if statement is working all fine, but when I write else or elif commands, the interpreter gives me a syntax error. if语句一切正常,但是当我编写elseelif命令时,解释器给了我一个语法错误。 I'm using Python 3.2.1 and the problem is arising in both its native interpreter and IDLE.我正在使用 Python 3.2.1,问题出现在它的本机解释器和 IDLE 中。

I'm following as it is given in the book 'A Byte Of Python' .我正在关注“A Byte Of Python”一书中给出的内容。 As you can see, elif and else are giving Invalid Syntax .如您所见, elifelse给出了Invalid Syntax

>> number=23
>> guess = input('Enter a number : ')
>> if guess == number:
>>    print('Congratulations! You guessed it.')
>> elif guess < number:
   **( It is giving me 'Invalid Syntax')**
>> else:
   **( It is also giving me 'Invalid syntax')**

Why is this happening?为什么会这样? I'm getting the problem in both IDLE and the interactive python.我在 IDLE 和交互式 python 中都遇到了问题。 I hope the syntax is right.我希望语法是正确的。

在此处输入图像描述

It looks like you are entering a blank line after the body of the if statement.看起来您在if语句的主体之后输入了一个空行。 This is a cue to the interactive compiler that you are done with the block entirely, so it is not expecting any elif / else blocks.这是对交互式编译器的提示,您已完全完成了该块,因此它不需要任何elif / else块。 Try entering the code exactly like this, and only hit enter once after each line:尝试完全像这样输入代码,并且在每行之后只按一次回车:

if guess == number:
    print('Congratulations! You guessed it.')
elif guess < number:
    pass # Your code here
else:
    pass # Your code here

The problem is the blank line you are typing before the else or elif .问题是您在elseelif之前输入的空行。 Pay attention to the prompt you're given.注意给你的提示。 If it is >>> , then Python is expecting the start of a new statement.如果是>>> ,则 Python 期待新语句的开始。 If it is ... , then it's expecting you to continue a previous statement.如果是... ,那么它希望您继续之前的声明。

elif and else must immediately follow the end of the if block, or Python will assume that the block has closed without them. elifelse必须紧跟if块的末尾,否则 Python 将假定该块在没有它们的情况下关闭。

if 1:
    pass
             <--- this line must be indented at the same level as the `pass`
else:
    pass

In your code, the interpreter finishes the if block when the indentation, so the elif and the else aren't associated with it.在您的代码中,解释器在缩进时完成if块,因此elifelse不与之关联。 They are thus being understood as standalone statements, which doesn't make sense.因此,它们被理解为独立的陈述,这是没有意义的。


In general, try to follow the style guidelines , which include removing excessive whitespace.通常,请尝试遵循样式指南,其中包括删除过多的空格。

In IDLE and the interactive python, you entered two consecutive CRLF which brings you out of the if statement.在 IDLE 和交互式 python 中,您输入了两个连续的 CRLF,这使您脱离了 if 语句。 It's the problem of IDLE or interactive python.这是IDLE或交互式python的问题。 It will be ok when you using any kind of editor, just make sure your indentation is right.当您使用任何类型的编辑器时都可以,只要确保您的缩进是正确的。

Remember that by default the return value from the input will be a string and not an integer.请记住,默认情况下,输入的返回值将是一个字符串,而不是 integer。 You cannot compare strings with booleans like <, >, =>, <= (unless you are comparing the length).您不能将字符串与诸如 <、>、=>、<= 之类的布尔值进行比较(除非您正在比较长度)。 Therefore your code should look like this:因此,您的代码应如下所示:

number = 23
guess = int(input('Enter a number: '))  # The var guess will be an integer

if guess == number:
    print('Congratulations! You guessed it.')

elif guess != number:
    print('Wrong Number')
 if guess == number:
     print ("Good")
 elif guess == 2:
     print ("Bad")
 else:
     print ("Also bad")

Make sure you have your identation right.确保您的身份正确。 The syntax is ok.语法没问题。

Besides that your indention is wrong.除此之外,您的缩进是错误的。 The code wont work.该代码将无法正常工作。 I know you are using python 3. something.我知道你正在使用 python 3. 一些东西。 I am using python 2.7.3 the code that will actually work for what you trying accomplish is this.我正在使用 python 2.7.3 实际适用于您尝试完成的代码就是这个。

number = str(23)
guess =  input('Enter a number: ')
if guess == number:
   print('Congratulations! You guessed it.')
elif guess < number:
     print('Wrong Number')
elif guess < number:
     print("Wrong Number')

The only difference I would tell python that number is a string of character for the code to work.我会告诉 python 的唯一区别是该数字是代码工作的字符串。 If not is going to think is a Integer.如果不是会认为是 Integer。 When somebody runs the code they are inputing a string not an integer.当有人运行代码时,他们输入的不是 integer 的字符串。 There are many ways of changing this code but this is the easy solution I wanted to provide there is another way that I cant think of without making the 23 into a string.有很多方法可以更改此代码,但这是我想提供的简单解决方案,如果不将 23 转换为字符串,我无法想到另一种方法。 Or you could of "23" put quotations or you could of use int() function in the input.或者您可以使用 "23" 引用,或者您可以在输入中使用 int() function。 that would transform anything they input into and integer a number.这会将他们输入的任何内容转换为 integer 一个数字。

Python can generate same 'invalid syntax' error even if ident for 'elif' block not matching to 'if' block ident (tabs for the first, spaces for second or vice versa). Python 可以生成相同的“无效语法”错误,即使“elif”块的标识与“if”块标识不匹配(第一个为制表符,第二个为空格,反之亦然)。

indentation is important in Python.缩进在 Python 中很重要。 Your if else statement should be within triple arrow (>>>), In Mac python IDLE version 3.7.4 elif statement doesn't comes with correct indentation when you go on next line you have to shift left to avoid syntax error.您的 if else 语句应该在三箭头 (>>>) 内,在 Mac python IDLE 3.7.4 版中,当您在下一行 go 时,elif 语句没有正确缩进,您必须向左移动以避免语法错误。

在此处输入图像描述

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

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