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小课堂的微信群与更多志同道合的小伙伴一起学习和交流!

python输入end退出循环_4.学习python获取用户输入和while循环及if判断语句相关推荐

  1. 编写python程序、利用循环输出_Python基础编程—用户输入和while循环

    温馨提示 如果你喜欢本文,请分享到朋友圈,想要获得更多信息,请关注我. 函数input()的工作原理 函数input()让程序暂停运行,等待用户输入一些文本.获取用户输入后,Python将其存储在一个 ...

  2. Python学习笔记之用户输入

    1.函数input()的工作原理,函数input()让程序暂停运行,等待用户输入一些文本.获取用户输入后,Python将其存储在 一个变量中,以方便你使用. 示例代码如下: #用户输入input()简 ...

  3. Python编程:从入门到实践-第七章:用户输入和while循环(语法)

    #7-1 汽车租赁:编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,如"Let me see if I can find you a Subaru". ''' print ...

  4. python的输入函数是什么意思_在Python中,用于获取用户输入的函数是

    在Python中,用于获取用户输入的函数是 Whichofthefollowingmodernfarmtoolsaredevelopedbasedonpushsickle?A:Reaper.B:Gra ...

  5. 在python中用于获取用户输入的是-在Python中,用于获取用户输入的函数是

    在Python中,用于获取用户输入的函数是 Whichofthefollowingmodernfarmtoolsaredevelopedbasedonpushsickle?A:Reaper.B:Gra ...

  6. python 字符串输入时间_Python input()函数:获取用户输入的字符串

    input() 函数用于向用户生成一条提示,然后获取用户输入的内容.由于 input() 函数总会将用户输入的内容放入字符串中,因此用户可以输入任何内容,input() 函数总是返回一个字符串. 例如 ...

  7. 零基础学python多久可以工作-零基础学习python,要多久才可以学好并且找到工作?...

    原标题:零基础学习python,要多久才可以学好并且找到工作? 零基础的你想学习python肯定很关注学习python的最短时间是多久,怎样才能快速学习python等问题,今天就为大家详细地回答一下这 ...

  8. python 获取用户的一个输入值_Python中,用于获取用户输入的命令为:

    [多选题]以下关于机器学习说法正确的是? [判断题]Python内置函数sum____用来返回数值型序列中所有元素之和. [单选题]关于自定义函数的下列说法不正确的是: [判断题]Python内置函数 ...

  9. python用于获取用户输入的函数是_在Python函数中,用于获取用户输入的是( )...

    在Python函数中,用于获取用户输入的是( ) 答:input() 中国大学MOOC:\"骨质疏松症的特征是是以骨量减少.骨的微观结构退化,致使发生的严重后果是\"; 答:\&q ...

最新文章

  1. Django搭建个人博客(二)
  2. 用js取1-100的随机数
  3. 计算机论文北大核心,北大计算机(毕业论文).doc
  4. CBitMap的用法 from http://www.cnblogs.com/toconnection/archive/2012/08/04/mfc.html
  5. redhat Nginx 安装
  6. vue条件语句与循环语句的基本使用
  7. Kafka将逐步弃用对zookeeper的依赖
  8. mysql到底可不可以使用join_《Mysql 到底可不可以使用 Join ?》
  9. 使用 PHP Curl 做数据中转
  10. 设计模式之建造者(builder)模式
  11. Vdbench工具安装使用
  12. 计算机英文电子书分享
  13. ssb的有效性最好_在AM、DSB、SSB、VSB四个通信系统中,有效性最好的通信系统()。...
  14. console连接h3c s5500_H3C交换机、路由器Console和Telnet密码配置
  15. java获取唯一序列号,Android 获取本机唯一序列号 和可变UUID方法
  16. html5 cms结构,cms产品架构图.html
  17. Android SDKManger 更新设置
  18. 微信小程序开发:调用百度文字识别API实现图文识别
  19. 破解系统登录密码与软件密码
  20. 极简 ssh之 scp

热门文章

  1. 使用spring jdbc的batchUpdate功能提高性能
  2. Apache2.2.21安装图解
  3. PowerDesigner反向工程 mysql
  4. Linux IPC实践(13) --System V IPC综合实践
  5. net core 中间件(MiddleWare)
  6. HashMap 排序
  7. zabbix邮件报警配合logging模块排错的python脚本
  8. JavaScript 总结几个提高性能知识点(转)
  9. java jre 1.6 32位_jre1.6官方下载-java jre1.6(虚拟机运行环境)下载官方版(含32位/64位)-当易网...
  10. mysql删除unionkey_MySQL索引如何优化?二十条铁则送给你