注册 登录
编程论坛 Python论坛

请教一下,如何在用int(input())函数时候输入字符串时候可以不出错

LanXX 发布于 2019-11-27 14:51, 1567 次点击
谢谢各位大神,帮帮我,我需要的的确是整数,但怎么才可以输入了字符串也不会出错呢?


print('You enter a dark room with two doors.\nDo you go through oor #1 or door #2?')
door = int(input('>'))

if door == 1:
    print('There\'s a giant bear here eating a cheese cake.')
    print('what do you do?')
    print('1.Take the cake. \n2.Scream at the bear.')
    num = int(input('>'))

    for i in range(1):
        if num == 1:
            print('The bear eats your face off.\tGood job!')

        if num == 2:
            print('The bear eats your legs off.\tGood job!')

        else:
            print(f'{num} is not option, do it agains.')
            continue
else:
    print('you\'re dead')
2 回复
#2
fall_bernana2019-11-27 15:59
以下是引用LanXX在2019-11-27 14:51:15的发言:

谢谢各位大神,帮帮我,我需要的的确是整数,但怎么才可以输入了字符串也不会出错呢?


print('You enter a dark room with two doors.\nDo you go through oor #1 or door #2?')
door = int(input('>'))

if door == 1:
    print('There\'s a giant bear here eating a cheese cake.')
    print('what do you do?')
    print('1.Take the cake. \n2.Scream at the bear.')
    num = int(input('>'))

    for i in range(1):
        if num == 1:
            print('The bear eats your face off.\tGood job!')

        if num == 2:
            print('The bear eats your legs off.\tGood job!')

        else:
            print(f'{num} is not option, do it agains.')
            continue
else:
    print('you\'re dead')

程序代码:
print('You enter a dark room with two doors.\nDo you go through oor #1 or door #2?')
door = input('>')
while not door.isdigit():
    print("must int\n")
    door = input('>')

if int(door) == 1:
    print('There\'s a giant bear here eatinsg a cheese cake.')
    print('what do you do?')
    print('1.Take the cake. \n2.Scream at the bear.')
    num = input('>')
    while not num.isdigit():
        print("must int\n")
        num = input('>')

    for i in range(1):
        if int(num) == 1:
            print('The bear eats your face off.\tGood job!')

        elif int(num) == 2:
            print('The bear eats your legs off.\tGood job!')

        else:
            print(f'{num} is not option, do it agains.')
            continue
else:
    print('you\'re dead')
#3
LanXX2019-11-29 14:16
回复 2楼 fall_bernana
谢谢大神解答!!!
1