【Python编程从入门到实践】if语句、字典、while循环

第五章.if语句

if, else类似for循环,后面都要加上:

5.1 and or 逻辑运算符

car = "BMW"
print(car == "bmw") # 输出 False
print(car.lower() == "bmw") # 输出 True

if car == "1":
    print("Yes")
else:
    print("No")

age_0 = 22
age_1 = 18
if age_0 > 21 and age_1 > 21:
    print("Both > 21")
else:
    print("Someone <= 21")

if (age_0 > 21) or (age_1 > 21): # 可以加括号增强可读性
    print("Someone > 21")
else:
    print("Both <= 21")

5.2 in 检查特定值是否在列表中

requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings) # 输出 True

同理用not in 检查特定值是否不在列表中

banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
    print(user.title() + ", you can post a response if you wish")
# 输出 Marie, you can post a response if you wish

用途:在地图程序中,可能需要检查用户提交的位置是否包含在已知位置列表中;结束用户的注册过程前,可能需要检查他提供的用户名是否已包含在用户名列表中,而且通常会先把用户名转为全部小写后再去比较

5.3 if-elif-else结构

Python是if-elif-else结构 后面加:

C++是if-else if-else结构 后面加{}

digit = 12
if digit < 4:
    print("Your admission cost is $0.")
elif digit < 18:
    print("Your admission cost is $5.")
else:
    print("Your admission cost is $10.")

else是一条包罗万象的语句,只要不满足任何if或elif中的条件测试,其中的代码就会执行,所以如果知道最终要测试的条件,应考虑使用一个elif代码块来代替else代码块。这样可以肯定,仅当满足相应的条件时,你的代码才会执行

示例

# 披萨店点披萨
# requested_toppings = []
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
if requested_toppings:  # 列表非空时执行
    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!")
else:
    print("Are you sure you want a plain pizza?")

输出

Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.

Finished making your pizza!


第六章.字典

6.1 使用字典{ : , : }

使用字典可以让我们高校地模拟现实世界中的情形,如创建一个表示人的字典,然后可以存储信息:姓名、年龄、地址、职业以及要描述的任何方面

在Python中字典是一系列键-值对(类似C++中的map),任何python对象都可以作为字典中的值

访问字典中的值:指定字典名和放在方括号内的键

# 使用字典
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['points']) # 输出5

添加键-值对
字典是一种动态结构,可随时在其中添加键-值对
Python不关心键-值对的添加顺序,而只关心键和值之间的关联关系

alien_0 = {'color': 'green', 'points': 5}
print(alien_0['points']) # 输出5

alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0) # 输出 {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

6.2 删除键-值对del

使用del时,需要指定字典名和要删除的键

alien_0 = {'color': 'green', 'points': 5}
del alien_0['points']
print(alien_0)  # 输出 {'color': 'green'}

6.3 由类似对象组成的字典

# 由类似对象组成的字典
favorite_languages = {
    'jeny': 'Python',
    'sarah': 'c',
    'wilson': 'c++'
}
# 较长的print语句可分成多行
print("Wilson's favorite language is " +
      favorite_languages['wilson'].title()
      + ".")
# 输出 Wilson's favorite language is C++.

6.4 遍历字典 items()

Python遍历字典中的每个键-值对,并将键存在变量name中,将值存在变量language中

items()返回一个键-值对列表

# 遍历字典
favorite_languages = {
    'kevin': 'java',
    'jeny': 'python',
    'sarah': 'c',
    'wilson': 'c++',
}

for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " 
    + language.title() + ".")

6.4.1 遍历字典中所有的键 keys()或缺省

遍历字典时会默认遍历所有的键,所以把下面的for name in favorite_languages.keys():改成for name in favorite_languages:效果是一样的

favorite_languages = {
    'kevin': 'Java',
    'jeny': 'Python',
    'sarah': 'c',
    'wilson': 'c++',
}

for name in favorite_languages.keys():
    print(name.title())

方法keys()会返回dict_keys([ ])列表

print(favorite_languages.keys())  
# 输出 dict_keys(['kevin', 'jeny', 'sarah', 'wilson'])

6.4.2 按顺序遍历字典中的所有键sorted()

用方法sorted()

favorite_languages = {
   'kevin': 'Java',
   'jeny': 'Python',
   'sarah': 'c',
   'wilson': 'c++',
}

for name in sorted(favorite_languages.keys()):
   print(name.title()) 

