[英]Why if-then statement isn't working?
This is the code that I made when I tried making an if-then statement but, it always defaults to else. 这是我尝试执行if-then语句时编写的代码,但始终默认为else。 Also i just started trying to code from online tutorials today.
我今天也刚刚开始尝试从在线教程进行编码。
print('yes or no?')
if sys.stdin.readline() == 'yes' :
print('Yay')
else :
print('Aww')
This is what happens: 这是发生了什么:
Console:yes or no?
Me:yes
Console:Aww
I've been looking stuff up for half an hour and can't figure out how to fix this please help 我一直在找东西半个小时,不知道如何解决这个问题,请帮忙
sys.stdin.readline()
reads a line which ends with '\\n' (when you hit "enter"). sys.stdin.readline()
读取以'\\ n'结尾的行(当您单击“ enter”时)。
So you need to remove this '\\n' from the captured input using strip()
. 因此,您需要使用
strip()
从捕获的输入中删除此“ \\ n”。
print('yes or no?')
if sys.stdin.readline().strip() == 'yes' :
print('Yay')
else :
print('Aww')
I tried to explain and solve your specific problem but you could of course use raw_input()
or input()
(PY3) as mentioned in the other answer. 我试图解释和解决您的特定问题,但您当然可以使用其他答案中提到的
raw_input()
或input()
(PY3)。
In python, getting the input of a user's string can be done via input()
(or in python 2.7, use raw_input()
). 在python中,可以通过
input()
获取用户字符串的input()
(或者在python 2.7中,使用raw_input()
)。
If you include the code: 如果包含代码:
user_input = raw_input("yes or no?")
This will first print the string "yes or no?", then wait for user input (through stdin), then save it as a string named user_input
. 这将首先打印字符串“是或否?”,然后等待用户输入(通过stdin),然后将其另存为名为
user_input
的字符串。
So, you change your code to be: 因此,您将代码更改为:
user_input = raw_input("yes or no?")
if user_input == "yes":
print("Yay")
else:
print("Aww")
this should have the desired effect. 这应该具有预期的效果。
Ok I used user_input and input instead of sys.stdin.readline() on strings and i used it in a basic calculator here it is : 好的,我在字符串上使用了user_input和input而不是sys.stdin.readline(),我在一个基本的计算器中使用了它,它是:
import random
import sys
import os
user_input = input("Would you like to add or subtract?")
if user_input == 'add' :
print('What would you like to add?')
plus1 = float(sys.stdin.readline())
print('Ok so %.1f plus what?' % (float(plus1)))
plus2 = float(sys.stdin.readline())
print('%.1f plus %.1f equals %.1f' % (float(plus1),float(plus2), float(plus1+plus2)))
elif user_input == 'subtract' :
print('What would you like to subtract?')
minus1 = float(sys.stdin.readline())
print('Ok so %.1f minus what?' % (float(minus1)))
minus2 = float(sys.stdin.readline())
print('%.1f minus %.1f equals %.1f' % (float(minus1), float(minus2), float(minus1 - minus2)))
else :
print('That is not one of the above options')
Thanks alot guys! 谢谢大家!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.