python - 如何检查某些变量输入是否为特定类型
问题描述
我一直在尝试使我的简单代码工作并搜索不同的方法来检查使用 if 语句时变量是否为某种类型
# Are you tall enough to ride the roller coaster
print('This will determine if you are able to ride this Rollar Coaster?')
age = int(input('How old are you? '))
if isinstance(age, int):
print('Please input a valid age')
elif age <= 12:
print('You are not old enough to ride this ride!')
else:
height = int(input('How tall are you? Enter in centimeters please: '))
if height > 72:
print('You may enter, enjoy the ride')
else:
print('You are not tall enough to ride.')
我搜索并搜索了堆栈溢出,我遇到了 isinstance 和 issubclass ,它们似乎不起作用。我也尝试过while != int
,虽然我不完全确定代码是否有效。
解决方案
age = int(input('How old are you? '))
在这里,该input
函数始终返回一个字符串,并使用int()
您将字符串输入转换为整数。所以,现在年龄是一个整数。因此,以下 if 条件将始终返回true
if isinstance(age, int):
print('Please input a valid age')
因此,即使您的程序接收到有效输入,它最终也会要求有效输入。
推荐阅读
- linux - wp-login.php 谷歌验证码验证
- google-chrome - chrome 上的网络通知限制
- python - 匹配组的数据框列中的数据模式的最佳方法?
- sql - 将 BY 子句分组到临时表
- elasticsearch - 用于审计跟踪的 Elasticsearch
- reactjs - 为什么我的 React 组件渲染多次
- events - 如何使用键盘事件调用绘图函数
- java - 如何使用带有 Java 的 AWS Lambda 使用 Google Drive API(Springboot)
- c# - 测试一个包含任务的普通 C# 函数
- python - 如何使用python更改Windows 10中的锁屏图像?