Python笔记


# ***********************************变量、方法**********************************#
# 变量的命名规则:
# 1. 有字母、数字、下划线(不可使用空格)构成;
# 2. 避免使用Python关键字;
# 3. 名字有描述意义,变量命名单词之间可用下划线分隔;
# 4. 避免使用字母与l和字母o。


# ************************************字符串***********************************#
message="hello Python World!"
# 首字母大写
print(message.title())
# 字母大写
print(message.upper())
# 字母小写
print(message.lower())

# 字符串
message="    rstrip    "
# 去除右边空格
print(f"{message.rstrip()}"+'end')
message="    lstrip    "
# 去除左边空格
print(f"{message.lstrip()}"+'end')
message="    strip    "
# 去除两边空格
print(f"{message.strip()}"+'end')

# ******************************数 (整型&浮点型)******************************#
# 整型
print(5+4)
print(9-1)
print(2*4)
# 浮点型
print(0.1*2)
# 这是所有语言都存在的问题,所以在进行浮点型计算时需控制小数点后位数
print(0.1+0.2)
print(0.1*3)

# 除法计算保存浮点型 使用int方法转为整型
print(16/2)
print(int(16/2))


# ***********************************常量**************************************#
# 将大写视为常量
MAX_CONNECTIONS=1000000


# ********************************python编码法则********************************#
import this
# Beautiful is better than ugly.
# Explicit is better than implicit.
# Simple is better than complex.
# Complex is better than complicated.
# Flat is better than nested.
# Sparse is better than dense.
# Readability counts.
# Special cases aren't special enough to break the rules.
# Although practicality beats purity.
# Errors should never pass silently.
# Unless explicitly silenced.
# In the face of ambiguity, refuse the temptation to guess.
# There should be one-- and preferably only one --obvious way to do it.
# Although that way may not be obvious at first unless you're Dutch.
# Now is better than never.
# Although never is often better than *right* now.
# If the implementation is hard to explain, it's a bad idea.
# If the implementation is easy to explain, it may be a good idea.
# Namespaces are one honking great idea -- let's do more of those!

# ******************************列表******************************#
bicycles=['trek','cannondale','redline','specialized','test']
print(bicycles)
# 列表尾追加元素
bicycles.append('test')
print(bicycles)
# 列表规定个位置插入元素
bicycles.insert(1,'second')
print(bicycles)
# 删除列表指定位置元素
del bicycles[1]
print(bicycles)
# 删除列表指定索引元素并返回索引信息
bicycles_pop=bicycles.pop(1)
print(bicycles)
# 删除列表中的指定数据
print(bicycles_pop)
bicycles.remove('trek')
print(bicycles)

# ******************************列表排序******************************#
# 排序(按照字母顺序)
bicycles.sort(reverse=True)
print(bicycles)
# 临时排序(列表本身不改变)
print(sorted(bicycles))
# 倒序排序
bicycles.reverse()
print(bicycles)
# 列表长度
print(len(bicycles))

# ******************************列表循环   for循环******************************#
# 操作列表  遍历列表
for bicycle in bicycles:
	print(f"{bicycle.title()},that was s great bicycle!")
print("\nThank you, everyone,that's a very pretty show!")
print(f"{bicycle.title()},that was s great bicycle!")

# 创建数
numbers =range(1,6)
print(numbers)
# 生成数列表
numbers =list(numbers)
print(numbers)
for value in numbers:
 	print(value)

# 生成偶数列表
numbers=list(range(2,11,2))
print(numbers)
for value in numbers:
	# 数的平方
	print(value**2)


# ******************************数列表******************************#
digits=[2,21,45,77,1009,0,3,78]
# 长度
print(len(digits))
# 最小值
print(min(digits))
# 最大值
print(max(digits))
# 求和
print(sum(digits))
# 切片  创建一个切片副本
print(digits[1:])
# 遍历切片
for digit in digits[:3]:
	print(digit)
# 复制列表
digits_s=digits[:]
print(digits_s)
# 这种复制方法是错误的,是将digits的值赋值给digits_s而不是副本
digits_s=digits
print(digits_s)





# ******************************定义元组******************************#
dimensions=(1,2,3,4,5)
print(dimensions[2])
# 这种方式是错误的dimensions[0]=100
# 给元组重新赋值是合法的
dimensions=(1,2)
print(dimensions)

# ******************************if语句******************************#
age = 18
if age == 18:
	print("永远18岁!")

age_1 = 19
age_2 = 23
if age_1 >= 18 and age_2 >= 18:
	print("你们已经是个成年人了!")
if age_1 >= 18 or age_2 >= 18:
	print("你们其中有一位已经成年了!")
# 检查特定的值是否在列表中
requested_toppings=['mushrooms','onions','pineapple']
if 'mushrooms' in requested_toppings:
	print('mushrooms在列表中。')
# 检查特定的值不在列表中
if "potatoes" not in requested_toppings:
	print("potaoes不在列表中")

# if-else
if age >= 18:
	print("You are old enough to vote!")
else:
	print('You are so young to vote.')
#  if-elif-else  else 可以省略
if age < 4:
	print("Your adminssion cost is $0.")
elif age < 18:
	print("Your adminssion cost is $25.")
else:
	print("Your adminssion cost is $40.")


# ******************************字典********************************#
# 一个简单的字典
alien_0={"color":"green","points":5}
print(alien_0["color"])
print(alien_0["points"])
print(alien_0)
# 添加键值对
alien_0["x_position"]=0
alien_0["y_position"]=25
alien_0["z_position"]=0

print(alien_0)
# 删除键值对
del alien_0["points"]
print(alien_0)

