(四)用户输入与if语句

199 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

用户输入--函数input()

函数input()让程序暂停运行,提示用户根据需求输入信息,等待用户输入一些文本后, 将该文本赋值给一个变量,然后继续运行后面的程序。

name = input("Please enter your name:")
print(f"Hello,{name.title()}!")
=========================================================

输出:
Please enter your name:lisa
Hello,Lisa!

需要注意的是,python会将input()函数中用户输入解读为字符串,这时如若要进行数值比较,则会报错,此时只需要用int()将字符串转化为数值即可。

if语句

最简单的if语句,只有一个测试和一个操作。第一行可包含任何条件测试,而紧跟在测试后面的缩紧代码块中,可执行任何操作。如果条件代码的测试结果为True,python就会执行if语句后的代码。(条件测试其实就是布尔表达式的别称,布尔表达式的结果就是要么为True,要么为False。

下面就是一个简单的if语句:

score = input("Please enter your score:")
score = int(score)
if score >= 60:
    print("Congratulations! you are qualified")
=======================================================    
    
输出:    
Please enter your score:70
Congratulations! you are qualified

上面是成绩合格的情况,那么成绩不合格却没有可以执行的操作,这种情况下可以使用if- else语句。

if-else语句

else语句让你能够指定条件测试未通过时要执行的操作。如下:

score = input("Please enter your score:")
score = int(score)
if score >=  60:
    print("Congratulations! you are qualified")
else:
    print("Not qualified")
=============================================================

输出:
Please enter your score:59
Not qualified

但是当需要检查超过两个的情形,就需要用到if-elif-else语句。

if-elif-else语句

python只执行if-elif-else结构中的一个代码块,它依次检查每个条件测试,直到遇到通过了的测试,测试通过后,python将执行紧跟在他后面的代码,并跳过余下测试。

score = input("Please enter your score:")
score = int(score)
if 90 < score <= 100:
    print('A')
elif 80 < score <= 90:
    print('B')  
elif 70 < score <= 80:
    print('C')    
elif 60 < score <= 70:
    print('D')
else:
    print('E')
===================================================    
输出:
Please enter your score:87
B