一. 变量
1、变量
变量的命名和使用:
- 变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头。例如,可将变量命名为message_1,但不能将其命名为1_message。
- 变量名不能包含空格,但可使用下划线来分隔其中的单词。
- 不要将Python关键字和函数名用作变量名。
- 变量名应既简短又具有描述性。
- 慎用小写字母l和大写字母O,因为它们可能被人错看成数字1和0。
2、数据类型
a. 字符串
字符串就是一系列字符。在Python中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号。
常用API:
- 字符大小写API
-
- title():将每个单词的首字母都改为大写
- upper():将字符串全部大写
- lower():将字符串全部小写
- 去除字符串空格API
-
- rstrip():去掉字符串右端的空格。并没有改变源字符串,如果需要去除源字符串的空格,在使用此API之后,需要将结果重新赋给变量。
- lstrip():去掉字符串左端的空格。
- strip():去掉字符串左右两端的空格。
- 使用str()避免类型错误
# 下面代码会报错:TypeError: can only concatenate str (not "int") to str
age = 23
print("Happy" + age + "rd Birthday!")
# 将age转换成字符串类型
age = 23
print("Happy" + str(age) + "rd Birthday!")
使用制表符(“\t”)或换行符(“\n”)来添加空白
b. 数字
整数:
- Python使用两个乘号表示乘方运算:3 ** 2 = 9
- Python 2中,整数除法的结果只包含整数部分,小数部分被删除。请注意,计算整数结果时,采取的方式不是四舍五入,而是将小数部分直接删除。若要避免这种情况,务必确保至少有一个操作数为浮点数,这样结果也将为浮点数。
浮点数:
- 结果包含的小数位数可能是不确定的
3、注释
单行注释用 井号(#)标识
4、格式设置
PEP 8:请访问https://python.org/dev/peps/pep-0008/,阅读PEP 8格式设置指南。
- 缩进:建议每级缩进都使用四个空格,这既可提高可读性,又留下了足够的多级缩进空间。
- 行长:建议每行不超过80字符。还建议注释的行长都不超过72字符。
- 空行:如果你有5行创建列表的代码,还有3行处理该列表的代码,那么用一个空行将这两部分隔开是合适的。
二、if语句
1、条件测试
- 检查多个条件:and(并且)、or(或者)
- 检查是否包含特定值:in(包含)、not in(不包含)
- 布尔表达式:True、False
2、if语句结构
- 检查超过两个的情形,使用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.")
- 而在其他一些情况下,使用一条elif语句来处理特定的情形更清晰,这时可以省略else代码块。
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print("Your admission cost is $" + str(price))
- for语句结合if语句
available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding," + requested_topping + ".")
else:
print("Sorry,we don't have " + requested_topping + ".")
print("\nFinished making your pizza.")
三、While循环
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志,充当了程序的交通信号灯。
prompt = "\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
# 定义标志
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
1、input() & int()
input()函数:让程序暂停运行,等待用户输入一些文本。获取用户输入后,将其存储在一个变量中,以方便你使用。如果你使用的是Python 2.7,请使用raw_input()而不是input()来获取输入。
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 + "!")
int()函数:将用户输入的数字,转换成数字类型并在后续的程序中使用这个输入的数字。
age = input("How old are you?")
age = int(age)
if age > 0 and age < 18:
print("你还没有成年哦!")
elif age >= 18:
print("您已经成年了哦!")
else:
print("输入的年龄不正确!")
2、break & continue
break语句可以立即退出while,不再运行循环中余下的代码,也不管条件测试的结果如何。
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() + "!")
continue 跳出本次循环,直接进入下一轮循环。
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
3、while处理列表和字典
a. 移动列表中的元素
在列表中移动元素:假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户后,将他们移到另一个已验证用户列表中。
# 首先创建一个待验证用户列表和一个存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candance']
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 user in confirmed_users:
print(user.title())
b. 删除列表中的元素
假设有一个宠物列表,其中包含多个值为'cat'的元素。要删除所有这些元素,可不断运行一个while循环,直到列表中不再包含值'cat'。
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
c. 用户输入填充字典
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 you like to climb " + response + ".")