4.学习python获取用户输入和while循环及if判断语句

0x00 Abstract

在开发中为了增加程序与用户的互动性需要增加获取用户输入的功能,在python中可以使用input()函数来获取用户的输入。当获取用户的各种输入后,我们需要使用逻辑语句来对数据进行处理,逻辑语句包含判断语句和循环语句。在本次教程中介绍if判断语句,while循环语句,当然还有for循环语句,不过for语句我们在前面的教程中已经介绍过了。

前面我们在介绍python的编程是都是在python的解释器终端里输入,在本次教程中我们开始使用文件形式来编写代码,然后来执行该文件来查看编程结果。

0x01 使用input()函数

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

#!/usr/bin/python3

name =input("What's your name ? Please input:")

print("Hello" + name + ", nice to meet you!")

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

#!/usr/bin/python3

name =input("What's 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) + 5

print("Five years later you will"+str(later_age) +"years old.")

当增加了输入年龄的代码后,开始测试:

corvin@workspace:~/python_tutorial$./greeter.py

What's your name ? Please input:corvin

Hello corvin, nice to meet you!

How old are you now? Please input:12

Five years later you will 17 years old.

在对数值信息处理时,经常用到求模运算%,它将两个数相除并返回余数,下面来继续完善测试代码:

#!/usr/bin/python3

name =input("What's 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) + 5

print("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

What's your name ? Please input:corvin

Hello corvin, nice to meet you!

How old are you now? Please input:23

Five years later you will 28 years old.

Input test num :5

The odd num is:3

0x02 while循环

(1)for循环是针对集合中的每一个元素进行遍历,while循环是不断的运行,直到指定的条件不满足才会停止运行,接下来编写while.py:

#!/usr/bin/python3

importtime

now =input("Start counting down now, please input total time:")

now =int(now)

whilenow > 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:5

now 5 seconds remaining...

now 4 seconds remaining...

now 3 seconds remaining...

now 2 seconds remaining...

now 1 seconds remaining...

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

#!/usr/bin/python3

importtime

now =input("Start counting down now, please input total time:")

now =int(now)

whilenow > 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 = ""

whilemsg != 'quit':

msg =input(prompt)

print(msg)

测试效果如下,只有当输入quit后程序才会退出:

corvin@workspace:~/python_tutorial$./while.py

Start counting down now, please input total time:3

now 3 seconds remaining...

now 2 seconds remaining...

now 1 seconds remaining...

I will repeat it back to you(enter quit to end):corvin

corvin

I will repeat it back to you(enter quit to end):tom

tom

I will repeat it back to you(enter quit to end):jim

jim

I will repeat it back to you(enter quit to end):hahah

hahah

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

quit

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

#!/usr/bin/python3

importtime

now =input("Start counting down now, please input total time:")

now =int(now)

whilenow > 0:

print("now"+str(now) + "seconds remaining...")

now -= 1

time.sleep(1)

prompt = "I will repeat it back to you(quit/exit/byeto end):"

active = True

whileactive:

msg =input(prompt)

ifmsg == 'quit' or msg == 'exit' or msg == 'bye':

active = False

else:

print(msg)

下面是测试结果,当我们输入quit或者exit或bye时都可以退出while循环:

corvin@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):corvin

corvin

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

corvin@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):sdf

sdf

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

corvin@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/python3

importtime

now =input("Start counting down now, please input total time:")

now =int(now)

whilenow > 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 = True

cnt = 0

whileactive:

cnt += 1

ifcnt > 5:

break;

msg = input(prompt)

ifmsg == 'quit' or msg == 'exit' or msg == 'bye':

active = False

else:

print(msg)

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

corvin@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):a

a

I will repeat it back to you(quit/exit/byeto end):b

b

I will repeat it back to you(quit/exit/byeto end):c

c

I will repeat it back to you(quit/exit/byeto end):d

d

I will repeat it back to you(quit/exit/byeto end):e

e

(5)使用while循环来处理列表和字典:

可以使用while循环来处理列表中所有元素,现在有两个列表,一个是全局列表all_sheet,一个是new_sheet,现在可以使用while循环依次将new_sheet中元素加入到all_sheet中:

corvin@workspace:~/python_tutorial$cat while_list.py

#!/usr/bin/python3

all_sheet = ['apple', 'peach', 'watermelon']

new_sheet = ['banana', 'orange']

whilenew_sheet:

