[英]Simple if/elif statement + raw_input why dosen't work
I have a problem with simple if statement. 我对简单的if语句有疑问。 I want user to press a key '1','2' or '3' to choose any option then program will do something.
我希望用户按下键“ 1”,“ 2”或“ 3”以选择任何选项,然后程序将执行某些操作。 For a test it just prints text for example "Wybrano 2" after pressing '2'.
为了进行测试,它仅在按“ 2”后才打印文本,例如“ Wybrano 2”。
Here is my code: 这是我的代码:
if raw_input() == '1':
print "Wybrano 1"
elif raw_input() == '2':
print "Wybrano 2"
elif raw_input() == '3':
print "Wybrano 3"
So if I press 1 it correctly prints "Wybrano 1" but when I press 2 or 3 the program does nothing. 因此,如果我按1,它将正确打印“ Wybrano 1”,但是当我按2或3时,程序将不执行任何操作。
When i press 2 or 3 program does not nothing is wrong. 当我按2或3程序不没有什么不对。 It is waiting for you for next input.
它正在等待您下一次输入。
Let me tell you how this is working. 让我告诉你这是如何工作的。
raw_input
is python function for accepting user input.(I know you are aware of this :) ) raw_input
是用于接受用户输入的python函数。(我知道您知道这一点:)) if
" statement. if
”语句。 'if'
statement has 'raw_input'
function after it. 'if'
语句之后具有'raw_input'
功能。 So, it waits for your input. "1" = "1"
, it gives you expected output and come out of code. "1" = "1"
,它将为您提供预期的输出并脱离代码。 'raw_input'
after 'if'
is executed waiting for your input. 'if'
之后再次执行'raw_input'
以等待您的输入。 When you input '2' and since '1' == '2'
is false, code goes to next 'elif'
statement. '1' == '2'
为假时,代码将转到下一个'elif'
语句。 After 'elif'
there is 'raw_input'
function which is waiting for input again. 'elif'
有'raw_input'
功能正在等待再次输入。 Example of above explained behavior 上述行为的示例
if raw_input("Enter number : ") == '1':
print "Wybrano 1"
elif raw_input("Enter number : ") == '2':
print "Wybrano 2"
elif raw_input("Enter number : ") == '3':
print "Wybrano 3"
Output: 输出:
C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 1
Wybrano 1
C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 2
Enter number : 2
Wybrano 2
C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 3
Enter number : 3
Enter number : 3
Wybrano 3
How to make your code working ? 如何使您的代码正常工作?
Answer is simple. 答案很简单。 As explained by @MooingRawr in first comment, just save user input in some variable and then check.
如@MooingRawr在第一条评论中所述,只需将用户输入保存在某个变量中,然后进行检查。
x = raw_input("Enter number : ")
if x == '1':
print "Wybrano 1"
elif x == '2':
print "Wybrano 2"
elif x == '3':
print "Wybrano 3"
Output: 输出:
C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 1
Wybrano 1
C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 2
Wybrano 2
C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 3
Wybrano 3
C:\Users\dinesh_pundkar\Desktop>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.