在Python脚本中更改随机数

时间:2016-11-26 10:22:25

标签: python random numbers

我正在编写一个Python脚本,用户必须猜测一个由脚本选择的随机数。这是我的代码:

import random
while True:
    number = random.randint(1, 3)
    print("Can you guess the right number?")
    antwoord = input("Enter a number between 1 and 3: ")
    if antwoord == number:
        print ("Dang, that's the correct number!")
        print (" ")
    else:
       print ("Not the same!")
       print ("The correct answer is:")
       print (number)

    while True:
        answer = input('Try again? (y/n): ')
        print (" ")
        if answer in ('y', 'n'):
            break
        print("You can only answer with y or n!")
    if answer == 'y':
        continue
    else:
        print("Better next time!")
        break

它有效......有点......我正在尝试它并遇到了这个: User enters 2, it says it's incorrect, but then displays the same number!

我感觉每次调用变量'number'时,它会再次更改随机数。如何强制脚本保存在开头选择的随机数,而不是在脚本中保持更改?

1 个答案:

答案 0 :(得分:0)

据我所知,你想在每个循环步骤中选择一个新的随机整数。 我猜你正在使用python 3,所以input返回一个字符串。由于您无法在字符串和int之间执行comparisson,因此需要先将输入字符串转换为int。

import random
while True:
    number = random.randint(1, 3)
    print("Can you guess the right number?")
    antwoord = input("Enter a number between 1 and 3: ")
    try:
        antwoord = int(antwoord)
    except:
        print ("You need to type in a number")
    if antwoord == number:
        print ("Dang, that's the correct number!")
        print (" ")
    else:
       print ("Not the same!")
       print ("The correct answer is:")
       print (number)

    while True:
        answer = input('Try again? (y/n): ')
        print (" ")
        if answer in ('y', 'n'):
            break
        print("You can only answer with y or n!")
    if answer == 'y':
        continue
    else:
        print("Better next time!")
        break