favorite_languages={
	'jen':'python',
	'sarah':'c',
	'edward':'ruby',
	'phil':'python',
}
print(favorite_languages.get('lee','不存在这个值。'))
# ******************************遍历字典*******************************#
# 遍历键值对
for key,value in alien_0.items():
	print(f"\nKey:{key}")
	print(f"Value:{value}")
 # 遍历所有的键
for key in alien_0.keys():
 	print(f"Key:{key}")
# 按特定顺序遍历键
for key in sorted(alien_0.keys()):
 	print(f"Key:{key}")
# 遍历所有的值 
for value in alien_0.values():
 	print(f"Value:{value}")
# 使用set剔除重复的值
print(set(alien_0.values()))



# ******************************嵌套******************************#

# 列表中存储字典
# 初始化30个同样的外星人
aliens=[];
for alien_number in range(30):
	print(alien_number)
	new_alien={"color":"yellow","points":5,"speed":"slow"};
	aliens.append(new_alien);
# 将前三个外星人改为绿色 分值为10分,速度中等

for alien in aliens[:3]:
	alien["color"]="green";
	alien["points"]=10;
	alien["speed"]="medium";
print(aliens[:3])

for alien in aliens:
	if alien["color"]=="green":
		alien["color"]="yellow";
		alien["points"]=5;
		alien["speed"]="slow";
	elif alien["color"]=="yellow":
		alien["color"]="red";
		alien["points"]=15;
		alien["speed"]="fast";
print(aliens)

# 字典中存储列表
pizza={
"crust":"thick",
"toppings":["mushrooms","extra cheese"]
}
print(pizza)

# 在字典中存储字典
user={
	"aeinstein":{
		"first":"albert",
		"last":"einstein",
		"location":"princeton"
	},
	"mcurie":{
		"first":"marie",
		"last":"curie",
		"location":"paris"
	}
}


# ******************************用户输入******************************#
# 使用终端运行  提示用户输入
message =input('Tell me sonmething,I will repeat it back to you: ')
print(message)
height=input("How tall are you,in inches?    ") 

height=int(height)
if height >=48:
	print("\nYou're tall enough to ride.")
else:
	print("\nYou'll be able to ride when you're a little order.")




# ******************************求模运算符  %******************************#
# 求模运算符  求余数  用于判断奇偶数
print(4%2)
print(4%3)



# ****************************** while循环******************************#
# 条件循环 当用户输入quit时退出程序
prompt="Tell me something, and I will repeat it back to you."
prompt+="\nEnter 'quit' to end program."
messgae=""
while message!="quit":
	message=input(prompt);
	print(message)

# 使用break退出循环
# 使用continue退出本次循环
# 出现无限循环  使用Ctrl+C关闭

# 使用while循环处理列表和字典————在列表中移动元素
unconfirmed_users=["alice","brain","cabdance"]
confirmed_users=[]
while unconfirmed_users:
 	current_user=unconfirmed_users.pop();
 	print(f"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())

# 删除为特定值的所有列表元素
pets=["dog","cat","dog","goldfish","cat","rabbit","cat"]
print(pets)
while "cat" in pets:
	pets.remove("cat")
print(pets)



# ***********************************函数***********************************#
# 函数定义 使用def标识符  告诉Python这是定义了一个函数
def greet_user():
	"""显示一个简单的问候语————这是一个文档字符串注释,用于描述函数是干嘛的"""
	print("Hello!")

greet_user()



# 向函数传递信息(参数)   实参和形参
def greet_user(user_name):
	print(f"Hello,{user_name}")

greet_user("Lee")

# 位置实参
def describe_pet(animal_type,pet_name):
	"""显示宠物的信息"""
	print(f"\nI have a {animal_type}.")
	print(f"My {animal_type}'s name is {pet_name}.")

describe_pet("dog","ShiYue")
describe_pet("cat","Will")

# 默认实参
def describe_pet(pet_name,animal_type="dog"):
	"""显示宠物的信息"""
	print(f"\nI have a {animal_type}.")
	print(f"My {animal_type}'s name is {pet_name}.")

describe_pet("Hua")

# 调用函数必须保持实参位置与形参位置保持一致,若不一致则需要使用关键字方式传递实参
describe_pet(animal_type="hamster",pet_name="Jessi")

# 实参变成可选的
def get_formatted_name(first_name,last_name,middle_name=""):
	if(middle_name):
		full_name=f"{first_name} {middle_name} {last_name}"
	else:
		full_name=f"{first_name} {last_name}"
	return full_name.title()

muscician=get_formatted_name("jimi","hendrix")
print(muscician)
muscician=get_formatted_name("john","hooker","lee")
print(muscician)


# 返回值可以是简单值也可以是字典列表

# 函数与while配合使用
def get_formatted_name(first_name,last_name):
	"""返回整洁的名字"""
	full_name=f"{first_name} {last_name}"
	return full_name.title()

while True:
	print("Please tell me your name:")
	print("\n(enter 'q' at any time to quit)")
	f_name=input("First name:")
	if(f_name=='q'):
		break

	l_name=input("Last name:")
	if(l_name=="q"):
		break

	formatted_name=get_formatted_name(f_name,l_name)
	print(f"\nHello ,{formatted_name}")

# 函数与for循环配合使用
def greet_user(names):
	for name in names:
		print(f"Hello,{name.title()}!")

names=["harry",'jessi','lee']
greet_user(names)

# 传递任意数量的参数
def make_pizza(*toppings):
	print(toppings)
make_pizza('pepperoni')
make_pizza('extra cheese','mushrooms','green peppers')

def make_pizza(*toppings):
	for topping in toppings:
		print(topping)
make_pizza('pepperoni')
make_pizza('extra cheese','mushrooms','green peppers')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小_爽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值