在学习过程中会不断更新
注意:笔记是为了学习,只记需要的即可,没必要每句话都记下,必要时可自己延申
若笔记可能出现对其理解不深入,不完整,甚至也会出现错误有问题的地方,希望大家谅解、留言提出指正,同时也欢迎大家来找我一起交流学习!
ctrl + / 是多行注释
1.
print(" * " * 4)
print(" * * " * 4)
print(" * * " * 4)
print(" * * " * 4)
print(" * " * 4)
2.
name = "John Smith"
age = 20
id = "a new patient"
print(f"We check in a patient named {name}. He's {age} years old and is {id}")
3.
name = input("What's your name?\n")
color = input("What's your favorite color?\n")
print(f"Hi, {name}. I know your favorite color is {color}.")
4.
birth_year = input("What's your birth year?\n")
print(type(birth_year))
age = 2022 - int(birth_year)
print(type(age))
sentence = f"you are {str(age)} years old"
print(sentence)
bool()
float()
5.
weight_catty = input("What's your weight in catty")
weight_kg = float(weight_catty) / 2
print(str(weight_kg))
6.
sentence = "I 'love' you"
sen = 'I "love" you'
print(sentence)
print(sen)
another = sen[:]
ano = sen
# 这两种方法可以用来拷贝复制文字
print(sen[-1] + " " + sen[0] + " " + sen[3:7] + " " + sen[3:] + " " + sen[:5] + " " + sen[1:-1])
# sen[-1],负数是倒着数的;sen[0:5],从0-4,不输出5;sen[3:], 从3到最后;sen[:5], 从0到5;sen[1:-1], 从1直接到导数第二个
print(another)
print(ano)
mail = '''
Hi, John.
Here is our first email to you.
thank you,
The support team.
'''
print(mail)
7.
mail = '''
Hi, John.
Here is our first email to you.
thank you,
The support team.
'''
print(len(mail))
print(mail.upper())
print(mail.lower())
# 以上两个形式不会改变原始字符
print(mail.replace("thank you", "Thank you"))
# 替换相应的文字
print(mail.find('o'))
# 查找字符并返回相应的索引 ,只查找第一个
print("support" in mail)
print("Support" in mail)
# 返回一个bool值,判断“support”是否在mail中
8.
num = 10 / 3
# 输出直接结果,带小数
num_1 = 10 // 3
# 输出取整之后的结果
num_2 = 10 % 3
# 输出余数
num_3= 10 ** 3
# 输出幂
num_4 = 2.5
num_5 = -2.9
print(num)
print(num_1)
print(num_2)
print(num_3)
print(round(num_4))
# 圆函数,用于数字的四舍五入
print(abs(num_5))
# 绝对值函数
9.
import math
print(math.ceil(2.9))
# 返回数字的上入整数
print(math.floor(2.9))
# 返回数字的下舍整数
# 去看官方文档,学习剩下的函数
10.
# if语句
is_not = False
is_cold = False
if is_not:
print("It's a hot day!")
print("Drink more water.")
elif is_cold:
print("It's a cold day!")
print("Ware warm clothes.")
else:
print("It's a lovely day.")
print("Enjoy your day.")
11.
price = 1000000
credit = input("If buyer have good credit?(T or F)")
if credit == 'T':
print("They need to put down 20%.")
print("They need to pay " + str(price * 0.8))
elif credit == 'F':
print("They need to put down 10%.")
print("They need to pay " + str(price * 0.9))
else:
print("It's wrong.")
# 任何非空字符串输入都将为真
# 两个布尔值都不等于字符串"True"或"False"。
# 直接使用==来判断会更好
12.
price = 1000000
credit = input("If buyer have good credit?(T or F)")
money = input("If buyer have money?(T or F)")
if credit == 'T' and money == 'F':
print("They need to put down 30%.")
print("They need to pay " + str(price * 0.7))
elif credit == 'F' and money == 'T':
print("They need to put down 20%.")
print("They need to pay " + str(price * 0.8))
else:
print("They need to put down 10%.")
print("They need to pay " + str(price * 0.9))
price = 1000000
credit = input("If buyer have good credit?(T or F)")
money = input("If buyer have money?(T or F)")
if credit == 'T' and not money == 'F':
print("They need to put down 30%.")
print("They need to pay " + str(price * 0.7))
elif credit == 'F' and not money == 'T':
print("They need to put down 20%.")
print("They need to pay " + str(price * 0.8))
else:
print("They need to put down 10%.")
print("They need to pay " + str(price * 0.9))
13.
weight = int(input("Weight: "))
unit = input("(L)bs or (K)g: ")
if unit.upper() == 'L':
convert = weight * 0.45
print(f"You are {convert} kilos")
else:
convert = weight / 0.45
print(f"You are {convert} pounds")
# 选中变量,点击重构,重命名,即可整体改变变量的名称
14.
secret_num = 7
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input("Guess: "))
guess_count += 1
if guess == secret_num:
print("You won!")
break
else:
print("Sorry, you failed")
15.
command = "" # 空字符
while True:
command = input("please enter tne problem: ").lower() # 防止重复,可以直接输入时将其改为小写
if command == "start":
print("Started")
elif command == "stop":
print("Stopped")
elif command == "help":
print('''
go out
wait for help
''')
elif command == "quit":
break
else:
print("I can't understand.")
16.
for item in ['john', 'dad', 'mom']:
print(item)
for item in range(1, 11): # 打印的是1-10
print(item)
for item in range(1, 30, 4): # 从1-29, 每隔4个打印一次
print(item)
for x in range(5):
for y in range(4):
print(f"({x}, {y})")
numbers = [5, 2, 5, 2, 2]
for count in numbers:
output = ''
for count in range(count):
output += 'x'
print(output)
17.
names = ["John", "Mimi", "Kite"]
print(names) # outcome is ['John', 'Mimi', 'Kite']
print(names[0])
print(names[2])
print(names[-2])
print(names[1:]) # outcome is ['Mimi', 'Kite']
names[0] = "Joh"
print(names)
18.
# To find the largest number in a list
numbers = [2, 4, 6, 39, 50, 27]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max)
19.
matrix = [
[2, 3, 4],
[5, 6, 7],
[8, 9, 10]
]
matrix[0][2] = 69
print(matrix[0][2])
for row in matrix:
for num in row:
print(num)
20.
numbers = [5, 6, 3, 6, 8]
numbers2 = numbers.copy() # 拷贝
numbers.append(50)
numbers.insert(3, 40) # The one number is index
numbers.remove(8)
numbers.pop() # remove the last number
# number.clear() # Empty the list
print(numbers)
print(numbers.index(3)) # find the number's index
print(4 in numbers) # No errors are generated, return Bool value
print(6 in numbers)
print(numbers.count(6)) # Calculate the quantity of number
numbers.sort() # sort the list
print(numbers)
numbers.reverse() # 使用sort后再逆向,即可倒序
print(numbers)
print(numbers2)
21.
# 删除一个列表中重复的数字
numbers = [2, 2, 4, 6, 8, 9, 8, 10]
uniques = []
for num in numbers:
if num not in uniques:
uniques.append(num)
print(uniques)
# 元组Tuples, 无法修改
numbers = (2, 4, 5)
print(numbers)
print(numbers.count(4))
print(numbers.index(2))
22.
coordinates = (1, 2, 3)
x, y, z = coordinates
# x = coordinates[0]
# y = coordinates[1]
# z = coordinates[2]
coordinates = [1, 2, 3]
l, n, m = coordinates
print(x)
print(l)
23.
# 字典
customer = {
"name": "John",
"age": 30,
"is_verified": True
}
customer["age"] = 19
print(customer.get("name")) # 使用get防止没有特征时报错
print(customer.get("age"))
print(customer.get("birthdate")) # None
print(customer.get("birthdate", "2003.9.21")) # 这样就可以得到一个值 or
customer["birthdate"] = "Jun 1 1998"
print(customer.get("birthdate")) # {'name': 'John', 'age': 19, 'is_verified': True, 'birthdate': 'Jun 1 1998'}
print(customer)
24.
# 把电话号码换成英文
phone = input("please enter your phone number: ")
digits_mapping = {
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five",
"6": "Six",
"7": "Seven",
"8": "Eight",
"9": "Nine",
"0": "Zero"
}
output = ""
for num in phone:
print(digits_mapping.get(num, "!")) # "!"在输入的东西不存在于键值对中时输出!
output += digits_mapping.get(num, "!") + " "
print(output) # 用这种方法,就可以把东西打印到一行上 ## 很好用
25.
message = input("> ")
words = message.split(" ") # split 通过指定分隔符对字符串进行切片
emoji = {
":)": "🙂",
":(": "☹"
}
output = ""
for word in words:
output += emoji.get(word, word) + " " # emoji.get(word, word) 当word是表情,返回表情;是文字,返回文字本身
print(output)
26.
def greet_user(first_name, last_name):
print(f"{first_name} {last_name}")
greet_user("John", "Smith") # 距离上面的要有两行的距离
greet_user(last_name="Smith", first_name="Mimi") # 这样在使用起来更直观
27.
def square(number):
return number * number
number = int(input(">"))
print(square(number))
28.
def putout(message):
words = message.split(" ")
emoji = {
":)": "🙂",
":(": "☹"
}
output = ""
for word in words:
output += emoji.get(word, word) + " "
return output
messages = input("> ")
print(putout(messages)) 作者:Aurora_____W https://www.bilibili.com/read/cv18096128?spm_id_from=333.999.0.0 出处:bilibili