概述
学习内容:
1.if语句
2.用户输入和while循环
一.if语句
(1)1.简单的if语句:
格式:
if conditional_test:
do something
在第1行中,可包含任何条件测试,而在紧跟在测试后面的缩进代码块中,可执行任何操作。
如果条件测试的结果为True,Python就会执行紧跟在if语句后面的代码;否则Python将忽略这些代码。
例如:
age = 19
if age >= 18:
print("You are old enough to vote!")
运行结果为:
You are old enough to vote!
2.if-else语句:
经常需要在条件测试通过了时执行一个操作,并在没有通过时执行另一个操作;在这种情况下,可使用Python提供的if-else语句。
例如:
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
运行结果为:
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
3.if-elif-else语句:
Python只执行if-elif-else结构中的一个代码块(即if或elif或else中的为真语句),它依次检查每个条件测试,直到遇到通过了的条件测试。
例如:
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
运行结果为:
Your admission cost is $5.
也可以使用多个elif的代码块
例如:
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print("Your admission cost is $" + str(price) + ".")
运行结果为:
Your admission cost is $5.
同时模块中也可以省略else改用elif。
if-elif-else结构功能强大,但仅适合用于只有一个条件满足的情况:遇到通过了的测试后,Python就跳过余下的测试。这种行为很好,效率很高,让你能够测试一个特定的条件。
4.测试多个条件:
使用一系列不包含elif和else代码块的简单if语句。在可能有多个条件为True,且你需要在每个条件为True时都采取相应措施
时,适合使用这种方法。
例如:
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("nFinished making your pizza!")
运行结果为:
Adding mushrooms.
Adding extra cheese.
Finished making your pizza!
if-elif-else情况下:
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
elif 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
elif 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("nFinished making your pizza!")
运行结果为:
Adding mushrooms.
Finished making your pizza!
在俩者的对比之下,更易体会何时使用何种语句。
(2)使用if语句处理列表
1.检查列表中特殊元素:
例如:
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print("Adding " + requested_topping + ".")
print("nFinished making your pizza!")
运行结果为:
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!
这样就可以找出列表中的特殊元素。
2.确定列表不为空:
在if语句中将列表名用在条件表达式中时,Python将在列表
至少包含一个元素时返回True,并在列表为空时返回False。
例如:
requested_toppings = []
if requested_toppings:
print("nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
运行结果为:
Are you sure you want a plain pizza?
二.用户输入和while循环
(1)input()函数
1.input()函数原理:函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。
函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做。
例如:
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
运行结果为:
Tell me something, and I will repeat it back to you: Hello everyone!
Hello everyone!
2.使用int()来获取数值输入:
使用函数input()时,Python将用户输入解读为字符串。然后要得到我们需要的值(整型,浮点型等)就需要强制转换。
用法:int(input())
(2)while循环
1.首先循环是什么结构组成,其次如何使用循环,循环可以干什么。
循环结构:测试条件+循环体
例如:
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
运行结果:
1
2
3
4
5
以上为一个打印1到5的简单循环。
2.while循环break语句:
当程序执行遇到break时将会退出循环结构。
prompt = "nPlease enter the name of a city you have visited:"
prompt += "n(Enter 'quit' when you are finished.) "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!")
运行结果为:
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) New York
I'd love to go to New York!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) San Francisco
I'd love to go to San Francisco!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) quit
3.使用while循环处理列表和字典:
在列表之间移动元素
例如:
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
print("nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
输出结果为:
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
删除包含特定值的所有列表元素
例如:
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
运行结果为:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
使用用户输入来填充字典
例如:
responses = {}
polling_active = True
while polling_active:
name = input("nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
responses[name] = response
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
polling_active = False
print("n--- Poll Results ---")
for name, response in responses.items():
print(name + " would like to climb " + response + ".")
运行结果为:
What is your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes/ no) yes
What is your name? Lynn
Which mountain would you like to climb someday? Devil's Thumb
Would you like to let another person respond? (yes/ no) no
--- Poll Results ---
Lynn would like to climb Devil's Thumb.
Eric would like to climb Denali.
最后
以上就是淡淡白昼为你收集整理的python基础 (3)if 和 while的使用学习内容:一.if语句二.用户输入和while循环的全部内容,希望文章能够帮你解决python基础 (3)if 和 while的使用学习内容:一.if语句二.用户输入和while循环所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复