一、你最喜欢的人
name = input('What is your name? ')
favorite_person = input('What is your favorite person? ')
print(name + ' likes ' +favorite_person)
二、你的年龄是
birth_year = input('Your year of birth: ')
age = str(2020 - int(birth_year))
print('Your age is ' + age)
三、名字
name = 'Jennifer'
print(name[1:-1])
print(name[0:5])
#打印字符串的长度
print(len(name))
# 找到 i 的索引
print(name.find('i'))
# 替换字符
print(name.replace('fer','ger'))
# 判断文本是否有特定字符
print('er' in name)
#对文本进行大小写
print(name.upper())
print(name.lower())
四、杨[旭东] is a coder
first = '杨'
last = '旭东'
#f的意思是格式化
message = f'{first} [{last}] is a coder'
print(message)
五、数字处理
math.floor() 向下取整
math.ceil() 向上取整
round() 四舍五入
六、if-else 语句
is_hot = True
is_cold = False
if is_hot:
print("Drink plenty of water")
elif is_cold:
print("Wear warm cloths")
else:
print("It's a lovely day")
七、逻辑运算符
and or not(与 或 非)
八、while 循环
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input('Guess: '))
guess_count += 1
if guess == secret_number:
print('You won!')
break
else:
print('Sorry you failed!')
九、不开两次车
command = ""
started = False
while True:
command = input("> ").lower()
if command == "start":
if started:
print("Car is already started!")
else:
started = True
print("Car started...")
elif command == "stop":
if not started:
print("Car is already stopped!")
else:
started = False
print("Car stopped.")
elif command == "help":
print("""
start - to start the car
stop - to stop the car
quit - to quit
""")
elif command == "quit":
break
else:
print("Sorry, I don't understand that!")
十、for循环与列表
1.列表的基本方法
numbers = [5,2,1,5,7,4]
# 在列表中添加元素
numbers.append(20)
# 在列表中的索引位置添加元素
numbers.insert(0,10)
#移除列表中的元素
numbers.remove(2)
# 清空列表
numbers.clear()
# 清空列表最后一个元素
numbers.pop(3)
#查找某个元素的个数
numbers.count(5)
#升序和降序
numbers.sort()
numbers.reverse()
#列表的复制
numbers2 = numbers.copy()
2.清空列表中的重复元素
numbers = [2,2,3,5,4,4,56,5,5,1,7]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques)
十一、元组与解压缩
coordinates = (1,2,3)
x,y,z = coordinates
print(y)#2
十二、字典
phone = input("Phone: ")
digits_mapping = {
"1" : "One",
"2" : "Two",
"3" : "Three",
"4" : "four",
"5" : "five"
#...
}
output = ""
for ch in phone:
output += digits_mapping.get(ch,"!") + " "
print(output)
十三、自定义函数
def greet_user(first_name, last_name):
print(f'Hi {first_name} {last_name}!')
print('Welcome aboard')
print("Start")
greet_user("john", last_name="smith")
print("Finish")
十四、异常处理
try:
age = int(input('Age: '))
income = 20000
risk = income / age
print(age)
except ZeroDivisionError:
print('Age cannot be 0.')
except ValueError:
print('Invalid value')