Python脚本中的随机数字被更改

2024-10-05 14:27:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个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’,它就会再次改变随机数。如何强制脚本保留在开始时选取的随机数,而不在脚本中不断更改它?你知道吗


Tags: theanswer脚本truenumberinputifrandom
1条回答
网友
1楼 · 发布于 2024-10-05 14:27:23

据我所知,您希望在每个循环步骤中选取一个新的随机整数。 我猜您使用的是python3,因此input返回一个字符串。由于不能在字符串和int之间执行比较,因此需要首先将输入字符串转换为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

相关问题 更多 >