python最简单的条件语句(4.学习python获取用户输入和while循环及if判断语句)python教程 / python条件语句和循环语句教程...

wufei123 发布于 2024-06-17 阅读(8)

0x00 Abstract在开发中为了增加程序与用户的互动性需要增加获取用户输入的功能,在python中可以使用input()函数来获取用户的输入当获取用户的各种输入后,我们需要使用逻辑语句来对数据进行处理,逻辑语句包含判断语句和循环语句。

在本次教程中介绍if判断语句,while循环语句,当然还有for循环语句,不过for语句我们在前面的教程中已经介绍过了前面我们在介绍python的编程是都是在python的解释器终端里输入,在本次教程中我们开始使用文件形式来编写代码,然后来执行该文件来查看编程结果。

0x01 使用input()函数input()函数的效果就是让程序暂停下来,等待用户的输入,然后将输入保存在变量中,这样程序后面的代码就可以来根据该变量进行各种处理了input()函数为了向用户提示信息,并获得用户的反馈来继续运行程序,下面我们来编写一个简单的程序命名为greeter.py,下面是完整代码:。

#!/usr/bin/python3name = input("Whats your name ? Please input:")print("Hello " + name + ", nice to meet you!

")

使用input()时,默认将用户的输入作为字符串,如果想把输入的内容转换为数字型变量就可以函数int()来将输入信息转换为数值形式,我们接下来继续完善该greeter.py源码:#!/usr/bin/python3

name = input("Whats your name ? Please input:")print("Hello " + name + ", nice to meet you!")now_age = 

