x,y,smaller = 3,5,0
if x < y:
smaller = x
else:
smaller = y
或
smaller = x if x < y else y
打印九九乘法表
def print_multiplication_tables():'''打印九九乘法表'''for i inrange(1,10): # 1-99行
for j inrange(1,i+1): # 1-11-21-31-4...9列
print('%s*%s=%s'%(j,i,i*j),end='\t')print()print_multiplication_tables()//输出1*1=11*2=22*2=41*3=32*3=63*3=91*4=42*4=83*4=124*4=161*5=52*5=103*5=154*5=205*5=251*6=62*6=123*6=184*6=245*6=306*6=361*7=72*7=143*7=214*7=285*7=356*7=427*7=491*8=82*8=163*8=244*8=325*8=406*8=487*8=568*8=641*9=92*9=183*9=274*9=365*9=456*9=547*9=638*9=729*9=81
冒泡排序
def bubble(list_nums):'''冒泡排序'''for j inrange(len(list_nums)-1):for i inrange(len(list_nums)-1-j):print(i)if(list_nums[i]>list_nums[i+1]):
list_nums[i],list_nums[i+1]= list_nums[i+1],list_nums[i]print(list_nums)
list_nums =[2,1,9,0,7]bubble(list_nums)//輸出0[1,2,9,0,7]1[1,2,9,0,7]2[1,2,0,9,7]3[1,2,0,7,9]0[1,2,0,7,9]1[1,0,2,7,9]2[1,0,2,7,9]0[0,1,2,7,9]1[0,1,2,7,9]0[0,1,2,7,9]
循环语句
while循环
基于条件执行,只要条件为真,循环体就会重复执行
while condition:
# 循环体
count =0while count <5:print(count)
count +=1// 输出012345
# 使用breakfor num inrange(1,10)://break 用于立即跳出循环,终止循环if num ==5:breakprint(num)
# 使用continuefor num inrange(1,10)://continue 跳过当前迭代,直接开始下一轮循环。if num %2==0:continueprint(num)
for循环
通常用于遍历遍历序列(如列表、元组、字符串、字典、range对象等)中的每个元素,执行一次循环体
接收可迭代对象
for item in sequence:
# 循环体
fruits =['apple','banana','cherry','kiwi']for fruit infruits:print(fruit)// 输出
apple
banana
cherry
kiwi
遍历字典
my_dict ={'name':'Alice','age':30,'city':'New York'}//遍历字典的键,使用.keys()方法返回一个包含所有键的视图for key in my_dict.keys():print(key)// 输出
name
age
city
//遍历字典的值,使用.values()方法返回所有值的视图for value in my_dict.values():print(value)//输出
Alice
30
New York
//遍历字典的键值对,使用.items()方法,每次迭代出一个元组,包含键和值for key, value in my_dict.items():print(key,":", value)//输出name:Alice
age:30city: New York
遍历列表
for city inname_list:print(city)//输出
xi'an
weinan
hanzhong
//当不知道传过来的列表有多长时:
name_list =['xi\'an','weinan','hanzhong']for city inrange(len(name_list)):print(city)//输出012
搭配range使用
// 计数for i inrange(5):print(i)// 指定起始值for i inrange(2,7):print(i)//指定步长for i inrange(0,10,2):print(i)//倒序打印for i inrange(5,0,-1):print(i)