2012-08-30 71 views
1

我是一個初學者python學習者。我正在嘗試創建一個基本詞典,詞彙的隨機含義將隨之出現,用戶必須輸入正確的詞彙。我使用了以下方法,但隨機不起作用。我總是首先得到第一個詞,當最後一個詞結束時,我將無限的'無',直到我殺了它。使用蟒蛇3.2Python-如何初始化隨機函數

from random import choice 


print("Welcome , let's get started") 
input() 

def word(): 
    print('Humiliate') 
    a = input(':') 
    while a == 'abasement': 
     break 
    else: 
     word() 
    # --------------------------------------------------------- # 



def word1(): 
    print('Swelling') 
    a = input(':') 
    while a == 'billowing': 
     break 
    else: 
     word() 
# ------------------------------------------------------------ # 


wooo = [word(),word1()] 
while 1==1: 
    print(choice(wooo)) 

有沒有更快的方式做到這一點,並得到真正的隨機?我嘗試過課,但看起來比這更難。另外,有什麼辦法可以讓python不關心天氣的輸入是否是大寫字母?

+0

我將重新以更清晰的方式構建代碼。你可以例如建立一個2元組列表,每個元組由'(「question」,「correct_answer」)組成。然後,我會隨機選擇這些元組中的一個,並將其提供給實際打印元組中第一個元素並請求用戶輸入的函數。這樣做可以避免多次寫入相同的代碼。 –

+0

謝謝,我會嘗試創建一個喜歡建議。 –

回答

2

要回答你的問題的一部分(「有沒有什麼辦法可以讓蟒蛇不關心天氣的輸入大寫字母或不?」):使用some_string.lower()

>>> "foo".lower() == "foo" 
True 
>>> "FOO".lower() == "foo" 
True 

的這是幫助你如何能提高你的代碼的結構:

import sys 
from random import choice 

WORDPAIRS = [('Humiliate', 'abasement'), ('Swelling', 'billowing')] 

def ask(): 
    pair = choice(WORDPAIRS) 
    while True: 
     answer = raw_input("%s: " % pair[0]).lower() 
     if answer == pair[1]: 
      print "well done!" 
      return 


def main(): 
    try: 
     while True: 
      ask() 
    except KeyboardInterrupt: 
     sys.exit(0) 


if __name__ == "__main__": 
    main() 

它的工作原理類似:

$ python lulu.py 
Swelling: lol 
Swelling: rofl 
Swelling: billowing 
well done! 
Humiliate: rofl 
Humiliate: Abasement 
well done! 
Swelling: BILLOWING 
well done! 
Humiliate: ^C 
$ 
+0

我以前從未使用.lower函數。我如何使用它?我嘗試在這樣的地方添加一些內容:'while a =='Billowing'.lower():'但它不能完成這項工作。 –

+0

這是一個字符串方法。只需通過's.lower()'將其應用於字符串's',並返回相同的字符串,並將所有大寫字母替換爲小寫字母。這就是爲什麼'FOO'.lower()'返回'「foo」'。在將測試字符串與引用字符串進行比較之前,將引用字符串(「滾滾」)保持爲小寫,並將測試字符串(用戶給定)轉換爲小寫。通過這樣做,測試不區分大小寫。例如:'a.lower()=='billowing''。 upvote幫助:-)的答案。 –

+0

感謝您的解釋:)我正在使用'n ='abAsement'.lower() while a == n:' –

2
wooo = [word, word1] 
while 1: 
    print(choice(wooo)()) 

但在任何情況下,它會打印你None,導致您的兩個函數返回任何結果(None)。

+0

謝謝:)它的工作原理!我試圖擺脫沒有回報,但它弄亂我想要的功能做的工作。 –