2016-04-29 103 views
0

基本上我爲隨機測試答案getter做了一些代碼。我的想法是,它會給你一個隨機答案,從一個選項。當我運行這個代碼時,它似乎會被拒之門外。爲什麼我的隨機答案getter的代碼不工作?

下面是代碼:

import random 
Question_total = int(input("How Many answers do you need?")) 
x = random.choice('abcd') 
print(x * Question_total) 

當我輸入一個號碼,它只是退出了。這裏是錯誤(我輸入四個):

dddd 
Exit status: 0 
logout 
Saving session... 
...copying shared history... 
...saving history...truncating history files... 
...completed. 

幫助將不勝感激。

+0

您需要一個循環。您正在生成一個隨機結果,然後重複該結果字符串幾次。 –

回答

1

它確實如此。如果仔細觀察,您會看到它打印了dddd。你寫它的方式,它抓取一個值從'abcd'並打印它Question_total次(x * Question_total)。如果您想要抓取Question_total不同的值,您需要多次撥打random.choice('abcd')

Question_total = int(input("How Many answers do you need?")) 

# Choose from 'abcd' Question_total different times and create a list of choices 
choices = [random.choice('abcd') for _ in range(Question_total)] 
print ' '.join(choices) 

# a b d a 

或者,如果你想將它寫出來作爲一個for循環

Question_total = int(input("How Many answers do you need?")) 

choices = list() 

# Go through the loop Question_total times 
for x in range(Question_total): 
    # Make a choice 
    newchoice = random.choice('abcd') 

    # Stick the choice in a list so we can remember it 
    choices.append(newchoice) 

    # Print the choice 
    print newchoice 
+0

感謝您的幫助,但是您是否認爲您可以告訴我如何更改當前代碼以便多次調用選擇?我試圖運行該代碼,它給了我這個錯誤:print(* choices) ^ SyntaxError:無效的語法。所以我不知道如何在評論中正確格式化它,但它表示print語句不是有效的語法。 –

+1

@jameslatimer對不起,我想你是在Python 3.它現在應該工作。此外,這個代碼已經*是您發佈的代碼的改編版。 – Suever

+0

謝謝朋友。我很感激 –

0

的代碼是做什麼我猜的。你給它一個號碼,然後你選擇一個隨機字母和由數

在Python中,字符串*號的字符串拼接返回到自身相乘次數

你需要做的是做什麼

for _ in range(input number): 
    Print one random letter