首页 > 解决方案 > 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。有人可以帮我这样做吗?

标签: python

解决方案


字符串按字典顺序比较,所以"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:

推荐阅读