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

0x00 Abstract

0x01 使用input()函数

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

#!/usr/bin/python3

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

#!/usr/bin/python3

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

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

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

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)

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)

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)

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)

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循环来处理列表和字典：

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

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

#!/usr/bin/python3

info_dict = {}

flag = True

while flag:

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

How old are you ?12

Continue ? (yes or no)yes

How old are you ?23

Continue ? (yes or no)yes

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

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

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

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

Congratulation, passwd ok

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

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

（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

Check over!

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

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 = []

ifname_list:

foriteminname_list:

ifname == item:

print("Find you !")

else:

print("The name_list size:" + str(len(name_list)))

name_list.append(name)

print("Now name_list is:")

foriteminname_list:

print(item)

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

OK, the list contain your fruit.

Check over!

The name_list size:0

Now name_list is:

corvin

0x04 Reference

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

0x05 Feedback

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

2021-11-30

2021-11-30

2021-11-30

2018-04-18

2021-11-30

2021-11-30

2021-11-30

2021-11-30

2021-11-30