美文网首页
Python之路3:写一些小程序

Python之路3:写一些小程序

作者: 缘小泽 | 来源:发表于2018-03-17 18:30 被阅读0次

1:猜年龄游戏
要求:
a、允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出
b、允许用户最多尝试3次
c、每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y, 就继续让其猜3次
d、如何猜对了,就直接退出

代码如下:

age = '23'

count = 0

while count < 3:
    Age = input("输入你猜的年龄:")
    if Age == age:
        print("恭喜你,猜对了")
        break
    else:
        print("猜错了")
    count += 1

    if count == 3:
        select = input("你是否还要继续猜:Y or N:")
        if select == "Y":
            count = 0
            continue
        else:
            break

2、打印商品列表游戏
要求:
现有商品列表如下:

    products = [ ['Iphone8',6888],['MacPro',14800], ['小米6',2499],['Coffee',31],['Book',80],['Nike Shoes',799] ]

1、需打印出这样的格式:

---------商品列表----------
0. Iphone8    6888
1. MacPro    14800
2. 小米6    2499
3. Coffee    31
4. Book    80
5. Nike Shoes    799

2、写一个循环,不断的问用户想买什么,用户选择一个商品编号,就把对应的商品添加到购物车里, 最终用户输入q退出时,打印购物车里的商品列表

解答代码:

products = [ ['Iphone8',6888],['MacPro',14800], ['小米6',2499],['Coffee',31],['Book',80],['Nike Shoes',799] ]
logo = True
shopping_ = []

while logo:
    print("-------商品列表------")
    for index,i in enumerate(products):
        print("%s. %s   %s"% (index,i[0],i[1]))

    choice = input("输入要买的商品编号:")
    if choice.isdigit(): 
        choice = int(choice)
        if choice >= 0 and choice < len(products): 
            shopping_.append(products[choice])
            print("你已添加 %s 到购物车" %(products[choice]))
        else:
            print('商品不存在')
    elif choice == "q":
        if len(shopping_) > 0:
            print('------你已购买一下商品------')
            for index,i in enumerate(shopping_):
                print("%s. %s   %s" % (index, i[0], i[1]))
        logo = False

3、九九乘法表

for i in range(1, 10):
    for k in range(1, i+1):
        print('{}*{}={}\t'.format(k, i, k*i), end='')
    print()


1*1=1   
1*2=2   2*2=4   
1*3=3   2*3=6   3*3=9   
1*4=4   2*4=8   3*4=12  4*4=16  
1*5=5   2*5=10  3*5=15  4*5=20  5*5=25  
1*6=6   2*6=12  3*6=18  4*6=24  5*6=30  6*6=36  
1*7=7   2*7=14  3*7=21  4*7=28  5*7=35  6*7=42  7*7=49  
1*8=8   2*8=16  3*8=24  4*8=32  5*8=40  6*8=48  7*8=56  8*8=64  
1*9=9   2*9=18  3*9=27  4*9=36  5*9=45  6*9=54  7*9=63  8*9=72  9*9=81

相关文章

网友评论

      本文标题:Python之路3:写一些小程序

      本文链接:https://www.haomeiwen.com/subject/dswjqftx.html