python if带有字符串的语句

时间:2016-01-25 15:43:29

标签: python

Name=str(input("Your name is? "))
print("Hello,",Name,"!")
Age=int(input("And how old might you be? "))
print("So you are",Age,"years old?")
print("So on your next birthday, you will be",Age+1,"?")
agecorrect=str(input("Yes or no? "))
yes= in ["Yes","yes","Y","y","yes.","Yes."]
no= in ["No","no","N","n","no.","No."]
if agecorrect=yes:
    print("Yes, I was right!")
else
if agecorrect=no:
    realage=int(input("So your real age on your next birthday will be? "))
    print("So you're actually going to be",realage,"? Good to know!")
else
print("I don't understand... I asked for a yes or no answer.")

如果之前已经问过这个问题,我很抱歉,但我不知道为什么我的代码无效,我需要一些帮助。谢谢。 (顺便说一下,Python 3.5.1)

4 个答案:

答案 0 :(得分:3)

您无法将变量设置为in [...]等比较表达式。所以

yes= in ["Yes","yes","Y","y","yes.","Yes."]

无效。您只需将yesno设置为列表:

yes = ["Yes","yes","Y","y","yes.","Yes."]
no = ["No","no","N","n","no.","No."]

然后您可以使用if agecorrect in yes

if agecorrect in yes:
    print("Yes, I was right!")
elif agecorrect in no:
    realage=int(input("So your real age on your next birthday will be? "))
    print("So you're actually going to be",realage,"? Good to know!")
else:
    print("I don't understand... I asked for a yes or no answer.")

:之后你还错过了else

答案 1 :(得分:3)

所以......

这是你的"固定"代码:

# don't use uppercase in variables names,
# prefer underscores over camelCase or dashes
# leave space before and after assignment, there are exceptions of this rule
# but not here ;)
name = str(input("Your name is? "))
print("Hello {}!".format(name))
age = int(input("And how old might you be? "))

# english grammar man!
print("So are you {} years old?".format(age))
print("So on your next birthday, you will be {}?".format(age + 1))
agecorrect = str(input("Yes or no? "))

# in is keyword and you use it to check whether item is in collection
# or its not
# please don't try to attach it to variable
# also use space after putting comma
yes = ["Yes", "yes", "Y", "y", "yes.", "Yes."]
no = ["No", "no", "N", "n", "no.", "No."]
if agecorrect in yes:
    print("Yes, I was right!")

# you forgot about colon
elif agecorrect in no:
    realage = int(input("So your real age on your next birthday will be? "))
    print("So you're actually going to be {}? Good to know!".format(realage))
else:
    print("I don't understand... I asked for a yes or no answer.")

答案 2 :(得分:2)

yes = ("Yes","yes","Y","y","yes.","Yes.")
question = input("Yes or no? ")
agecorrect = question in yes
if agecorrect:
    # ...

答案 3 :(得分:0)

检查应始终使用 <body ng-controller="TestController"> Selected item must be {{ array[test-1].name }} <select ng-model="myModel"> <option value="">Choose item..</option> <option ng-repeat="item in array" ng-value="item.id" ng-selected="item.id == test"> {{ item.name }} ({{item.id == test}}) </option> </select> </body> ,而不是==,这是作业。

始终使用

=

而不是

if y == 'yes':

如果您编写上面的代码,Python会抛出错误,但其他语言只会将值赋给if y = 'yes': 并运行if语句。

相关问题