【python3】while和for练习

 1 # Demo 1
 2 # 从键盘获取一个数字,然后计算它的阶乘,例如输入的是3那么输入3!的结果,并输出提示:
 3 # 1!等于1
 4 # 2!等于1*2
 5 # 3!等于1*2*3……*n
 6 # 案例分析:使用循环的方式计算阶乘
 7 
 8 
 9 factorial = 1
10 number = int(input("请输入你计算阶乘的数字:"))
11 if number < 0:
12     print("{}! 没有阶乘".format(number))
13 elif number == 0:
14     print("{}! 等于1".format(number))
15 else:
16     for i in range(1, number + 1):
17         factorial *= i
18     print("{}! 等于{}".format(number, factorial))
19 
20 
21 # Demo 2
22 # 模仿银行的输入密码当三次输入错误后锁定账户(也就是有三次重新输入密码的机会)
23 # 加入账户为root密码为123456
24 # 案例分析:条件为三次,可使用循环三次break
25 
26 
27 account = "root"
28 password = "123456"
29 i = 1
30 while True:
31     name = input("\n请输入你的账户:")
32     pass_wd = input("请输入你的密码:")
33     if name == account and password == pass_wd:
34         print("登录成功")
35         break
36     else:
37         print("输入错误!")
38 
39     if i == 3:
40         print("账户已锁定!")
41         break
42     i += 1
43 
44 
45 # Demo 3
46 # 使用while循环输出如下图形:(必须使用双重while循环实现)
47 #     *
48 #    * *
49 #   * * *
50 #  * * * *
51 # * * * * *
52 
53 
54 i = 1
55 while i <= 5:
56 
57     j = 1
58     while j <= i:
59         if j == 1:
60             print(" " * (5 - i), end="")
61         print("* ", end="")
62         j += 1
63 
64     print("")
65     i += 1
66 
67 
68 # Demo 4
69 # 求1 + 2!+ 3!+ …… + 20!的和。
70 
71 
72 factorial = 1
73 sum1 = 0
74 for i in range(1, 6):
75     factorial *= i
76     sum1 += factorial
77 print(sum1)
78 
79 
80 # Demo 5
81 # 本金10000元村人银行,年利润是千分之三每过1年,将本金和利息相加作为新的本金
82 # 计算五年后获取的本金是多少
83 
84 
85 money_rate = 0.003
86 capital = 10000
87 
88 for i in range(0, 6):
89     capital += capital + capital * 0.003
90 print(capital)

 

转载于:https://www.cnblogs.com/liduo0413/p/10870576.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值