input("How old are you now? Please input:")later_age = int(now_age) + 5print("Five years later you will 

"+ str(later_age) +" years old.")当增加了输入年龄的代码后,开始测试:corvin@workspace:~/python_tutorial$ ./greeter.py Whats your name ? Please input:

corvinHello corvin, nice to meet you!How old are you now? Please input:12Five years later you will 17 years old.

在对数值信息处理时,经常用到求模运算%,它将两个数相除并返回余数,下面来继续完善测试代码:#!/usr/bin/python3name = input("Whats your name ? Please input:

")print("Hello " + name + ", nice to meet you!")now_age = input("How old are you now? Please input:")

later_age = int(now_age) + 5print("Five years later you will "+ str(later_age) +" years old.")num = input

("Input test num :")print("The odd num is:" + str(later_age%int(num)))下面开始测试:corvin@workspace:~/python_tutorial$

 ./greeter.py Whats your name ? Please input:corvinHello corvin, nice to meet you!How old are you now? Please input:

23Five years later you will 28 years old.Input test num :5The odd num is:30x02 while循环(1)for循环是针对集合中的每一个元素进行遍历,while循环是不断的运行,直到指定的条件不满足才会停止运行,接下来编写while.py:

#!/usr/bin/python3 import timenow = input("Start counting down now, please input total time:")now = int

(now)while now > 0:print("now "+ str(now) + " seconds remaining...")    now -= 1    time.sleep(1)在这里我们import引用了一个time模块,使用了其中的sleep延时函数,运行效果如下:

corvin@workspace:~/python_tutorial$ ./while.py Start counting down now, please input total time:5now 5 seconds remaining...

now 4 seconds remaining...now 3 seconds remaining...now 2 seconds remaining...now 1 seconds remaining...

(2)除了这种while循环自动退出的情况,还可以根据用户的输入来选择退出,下面来完善代码,只有当用户输入quit时,才退出循环,否则是一直重复用户的输入:#!/usr/bin/python3import

 timenow = input("Start counting down now, please input total time:")now = int(now)while now > 0:print

("now "+ str(now) + " seconds remaining...")    now -= 1    time.sleep(1)prompt = "I will repeat it back to you(enter quit to end):

"msg = ""while msg != quit:    msg = input(prompt)print(msg)测试效果如下,只有当输入quit后程序才会退出:corvin@workspace:~/python_tutorial$

 ./while.py Start counting down now, please input total time:3now 3 seconds remaining...now 2 seconds remaining...

now 1 seconds remaining...I will repeat it back to you(enter quit to end):corvincorvinI will repeat it back to you(enter quit to end):

tomtomI will repeat it back to you(enter quit to end):jimjimI will repeat it back to you(enter quit to end):

hahahhahahI will repeat it back to you(enter quit to end):quitquit(3)使用标志的方式来同时检测多个条件,因为有多个条件时若全放在while的判断条件中会导致看起来很长,下面我们编写代码,当输入quit或exit,bye都可以退出循环:

#!/usr/bin/python3import timenow = input("Start counting down now, please input total time:")now = int

(now)while now > 0:print("now "+ str(now) + " seconds remaining...")    now -= 1    time.sleep(1)prompt = "

I will repeat it back to you(quit/exit/bye to end):"active = Truewhile active:    msg = input(prompt)

if msg == quit or msg == exit or msg == bye:        active = Falseelse:print(msg)下面是测试结果,当我们输入quit或者exit或bye时都可以退出while循环:

corvin@workspace:~/python_tutorial$ ./while.py Start counting down now, please input total time:1now 1 seconds remaining...

I will repeat it back to you(quit/exit/bye to end):corvincorvinI will repeat it back to you(quit/exit/bye to end):

quitcorvin@workspace:~/python_tutorial$ ./while.py Start counting down now, please input total time:1

now 1 seconds remaining...I will repeat it back to you(quit/exit/bye to end):sdfsdfI will repeat it back to you(quit/exit/bye to end):

exitcorvin@workspace:~/python_tutorial$ ./while.py Start counting down now, please input total time:1

now 1 seconds remaining...I will repeat it back to you(quit/exit/bye to end):bye(4)在某些条件下我们需要立刻退出while循环,并且循环中的后续代码不再继续执行,这里就需要break了,下面编写测试代码:

#!/usr/bin/python3import timenow = input("Start counting down now, please input total time:")now = int

(now)while now > 0:print("now "+ str(now) + " seconds remaining...")    now -= 1    time.sleep(1)prompt = "

I will repeat it back to you(quit/exit/bye to end):"active = Truecnt = 0while active:    cnt += 1if cnt > 5:

break;    msg = input(prompt)if msg == quit or msg == exit or msg == bye:        active = Falseelse:print

(msg)我在测试输入quit,exit或bye这些退出命令时,增加了一个计数标志,当输入的命令到达5次时即使没有输入退出的命令也会强制退出while循环,下面是测试效果:corvin@workspace

:~/python_tutorial$ ./while.py Start counting down now, please input total time:1now 1 seconds remaining...

I will repeat it back to you(quit/exit/bye to end):aaI will repeat it back to you(quit/exit/bye to end):

bbI will repeat it back to you(quit/exit/bye to end):ccI will repeat it back to you(quit/exit/bye to end):

ddI will repeat it back to you(quit/exit/bye to end):ee(5)使用while循环来处理列表和字典:可以使用while循环来处理列表中所有元素,现在有两个列表,一个是全局列表all_sheet,一个是new_sheet,现在可以使用while循环依次将new_sheet中元素加入到all_sheet中:

corvin@workspace:~/python_tutorial$ cat while_list.py #!/usr/bin/python3all_sheet = [apple, peach, watermelon

]new_sheet = [banana, orange]while new_sheet:    item = new_sheet.pop()print("get new item:" + item.title())

    all_sheet.append(item)print("now all sheet items are:")for all_item in all_sheet:print(all_item.title())

corvin@workspace:~/python_tutorial$ chmod +x while_list.py corvin@workspace:~/python_tutorial$ ./while_list.py 

get new item:Orangeget new item:Banananow all sheet items are:ApplePeachWatermelonOrangeBanana同样也可以使用while循环来填充字典,字典就是类似json格式的键值对信息,例如我们设计一个程序来收集每个人的年龄:

