2016-01-25 205 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