python - Python Elif 语句
问题描述
print("What is your age ?")
myAge = input()
if myAge <= "21" and myAge >= "18":
print("You are allowed to drive !")
elif myAge > "21":
print("You are too old to drive !")
elif myAge < "18":
print("You are too young to drive !")
我想问一下上面的python代码是否有问题?每当我输入一些小于 18 的数字时,就会出现“你太老不能开车了!”的消息。尽管数字小于 18,但仍会出现。
使用这些代码行,我想创建一个程序,这样,每当我输入任何小于 18 的数字时,都会显示一条消息“你太年轻了,不能开车!” elif
在 python 中出现 using statements。有人可以帮我这样做吗?
解决方案
字符串按字典顺序比较,所以"2"
through"9"
都大于"18"
,因为只有第一个字符 ,"1"
与它们进行比较。您需要将用户输入转换为int
并执行整数比较,例如:
print("What is your age ?")
myAge = int(input()) # Convert user input to int
if myAge <= 21 and myAge >= 18:
print("You are allowed to drive !")
elif myAge > 21:
print("You are too old to drive !")
elif myAge < 18:
print("You are too young to drive !")
您还可以(完全可选)稍微简化第一个测试;Python 允许链式比较,因此它是等效的,可读性稍高(并且代码速度无限快)来测试:
if 18 <= myAge <= 21:
推荐阅读
- javascript - 查找数组中最接近的较小值
- javascript - 我的删除按钮功能有什么问题 - 反应
- python - Python tkinter 文本到边界问题
- android - 滚动已在 scichart android 中绘制的折线图时如何修复延迟
- javascript - 根据 ID 存在的特定性别数据拆分组合列表
- grails - 为什么类名长度为一时,生成的控制器中没有注入服务?
- python - 将每个元组与元组列表中的下一个元组合并
- python - 从数据框中绘制数据以更好地理解它 - Pandas,matplotlib
- python - 在 Python 中生成所有 4 位唯一代码
- php - 我通过路由将 id 从视图传递到控制器,因为它我的另一个视图没有获取 js 和 css 文件