彩票random.randint帮助python

时间:2012-03-01 14:51:13

标签: python

到目前为止我的节目

import random

def lottery(lottoNumber1,lottoNumber2,lottoNumber3):
    for count in range(1):
        lottoNumber1 = random.randint(1,50)
        print(lottoNumber1)
    for count in range(1):
        lottoNumber2 = random.randint(1,50)
        print(lottoNumber2)
    for count in range(1):
        lottoNumber3 = random.randint(1,50)
        print(lottoNumber3)



    return lottoNumber1,lottoNumber2,lottoNumber3

def main():
    userChoice1 = int(input('Chose a number between 1 and 50: '))
    userChoice2 = int(input('Chose a number between 1 and 50: '))
    userChoice3 = int(input('Chose a number between 1 and 50: '))


    if userChoice1 == lottoNumber1:
        lottoNumber1 = lottery(lottoNumber1,lottoNumber2,lottoNumber3)
        print('You win $1,000')
    else:
        print('You effing suck')





main()

我收到一条消息错误,说明lottoNumber1是在main函数中赋值之前的引用。我不确定这意味着什么。任何人都知道我能做些什么来使这段代码更顺畅。我想这样做,所以用户必须选择3个数字,如果他得到它们等于3个乐透号码,他就赢了10000个

谢谢你们。

2 个答案:

答案 0 :(得分:2)

您在定义之前使用lottonumber1(评估lottery时尚未调用if userChoice1 == lottonumber1:)。

即使您将lottery的呼叫移至if之前,它仍会失败,因为您(不必要地)使用参数lottoNumber1,lottoNumber2,lottoNumber3调用它也未定义爱好。

此外,for语句在这里没用(它只执行一次,即使你迭代了多个元素的实际range,它仍然不会改变任何东西,因为它相同变量将连续几次设置为随机值。

这可行(虽然没有多大意义):

import random

def lottery():                          # no parameters!
    lottoNumber1 = random.randint(1,50)
    print(lottoNumber1)
    lottoNumber2 = random.randint(1,50)
    print(lottoNumber2)
    lottoNumber3 = random.randint(1,50)
    print(lottoNumber3)
    return lottoNumber1,lottoNumber2,lottoNumber3

userChoice1 = int(input('Choose a number between 1 and 50: '))
userChoice2 = int(input('Choose a number between 1 and 50: '))
userChoice3 = int(input('Choose a number between 1 and 50: '))

lottoNumber1, lottoNumber2, lottoNumber3 = lottery()

if userChoice1 == lottoNumber1:
    print('You win $1,000')
else:
    print('You effing suck')

lotteryn之间编写一个返回min_value - 随机值元组的max_value函数可能会更有意义:

def lottery(n=3, min_value=1, max_value=50):
    return [random.randint(min_value, max_value) for i in range(n)]

答案 1 :(得分:0)

简单回答:lottoNumber1未在函数main中定义。

此外,我建议你不要重复相同的代码,而是将其移动到一个函数中。而不是像

这样的结构
userChoice1 = int(input('Chose a number between 1 and 50: '))
userChoice2 = int(input('Chose a number between 1 and 50: '))
userChoice3 = int(input('Chose a number between 1 and 50: '))

会好得多
def inputNumber():
    return int(input('Chose a number between 1 and 50: '))

...

def main():
    ....
    userChoice1=inputNumber()
    userChoice2=inputNumber()
    userChoice3=inputNumber()

这样必须重复,您的代码只包含一次文本,您可以添加一个检查,如果数字真的在1到50之间在代码中一点