输出

Jeny
Kevin
Sarah
Wilson

6.4.3 遍历字典中的所有值values()

favorite_languages = {
    'kevin': 'java',
    'jeny': 'python',
    'sarah': 'c',
    'wilson': 'c',
}

for language in favorite_languages.values(): # value可能重复
    print(language.title())

print("\nUsing set to remove duplicate values")
# 用set去重
for language in set(favorite_languages.values()): 
    print(language.title())

6.5 set用法{ }

set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。

set是无序无重复元素集合

要创建一个set,需要提供一个list作为输入集合:

set用add()和remove()方法增删元素

# set用法
arr = [1, 2, 2, 3, 3]
print(set(arr))  # 输出 {1, 2, 3}
b = set([1, 2, 2])
print(b)  # 输出 {1, 2}

b.add(7)
print(b)  # 输出 {1, 2, 7}
b.remove(7)
print(b)  # 输出 {1, 2}

把set转为list的方法

b = set([1, 2, 2])
print(b)  # 输出 {1, 2}
tt = list(b)
print(tt)  # 输出 [1, 2]

6.6 嵌套

有时我们需要将一系列字典存储在列表中,或者将列表作为值存储在字典中,这些都成为嵌套

如字典alien_0包含一个外星人的各种信息,但无法同时存储外星人的信息。此时我们可以创建一个外星人列表

# 创建一个用于存储外星人的空列表
aliens = []

# 创建30个绿色的外星人
for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)

for alien in aliens[0:3]:
    if (alien['color'] == 'green'):
        alien['color'] = 'red'
        alien['points'] = 15
        alien['speed'] = 'fast'

for alien in aliens[0:5]:
    print(alien)

print("...")

输出

{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...

我们经常需要再列表中包含大量的字典,比如做网站时,需要给每个用户创建一个字典,并将这些字典存储在一个名为users的列表中


第七章.用户输入和while循环

7.1 函数input()获取字符串输入

函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用

函数input()接受一个参数:即要想用户显示的提示或说明
相当于内置了一行print()但是不自动换行

prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "

name = input(prompt)
print("\nHello, " + name.title() + "!")

输出

If you tell us who you are, we can personalize the messages you see.
What is your first name? wilson79

Hello, Wilson79!

注意:如果你使用的是Python2.7,请使用raw_input()而不是input()来获取输入

7.2 函数int() 字符串转为数值

函数input()将用户输入解读为字符串
函数int()将数字字符串转为数值

age = input("How old are you? ")
age = int(age) # '22' to 22

函数float()将字符串转为浮点数

time = '2.3'
time = float(time)

7.3 while循环

你每天使用的程序很可能就包含while循环,比如游戏使用while循环,确保玩家在想玩的时候不断运行,并在玩家想退出时停止运行;终端按control+c终止运行

示例:让用户选择何时退出

# while循环
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "

message = ""
while message != 'quit':
    message = input(prompt)
    if (message != 'quit'):
        print(message)

7.3.1 使用标志

在游戏中,多种事件都可能导致游戏结束,如玩家一艘飞船都没有了或要保护的城市都被摧毁了。
在要求很多的条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活跃状态。这个变量成为标志
用True或False去表示状态的更改

7.3.2 break和continue

用法和C++类似

while循环要确保程序中至少有一个这样的地方能让循环条件为False或break

sublime text把内容输出到out.txt时,如果是死循环,会导致当前的txt会非常大,占用很大的内存,所以要及时终止程序

7.3.3 使用用户输入填充字典

创建一个调查报告,其中的循环每次执行时提示输入被调查者的名字和回答

# 使用用户输入来填充字典
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'):
        break

print("\n--- Poll Results ---")
for name, response in responses.items():
    print(name.title() + " would like to climb " + response.title() + ".")

输出


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? evil's thumbd
Would you like to let another person respond? (yes / no) no

--- Poll Results ---
Eric would like to climb Denali.
Lynn would like to climb Evil'S Thumbd.


写在最后:我的博客主要是对计算机领域所学知识的总结、回顾和思考,把每篇博客写得通俗易懂是我的目标,分享技术和知识是一种快乐 ,非常欢迎大家和我一起交流学习,有任何问题都可以在评论区留言,也期待与您的深入交流(^∀^●)

发布了232 篇原创文章 · 获赞 80 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_43827595/article/details/104293771
今日推荐