2016-08-11 55 views
0

爲了防止有人採取這種行動是的,我去找手中的答案。所以我正在研究一個小型的個人項目,並且我陷入了僵局(只是你知道我對Python很新穎)。我會告訴你我是什麼意思某些變量無法定義?

joke = input("Want to hear a funny joke?\n") 
if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']: 
    chicken = input("Why did the chicken cross the road?\n") 
if chicken in ["To get to the other side", "to get to the other side"]: 
    print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!") 
else: 
    print("Awww..") 

我試圖去這裏發生的是蟒蛇會問你,如果你想聽到一個笑話,如果你說沒有它會去「噢......」如果你說是,它會問你爲什麼雞過馬路。它的工作原理,當我說是的,但是當我說沒有它給這個

Want to hear a funny joke? 
no 
Traceback (most recent call last): 
    File "C:\Users\Andrew\Desktop\Python projects\Python Buddie.py", line 34, in <module> 
    if chicken in ["To get to the other side", "to get to the other side"]: 
NameError: name 'chicken' is not defined 

我有雞定義,你可以看到。我覺得我得到的訂單是錯的,有人能幫助我嗎?

回答

2
if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']: 
    chicken = input("Why did the chicken cross the road?\n") 
if chicken in ["To get to the other side", "to get to the other side"]: 
    print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!") 

如果jokein ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']會發生什麼?

然後chicken未定義。您應該有第一if內第二if,或定義chicken事先:

if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']: 
    chicken = input("Why did the chicken cross the road?\n") 
    if chicken in ["To get to the other side", "to get to the other side"]: 
     print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!") 

chicken = None 
if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']: 
    chicken = input("Why did the chicken cross the road?\n") 
if chicken in ["To get to the other side", "to get to the other side"]: 
    print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!") 
+0

那你說的那個部分怎麼樣,它不去啊? –

+0

@DeanGullberry你可以把它留在原地。我只專注於有問題的部分。 – DeepSpace

0

你把別人錯了地方,這就是爲什麼

你else語句當用戶已經說好的時候是跟着的

要解決這個問題:

joke = input("Want to hear a funny joke?\n") 

if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']: 
    chicken = input("Why did the chicken cross the road?\n") 
    if chicken in ["To get to the other side", "to get to the other side"]: 
    print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!") 
else: 
    print("Awww..") 
+0

再次嘗試,並確保所有代碼是聯機的,並匹配規定的縮進python 2.7.x或3.0x –

+0

很高興幫助:) –

0

Python不提供大括號來指示類和函數定義或流量控制的代碼塊。代碼塊由線條縮進表示,嚴格執行。

錯誤僅僅是因爲縮進錯誤。

joke = input("Want to hear a funny joke?\n") 
if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']: 
    chicken = input("Why did the chicken cross the road?\n") 
    if chicken in ["To get to the other side", "to get to the other side"]: 
     print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!") 
else: 
    print("Awww..") 
+0

只有答案工作非常感謝你! –

+0

好..歡迎光臨 – Harsha

相關問題