我如何使我的输入接受所有int和str类型的数据

时间:2019-08-29 23:31:26

标签: python-3.x input

我正在尝试使用用户输入作为答案的猜谜游戏,如果用户类型退出,游戏将显示玩家尝试的时间,但该程序无法运行,因为它只能使用任一个整数或字符串类型。

import random
while True:
    number = random.randint(1,9)
    guess = int(input('guess the number: '))
    time = 0
    time += 1
    if guess == number:
        print('you guessed correct')
    elif guess < number:
        print('your guessed is lower than the actual number')
    elif guess > number:
        print('your guessed is higher than the actual number')
    elif guess == 'exit':
        print(time)
        break
        

2 个答案:

答案 0 :(得分:0)

类似的东西

import random

time = 0
number = random.randint(1,9)

while True:
    guess = input('guess the number: ')
    time += 1
    if guess == "exit":
        print(time)
        break
    elif int(guess) < number:
        print('your guessed is lower than the actual number')
    elif int(guess) > number:
        print('your guessed is higher than the actual number')
    elif int(guess) == number:
        print('you guessed correct')
        print(time)
        break

请注意,时间和数字必须在while循环之外进行初始化,因为如果没有,我们将为每次迭代获得不同的随机数,并且时间也将每次初始化为0。

答案 1 :(得分:0)

您可以先将输入作为字符串测试,然后再将其转换为整数:

while True:
    response = input('guess the number: ')
    if response == 'exit':
        break
    guess = int(response)
    # the rest of your code testing guess as a number