item = new_sheet.pop()

print("get new item:" + item.title())

all_sheet.append(item)

print("now all sheet items are:")

forall_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:Orange

get new item:Banana

now all sheet items are:

Apple

Peach

Watermelon

Orange

Banana

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

corvin@workspace:~/python_tutorial$cat while_dict.py

#!/usr/bin/python3

info_dict = {}

flag = True

while flag:

name = input("What's your name?")

age = input("How old are you ?")

info_dict[name] = age

repeat = input("Continue ? (yes or no)")

if repeat == 'no':

flag = False

print("------ ALL INFO ------")

forname, 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

What's your name?corvin

How old are you ?12

Continue ? (yes or no)yes

What's your name?Tom

How old are you ?23

Continue ? (yes or no)yes

What's your name?Will

How old are you ?34

Continue ? (yes or no)no

------ ALL INFO ------

name: Tom ,age: 23

name: corvin ,age: 12

name: Will ,age: 34

0x03 if语句

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

corvin@workspace:~/python_tutorial$cat check_pwd.py

#!/usr/bin/python3

msg = "Please input passwd:"

err_msg = "Input passwd error, please retry..."

ok_msg = "Congratulation, passwd ok"

passwd = "CORVIN"

pwd = input(msg)

ifpwd != 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:asdf

Input passwd error, please retry...

corvin@workspace:~/python_tutorial$./check_pwd.py

Please input passwd:corvin

Input passwd error, please retry...

corvin@workspace:~/python_tutorial$./check_pwd.py

Please input passwd:CORVIN

Congratulation, passwd ok

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

(2)判断多个条件是否同时满足或者多个条件只有一个满足:

corvin@workspace:~/python_tutorial$cat if_and_or.py

#!/usr/bin/python3

apple_cnt = input("Apple count:")

orange_cnt = input("Orange count:")

banana_cnt = input("Banana Count:")

if int(apple_cnt) > 3 and int(orange_cnt)

print("Apple and Orange !")

elif int(orange_cnt) > 3 or int(banana_cnt)

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:4

Orange count:5

Banana Count:6

Apple and Orange !

corvin@workspace:~/python_tutorial$./if_and_or.py

Apple count:1

Orange count:2

Banana Count:3

Orange or banana !

corvin@workspace:~/python_tutorial$./if_and_or.py

Apple count:1

Orange count:2

Banana Count:9

Banana is your favorite!

(3)使用if语句处理列表,在其中检查特殊的元素是否存在或者跟预期值匹配:

corvin@workspace:~/python_tutorial$cat if_list.py

#!/usr/bin/python3

fruit_list = ['apple', 'orange', 'banana']

fruit = input("What's your favorite fruit?")

foriteminfruit_list:

iffruit == 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

What's your favorite fruit?corvin

Check over!

corvin@workspace:~/python_tutorial$./if_list.py

What's your favorite fruit?orange

OK, the list contain your fruit.

Check over!

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

corvin@workspace:~/python_tutorial$cat if_list.py

#!/usr/bin/python3

fruit_list = ['apple', 'orange', 'banana']

fruit = input("What's your favorite fruit?")

foriteminfruit_list:

if fruit == item:

print("OK, the list contain your fruit.")

print("Check over!")

name_list = []

name = input("What's your name?")

ifname_list:

foriteminname_list:

ifname == 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:")

foriteminname_list:

print(item)

corvin@workspace:~/python_tutorial$./if_list.py

What's your favorite fruit?banana

OK, the list contain your fruit.

Check over!

What's your name?corvin

The name_list size:0

Now add your name to name_list

Now name_list is:

corvin

0x04 Reference

[1].Eric Matthes 著 袁国忠 译. Python编程从入门到实践[M]. 北京:中国工信出版社 人民邮电出版社. 2017. 64-80,100-113

0x05 Feedback

大家在按照教程操作过程中有任何问题,可以关注ROS小课堂的官方微信公众号,在公众号中给我发消息反馈问题即可,我基本上每天都会处理公众号中的留言!当然如果你要是顺便给ROS小课堂打个赏,我也会感激不尽的,打赏30块还会邀请进ROS小课堂的微信群与更多志同道合的小伙伴一起学习和交流!

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180620G224DL00?refer=cp_1026
  • 腾讯「云+社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 yunjia_community@tencent.com 删除。

扫码关注云+社区

领取腾讯云代金券