您的位置:首页 > 编程语言 > Python开发

Python入门到实践-用户输入和while循环

2020-06-01 05:26 1226 查看

python打卡第6天:用户输入和while循环☁
本文基于文献:Python编程:从入门到实践/(美)Eric Matths 著
最近时间紧任务重,决定暂时停更一段时间,期待完成任务后,重新打卡学习Python的那天。

用户输入和while循环

目录:
1 用户输入
2 while循环
3 练习

1. 用户输入
在python中,使用input()实现输入。input()的工作原理是让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存在一个变量中,方便我们使用。
需要注意的是:
1.1 input()函数不是导入文件,而是实现与用户交互的一种方式;
1.2 如果用户输入的是数字,而我们需要以数字的形式使用这个输入的话,需要用int()将文本形式 转换为数字形式;
示例:

#input/input获取数值输入
#编写一个程序,它判断一个人是否满足坐过山车的条件
height=input("How tall are you, in inches?")
height=int(height)

if height>=36:
print("\nYou are tall enough to ride!")
else:
print("\nYou'll be able to ride when you are a little taller.")

得到
1.3 处理数值信息时,%表示对两个数进行求余运算。
示例:

number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)

if number % 2 ==0:
print("\nThe number "+str(number)+" is even.")
else:
print("\nThe number "+str(number)+" is odd.")

输出:

2. while循环

2.1 for循环用于针对集合中的每个元素的一个代码块,而while循环不断运行,直到指定的条件不满足为止;
2.2 可以用

while variable !=‘something’#variable、something可修改
定义一个退出值,只要用户输入的不是这个值,就继续运行;
2.3 此外,可以使用标志控制while循环,例如定义一个变量variable,当满足某种条件时,variable=True继续运行,而满足另一条件时,variable=Flase停止运行;
2.3 执行到break退出循环,执行到continue从头开始循环。

3.练习:
test_7.4

#test_7.4
#披萨配料
#编写一个循环,提示用户输入一系列的披萨配料,并在用户输入'quit'时,结束循环;
#每当用户输入一种配料后,都打印一条消息,说我们会在披萨中加入这种配料。
message = "Please tell me what would you like to add on pizza."
ingreidents=''
active=True

while active:
ingreidents=input(message)

if ingreidents == 'nothing':
active=False
else:
print("We will add "+ingreidents+" to the pizza!")

输出:

test_7.8

#test_7.8
#水果店
#创建一个名为fruits的列表,在其中包含各种水果;
#再创建一个空列表。
#遍历fruits列表,对其中的每一种水果都打印一条消息,最后打印出水果单。
fruits = ['apple','banana','tomato','mango']
on_sale_fruits=[]

while fruits:
your_fruits=fruits.pop()
print("\nWe have "+your_fruits.title()+".")

on_sale_fruits.append(your_fruits)
print("\nYour order is : ")
for on_sale in on_sale_fruits:
print(on_sale.title())

输出:

参考文献:Python编程:从入门到实践/(美)Eric Matths 著

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: