2016-01-25 170 views
-1
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)python if语句字符串

+0

的错误信息会清楚地告诉你,你有无效的语法'是=以... '。 –

+0

'in [“是”,“是”,“是”,“是”,“是”,“是”。]'那是什么? – Maroun

+0

@MarounMaroun是的所有可能的答案是 – SirParselot

回答

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后失踪的:

+0

非常感谢,对不起的问题感到抱歉 – Nezzeh

+1

@Nezzeh这很好,从错误中倾斜并改善您未来的帖子更重要。 – Maroun

+0

'elif'而不是'else if'? – LexyStardust

0

检查应始终使用==而不是=,这是分配。

始终使用

if y == 'yes': 

,而不是

if y = 'yes': 

,如果你写上面的代码Python会扔给你一个错误,但其他语言将只值分配给y和运行if语句。

+0

谢谢你,我会记住 – Nezzeh

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.") 
+0

感谢你 - 也就是'你是'的目的是作为一个声明,而不是一个问题 – Nezzeh

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

你也可以'agecorrect =是的问题' – ForceBru

+0

@ForceBru,编辑,谢谢 – Fred