corvin@workspace:~/python_tutorial$ cat while_dict.py #!/usr/bin/python3info_dict = {}flag = Truewhile flag:

    name = input("Whats your name? ")    age = input("How old are you ? ")    info_dict[name] = age    repeat = input("

Continue ? (yes or no)")    if repeat == no:        flag = Falseprint("------ ALL INFO ------")for name, age in info_dict.items():

print("name: " +name + " ,age: " +age)corvin@workspace:~/python_tutorial$ chmod +x while_dict.py corvin@workspace

:~/python_tutorial$ ./while_dict.py Whats your name? corvinHow old are you ? 12Continue ? (yes or no)

yesWhats your name? TomHow old are you ? 23Continue ? (yes or no)yesWhats your name? WillHow old are you ? 

34Continue ? (yes or no)no------ ALL INFO ------name: Tom ,age: 23name: corvin ,age: 12name: Will ,age: 34

0x03 if语句(1)if语句是在编程中非常常见的逻辑判断语句,我们经常需要对各种变量进行判断是否符合某种条件然后做出相应的判断:corvin@workspace:~/python_tutorial$

 cat check_pwd.py #!/usr/bin/python3msg = "Please input passwd:"err_msg = "Input passwd error, please retry...

"ok_msg = "Congratulation, passwd ok"passwd = "CORVIN"pwd = input(msg)if pwd != passwd:print(err_msg)

else:print(ok_msg)corvin@workspace:~/python_tutorial$ chmod +x check_pwd.py corvin@workspace:~/python_tutorial$ 

./check_pwd.py Please input passwd:asdfInput passwd error, please retry...corvin@workspace:~/python_tutorial$

 ./check_pwd.py Please input passwd:corvinInput passwd error, please retry...corvin@workspace:~/python_tutorial$ 

./check_pwd.py Please input passwd:CORVINCongratulation, passwd ok需要注意在python中检查是否相等时要区分字符串的大小写的,如果要想不受到大小写的影响,我们就可以将输入的字符串统一变成大写字符或小写字符来统一进行判断即可。

(2)判断多个条件是否同时满足或者多个条件只有一个满足:corvin@workspace:~/python_tutorial$ cat if_and_or.py #!/usr/bin/python3apple_cnt = input("

Apple count:")orange_cnt = input("Orange count:")banana_cnt = input("Banana Count:")if int(apple_cnt) > 3 and int(orange_cnt) <=5:

print("Apple and Orange !")elif int(orange_cnt) > 3 or int(banana_cnt)<=5:print("Orange or banana !")

elif int(banana_cnt) > 8:print("Banana is your favorite!")else:print("Sorry...")corvin@workspace:~/python_tutorial$ 

chmod +x if_and_or.py corvin@workspace:~/python_tutorial$ ./if_and_or.py Apple count:4Orange count:5Banana Count:6

Apple and Orange !corvin@workspace:~/python_tutorial$ ./if_and_or.py Apple count:1Orange count:2Banana Count:3

Orange or banana !corvin@workspace:~/python_tutorial$ ./if_and_or.py Apple count:1Orange count:2Banana Count:9

Banana is your favorite!(3)使用if语句处理列表,在其中检查特殊的元素是否存在或者跟预期值匹配:corvin@workspace:~/python_tutorial$ cat if_list.py 

#!/usr/bin/python3fruit_list = [apple, orange, banana]fruit = input("Whats your favorite fruit?")for item 

in fruit_list:if fruit == item:print("OK, the list contain your fruit.")print("Check over!")corvin@workspace

:~/python_tutorial$ chmod +x if_list.py corvin@workspace:~/python_tutorial$ ./if_list.py Whats your favorite fruit?

corvinCheck over!corvin@workspace:~/python_tutorial$ ./if_list.py Whats your favorite fruit?orangeOK, the list contain your fruit.

Check over!(4)使用if来判断列表是不是空的,if不仅可以直接比较元素的大小,是否跟预期字符串匹配,我们还可以直接判断列表是否为空:corvin@workspace:~/python_tutorial$

 cat if_list.py #!/usr/bin/python3fruit_list = [apple, orange, banana]fruit = input("Whats your favorite fruit?

")for item in fruit_list:    if fruit == item:print("OK, the list contain your fruit.")print("Check over!

")name_list = []name = input("Whats your name?")if name_list:for item in name_list:if name == item:print

("Find you !")else:print("The name_list size:" + str(len(name_list)))print("Now add your name to name_list

")    name_list.append(name)print("Now name_list is:")for item in name_list:print(item)corvin@workspace

:~/python_tutorial$ ./if_list.py Whats your favorite fruit?bananaOK, the list contain your fruit.Check over!

Whats your name?corvinThe name_list size:0Now add your name to name_listNow name_list is:corvin0x04 Reference

[1].Eric Matthes 著 袁国忠 译. Python编程从入门到实践[M]. 北京:中国工信出版社 人民邮电出版社. 2017. 64-80,100-1130x05 Feedback大家在按照教程操作过程中有任何问题,可以关注ROS小课堂的官方微信公众号,在公众号中给我发消息反馈问题即可,我基本上每天都会处理公众号中的留言!当然如果你要是顺便给ROS小课堂打个赏,我也会感激不尽的,打赏30块还会邀请进ROS小课堂的微信群与更多志同道合的小伙伴一起学习和交流!

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

河南中青旅行社综合资讯 奇遇综合资讯 盛世蓟州综合资讯 综合资讯 游戏百科综合资讯 新闻92773