一、循环:

1.场景:

①.用户名和密码,反复输入

②.计算1-100之间

③.游戏,重生

④.……

 

2.方式

①.while

②.for

 

3.while格式

while 条件:要循环执行的代码

 布尔类型的条件

 

例如:打印1-10之间的数字

# 初始值

n = 1

# 结束条件

while n > 10 :

           print('------> n=%d' %n)

332 
. # i,1Jfìffi 
334 
335 
white n 13: 
336 
print ( - 
337 
338 
339 
343 
4ÈAEpy ) 
D:\python\python.exe C:/Users/zongzi/PycharmPro 
n=13 
------> 
--> 
--> 
---> 
------> 
--> 
------> 
--> 
---> 
------> 
Process 
finished with exit code

 

练习:

1.打印1-50之间能被3整除的数字

D:\python\python.exe C:/Users/zongzi/PycharmProjects/pyth 
O results 
----> 
# while n 50: 
print('- 
,while n 50: 
print(' 
n) 
------> 
------> 
------> 
------> 
------> 
-----> 
------> 
TODO 
12 
15 
18 
21 
24 
27 
30 
33 
36 
39 
42 
O Problems 
Terminal 
Python Packages 
Python Console

 

 

 

2.打印1-10之间数字的累加和

355 
356 
357 
358 
359 
sum = @ # 
while n 10: 
sum +z n 
print( ' 
D: . exe 
sum', 
sum) 
C : /Users/zongzi/Pycharm 
sum 
sum 
sum 
sum 
sum 
sum 
sum 
sum 
sum 
sum 
1 
3 
6 
10 
15 
21 
28 
36 
45 
55 
Process finished with exit code

 

 

3.去超市买东西,价格和数量,允许买多件商品,并计算所有商品的总额

2. 
count 
while 
count 
if count 
break 
3. print('over...)

368 
369 
371 
372 
373 
574 
375 
376 
377 
378 
379 
381 
382 
383 
384 
385 
epüpy.py 
count 1 
if count 
5: 
break # 
total = 0 
while True: 
price 
number = 
int (input( 
total +2 price * number 
input(' 
answer = 
Al A 2 g 12 
? ' % total) 
if 
print( 
while True 
answer 
'q' 
break 
%.2f' 
%2.f, 
% total) 
on xpylnon. exe u:' users,' zongzl/ rycnarmrrojects/ 
400, ? 
800, ? 
800.06 
Process finished with exit code O

在第三题基础上加上,打印商品数量

371 
572 
573 
575 
376 
377 
380 
381 
384 
385 
586 
total @ 
# numbers LUØjkGwhileihfif89htfijl 
numbers = 
white True: 
price 
number = 
total +2 price * number 
numbers number 
input(' 
answer = 
f, 
% total) 
if 
print( 
answer 
break 
'q' 
% (numbers, 
total)) 
on \pytnon. exe c: /users,' zongzl/ 
400, 
800, 
40, 800.00 
Process finished with exit code @

 

 

4.产生随机数 random.randint(start,end)

可以猜多次,直到猜对为止,如果猜错了适当给出提示,猜大了还是猜小了。

1.统计猜了几次

2.如果一次就中,赶快去买彩票吧,运气爆了

  如果2-5,猜对了,运气还可以哦

  6次以上,猜对了,运气一般啊

395 
random 
396 
397 
random (1, 
398 
ran 
count 
399 
white True: 
401 
print(' 
50) 
404 
405 
408 
409 
410 
411 
12 
413 
414 
415 
416 
417 
418 
- int (input('få 
guess - 
# countitæ 
count 1 
if guess ran 
if count 
print( ' ' 
el if 2 count 5: 
print( f, 
el if count 6: 
print('fffi€r, 
021"! ' ) 
print( 
break 
el if guess 
el if guess 
print( 
while True 
> ran: 
< ran:

 

 

5.猜拳游戏:3局两胜

posted on 2022-01-17 22:00  粽子吖  阅读(203)  评论(0)    收藏  举报