赞
踩
Python一直没太学好,现在有机会了一定要自己来一遍和大佬们一起学习
简单的示例程序:
一定要动手写
变量名字只能包含字母、数字、下划线!
只能以字母或者下划线打头,不能以数字打头,变量名不能包含空格
message = "I am learning Python"
print(message)
message = "We are learning Englishi as well"
print(message)
name = 'richard lu'
print(name.title()) # 将字符串对象每个单词第一个字母大写
print(name.upper()) # 将字符串对象每个单词都大写
print(name.lower()) # 将字符串对象每个单词都小写
# 不会改变源字符串的内容
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name.title())
print(f"Hello {full_name.title()}!")
# 要在字符串中插入变量的值,可在前引号前加上字母 f ,再将要插入的变量放在花括号内。这样,当Python 显示字符串时,将把每个变量都替换为其值
# 还可以使用f字符串来创建消息,再把整个消息赋给变量
message = f"Hello {full_name.title()}!"`
print(message)`
print(f"\t {message}")`
print("languages:\nPython\nC\nJavascript")`
favorite_language = 'Python '
print(favorite_language.rstrip())
favorite_language = favorite_language.rstrip()
print(favorite_language)
# strip()方法消除两边的空格
# lstrip()方法消除前面的空格
# rstrip()方法消除后面的空格
bicycles = ['trek', 'cannonade', 'redline', 'specialized']
print(bicycles)
print(bicycles[-1].title())
message = f"My first vehicle is a {bicycles[0].title()}!"
print(message)
# 修改列表元素 bicycles[0] = 'bike' print(bicycles) # 添加列表元素(单引号和双引号在这里都可以,不做区分) bicycles.append("car") print(bicycles) # 在列表中插入新的元素 bicycles.insert(0, "train") print(bicycles) # 在列表中删除特定下标的元素 del bicycles[0] print(bicycles) # 使用方法pop()删除元素 # pop()删除列表末尾的元素,并让你能够接着使用它。 popped_motorcycle = bicycles.pop() print(popped_motorcycle) print(bicycles) print(f"I'd like to have a new {popped_motorcycle.title()}!") # 根据列表中的值删除元素 bicycles.remove("car") print(bicycles)
# 使用方法sort()对列表进行永久排序 cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort() print(cars) cars.sort(reverse=True) # 逆序 print(cars) # 使用函数sorted()对列表临时排序 print("original list:") print(cars) print("sorted list") print(sorted(cars)) print("original list") print(cars) # 列表逆置 cars.reverse() print(cars) # 确定列表的长度 print(len(cars))
# for循环
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next show {magician.title()}!\n")
print("Thank you, everyone. That was a great magic show!")
# 使用函数range() 经典差一思想 即输出1234 for value in range(1, 5): print(value) # 使用range()创建数值列表 numbers = list(range(1, 6)) print(numbers) even_numbers = list(range(2, 11, 2)) # range()可以指定步长 print(even_numbers) # 创建1-10的平方的列表 squares = [] for value in range(1, 11): squares.append(value ** 2) print(squares) # 对数字列表执行简单的统计计算 digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(min(digits)) print(max(digits)) print(sum(digits)) # 列表解析:将for循环和创建新元素的代码合并成一行,并自动附加新元素 squares = [value ** 2 for value in range(1, 11)] print(squares)
# 切片:仍然是一个列表 players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3]) print(players[1:4]) print(players[:4]) print(players[2:]) print(players[-3:]) # 遍历切片 print("Here are the first three players on my team:") for player in players[:3]: print(player.title()) # 复制列表(两个列表各自占有各自的内存空间) my_foods = ['pizza', 'felafel', 'carrot cake'] friend_foods = my_foods[:] print("My favorite foods are:") print(my_foods) print("\nMy friend's favorite foods are:") print(friend_foods) my_foods.append("shit") friend_foods.append("rice") print("My favorite foods are:") print(my_foods) print("\nMy friend's favorite foods are:") print(friend_foods)
# 错误示范:复制列表
my_foods = ['pizza', 'felafel', 'carrot cake']
friend_foods = my_foods
# 这种语法实际上是让Python将新变量friends_foods关联到已经与my_foods相关联的列表,因此这两个变量指向同一个列表。有鉴于此,当把'shit'添加到my_foods中时,他也将出现在friend_foods中。同样,虽然'ice rice'好像只被加入到了friend_foods中,但他也将出现在这两个列表中
列表适合存储在程序运行期间可能变化的数据集。列表是可以修改的
Python 将不能修改的值称为不可变的,而不可变的列表称为元组
元组看起来很像列表,但使用圆括号而非中括号来标识。定义元组后,就可以使用索引来访问其元素,就像访问列表元素一样
# 访问元组的值 dimensions = (200, 50) print(dimensions) print(dimensions[0]) #如果定义只包含一个元素的元组,必须在这个元素后面加上逗号 my_t = (3,) print(my_t) #遍历元组 for dimension in dimensions: print(dimension) #修改元组变量 print("Original dimensions:") for dimension in dimensions: print(dimension) dimensions = (400, 100) print("\nModified dimensions:") for dimension in dimensions: print(dimension)
# 简单的实例-----注意冒号的问题
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies")
answer = 17
if answer != 43:
print("That is not the correct answer.Please try again!")
# 检查特定值是否包含在列表之中
# 使用关键字 in / not in检查特定值是否包含在列表中 requested_toppings = ['mushrooms', 'onions', 'pineapple'] if 'mushrooms' in requested_toppings: print("Wow It's in it") if 'pepperoni' not in requested_toppings: print("It's not in it") banned_users = ['andrew', 'carolina', 'david'] user = 'marie' if user not in banned_users: print(f"{user.title()}, you can post a response if you wish.") # if-else结构: age = 17 if age >= 18: print("You're old enough to vote!") print("Have you registered to vote yet?") else: print("Sorry, you're too young to vote.") print("Please register to vote as soon as you turn 18!") # if-elif-else结构: if age < 4: print("Your admission cost is $0.") elif age < 18: print("Your admission cost is $25.") else: print("Your admission cost is $40.") # 简洁版 if age < 4: price = 0 elif age < 18: price = 25 else: price = 40 print(f"Your admission cost is ${price}.")
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(f"Adding {requested_topping}.")
print("\n Finished making your pizza")
# 判断列表是否为空
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print(f"Adding {requested_topping}.")
print("\nFinished making you pizza")
else:
print("Are you sure you want a plain pizza?")
# 两个列表交叉
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(f"Adding {requested_topping}")
else:
print(f"Sorry, we don't have {requested_topping}")
print("\nFinished making your pizza.")
# 这里应该是不区分大小写的
alien_0 = {"color": "green",
"points": 5}
print(alien_0["color"])
print(alien_0["points"])
# 在字典中新加入键值对 alien_0["x_position"] = 0 alien_0["y_position"] = 25 print(alien_0) # 日常使用时,可以先定义空的字典,再通过逻辑一步一步加入新的键值对 alien_0 = {} alien_0['color'] = 'green' alien_0['points'] = 5 print(alien_0) # 修改字典中的值 alien_0['color'] = 'yellow' print(f"The alien is now {alien_0['color']}.") # 加入了if判断的小综合 alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'} print(f"Original position: {alien_0['x_position']}") # 向右移动外星人 # 根据当前速度确定将外星人向右移动多远 if alien_0['speed'] == 'slow': x_increment = 1 elif alien_0['speed'] == 'medium': x_increment = 2 else: #这个外星人的移动速度肯定很快 x_increment = 3 alien_0['x_position'] = alien_0['x_position'] + x_increment print(f"New position: {alien_0['x_position']}") # 删除键值对 注意:删除的键值对会永远消失 alien_0 = {'color': 'green', 'points': 5} print(alien_0) del alien_0['points'] print(alien_0) # 由类似对象组成的字典:可以比较方便的去获取每个人的信息 favorite_language = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } print(favorite_language) language = favorite_language['sarah'].title() print(f"Sarah's favorite labguage is {language}.") # 使用get()来访问值 alien_0 = {'color': 'green', 'speed': 'slow'} # get()的第一个参数用于指定键,是必不可少的;第二个参数为指定的键不存在时要返回的值,是可选的 point_value = alien_0.get('points', 'No point value assigned') print(point_value)
# 遍历所有键值对 user_0 = { 'username': 'efermi', 'first': 'enrico', 'last': 'fermi', } for key, value in user_0.items(): print(f"\nKey: {key}") print(f"Value: {value}") for name, language in favorite_language.items(): print(f"{name.title()}'s favorite language is {language.title()}") # 遍历字典中的所有键 # 方法keys()返回一个列表,其中包含字典中的所有键 friends = ['phil', 'sarah'] for name in favorite_language.keys(): print(f"Hi {name.title()}.") if name in friends: language = favorite_language[name].title() print(f"\t{name.title()}, I see you love {language}!") if 'erin' not in favorite_language: print("Erin, please take our poll!") # 遍历字典中的所有值 # 通过对包含重复元素的列表调用set(),可以让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合 print("The following languages have been mentioned:") for language in set(favorite_language.values()): print(language.title()) # 可以使用一对花括号直接创建集合,并在其中用逗号分隔元素 # 集合和字典很容易混淆,因为他们都是用一对花括号定义的。当花括号内没有键值对时,定义的很可能是集合。不同于列表和字典,集合不会以特定的顺序存储元素 languages = {'python', 'ruby', 'python', 'c'} print(languages)
# 字典列表(将字典嵌套在列表之中) alien_0 = {'color': 'green', 'position': 5} alien_1 = {'color': 'yellow', 'position': 10} alien_2 = {'color': 'red', 'position': 15} aliens = [alien_0, alien_1, alien_2] for alien in aliens: print(alien) # 创建一个用于存储外星人的空列表 aliens = [] # 创建30个绿色的外星人 for alien_number in range(0, 30): new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} aliens.append(new_alien) # 显示前5个外星人 for alien in aliens[0:5]: print(alien) print("...") # 显示创建了多少个外星人 print(f"Total number of aliens: {len(aliens)}") for alien in aliens[:3]: if alien['color'] == 'green': alien['color'] = 'yellow' alien['speed'] = 'medium' alien['points'] = 10 elif alien['color'] == 'yellow': alien['color'] = 'red' alien['speed'] = 'fast' alien['points'] = 15 for alien in aliens[:5]: print(alien) print("...") # 在字典中存储列表 # 存储pizza信息 pizza = { 'crust': 'thick', 'toppings': ['mushrooms', 'extra cheese'], } # 概述所点的披萨 print(f"You ordered a {pizza['crust']}-crust pizza " "with the following toppings:") for topping in pizza['toppings']: print("\t" + topping) # 在字典中存储字典 users = { 'aeinstein': { 'first': 'albert', 'last': 'einstein', 'location': 'princeton', }, 'mcurie': { 'first': 'marie', 'last': 'curie', 'location': 'paris', } } for username, user_info in users.items(): print(f"\nUsername: {username}") full_name = f"{user_info['first']} {user_info['last']}" location = user_info['location'] print(f"\tFull name: {full_name.title()}") print(f"\tLocation: {location.title()}") ``
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。