Python 练习小代码

猜年龄(code)age = 30

flag = True

while flag == True:
guess =int(input('your guess age:'))
if guess == age:
print('you right!')
flag = False
else:
print('your is error!')
if guess < age:
print('maybe is small!')
elif guess > age:
print('maybe is big!')

求最大值和最小值(支持用户输入数字)

def num_list():   #将输入的数字,存入一个列表
num_list_a = []
flag = True
while flag == True:

your_choice = input('exit:')
if your_choice == 'yes':
flag = False
else:
num = int(input('>>:'))
num_list_a.append(num)
return num_list_a
def max_min_num(a): #求出最大值和最小值
max = 0
min = a[0]
for i in a:
if i < min:
min = i
if i > max:
max = i
print('the max number :',max)
print('the min number :',min)
return
max_min_num(num_list())
打印出一个九九乘法表:
for i in range(1,10):
for j in range(1,i+1): # 对于九九乘法表要注意他的每行,是第一个数在递增
print('%d * %d = %d' % (j, i, i*j), end=' ') # end的方法是将在本次循环中的输出的所有内容在一行输出
print() # 相当于一个换行符的作用


求最大公约数的个数

a = int(input('a = '))
b = int(input('b = '))

def times(x,y):
timess = 0
if x > y:
max = x+1
else:
max = y+1
for i in range(1,max):
if x % i == 0 and y % i == 0:
timess += 1
return timess
print(times(a,b))

一个购物车程序:

这是一个简单的购物程序

 

实现的功能有:

 

1.自定义商品 在shopping_list 中
2.可以实时退出
3.可以输入你有多少钱
4.有 是否确认支付的片段
5.可以循环购买

 

shopping_list = {'apple':10,
'banana':20,
'book':50}

def show_shopping(): # shopping show
n = 0
print('----------------shopping store----------------\n'
'welcome shopping store!!!!\n'
'this is my store all shopping!\n'
'----------------------------------------------')
for shopping in shopping_list:

print('%d ---> %s,%d' % (n,shopping,shopping_list[shopping]))
n+=1
# show_shopping() the test
# your_all_money -= shopping_list[your_choice]
# print('you have %d yuan now, and you purchase one %d' % (your_all_money,your_choice))


# 需要再次购买
def buy_again():
global flag
buy_again = input('you want to buy again:')
if buy_again == 'yes':
show_shopping()
main()
else:
print('wlcome again!')
flag = False
return flag
# 主函数
def main():
# 调用全局变量
global your_all_money
global flag
while flag == True:
exit = input('exit now:')
if exit == 'yes':
print('welcome again')
flag = False
else:
show_shopping() # show
your_choice= input('please enter you want to buy commodity:')
if your_choice in shopping_list:
print('you need pay %d yuan !!' % shopping_list[your_choice])
pay_choice = input('make sure to pay:')
if pay_choice == 'yes':
your_all_money -= shopping_list[your_choice]
print('you have %d yuan now, and you purchase one %s' % (your_all_money,your_choice))

flag = buy_again()

else:

flag = buy_again()
else:
print('please enter again!')
main()
flag = True # 控制直接退出程序
your_all_money = int(input('your all money:'))
main()
 

猜你喜欢

转载自www.cnblogs.com/kangjunhao/p/9097983.html
今日推荐