首页 > 解决方案 > 如何检查某些变量输入是否为特定类型

问题描述

我一直在尝试使我的简单代码工作并搜索不同的方法来检查使用 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,虽然我不完全确定代码是否有效。

标签: python

解决方案


age = int(input('How old are you? '))

在这里,该input函数始终返回一个字符串,并使用int()您将字符串输入转换为整数。所以,现在年龄是一个整数。因此,以下 if 条件将始终返回true

if isinstance(age, int):
    print('Please input a valid age')

因此,即使您的程序接收到有效输入,它最终也会要求有效输入。


推荐阅读