首页 > 解决方案 > 如何使变量接受字符串

问题描述

我想让这段代码继续运行吗?我尝试将 x == 放到 str 中,但我认为这不是答案。

while True:
    x = int(input("Please enter an integer: 
"))

if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
        print('Zero')
elif x == 1:
        print('Single')
else:
    x == str :
        input("please enter a string")

标签: python-3.x

解决方案


循环的第一行可以有两种效果之一:要么x保证是 a int,要么你会提高 a ValueError。捕获错误并重新启动循环,或者继续执行主体,知道这x是一个int

while True:
    x_str = input("Please enter an integer: ")
    try:
        x = int(x)
    except ValueError:
        print("{} is not an integer; please try again".format(x))
        continue

    if x < 0:
        x = 0
        print('Negative changed to zero')
    elif x == 0:
        print('Zero')
    elif x == 1:
        print('Single')

推荐阅读