python-3.x - 如何使变量接受字符串
问题描述
我想让这段代码继续运行吗?我尝试将 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")
解决方案
循环的第一行可以有两种效果之一:要么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')
推荐阅读
- c# - Selenium WebDriver 不能在 IIS 10 上启动,但如果应用程序托管在 InProcess 上,则可以正常工作
- javascript - 从清单 json 动态更新 href/src 属性
- r - 使用 For 循环进行数据聚合
- android - 多个意图将 listView 信息从一个活动传递到另一个活动
- java - 如何修复字符串索引超出范围:-1
- php - 在laravel中搜索未定义的变量
- reactjs - Webpack 无法解析 ant 设计模块
- encryption - 使用 RSACryptoServiceProvider,如何将密钥交换密钥和签名密钥存储在同一个密钥容器中?
- python - 从 django 中的每个页面搜索
- react-native - React Native 获取服务器上未收到的 POST 变量