2016-04-29 46 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 
相关问题