Python條件語句


 

  1. if.      : (冒號)起到條件與結果分開的作用

  if 條件 :

    結果

 1 # -*- encoding:utf-8 -*-
 2 
 3 #第一種
 4 if True:
 5     print('True')
 6 print('============')
 7 
 8 #第二種
 9 if 4 > 3:
10     print('True')
11 else:
12     print('False')
13 
14 #第三種
15 num = input('請輸入您猜的數字')
16 #會發現不管你輸入什么都會報錯,那是因為input出來的字符串
17 if num == 1:
18     print('一起抽煙')
19 elif num == 2:
20     print('一起喝酒')
21 elif num == 3:
22     print('燙頭')
23 else:
24     print('你猜錯了......')
25 
26 #第四種,多種條件只走一個位置
27 
28 #字符串強轉數字加int
29 score = int(input('請輸入您猜的數字'))
30 
31 if score > 100:
32     print('我擦,最高分才100')
33 elif score >= 90:
34     print('A')
35 elif score >= 80:
36     print('B')
37 elif score >= 70:
38     print('C')
39 else:
40     print('太笨了...D')
41 
42 #第五種,if嵌套
43 name = input('請輸入名字: ')
44 age = input('請輸入年齡: ')
45 if name == '小二':
46     if age == '18':
47         print(666)
48     else:
49         print(333)
50 else:
51     print('錯了....')

 

  2. while.   

  while 條件:

    循環體

1 print(111)
2 while True:
3     print('我們不一樣')
4     print('在人間')
5     print('')
6 print('222')

   終止循環:改變條件使其不成立,或break。

 1 count = 1
 2 flag = True
 3 
 4 while flag:
 5     print(count)
 6     count += 1
 7     if count > 100 :
 8         flag = False
 9 count = 1
10 while count <= 100:
11     print(count)
12     count = count + 1
13 
14 count = 1
15 sum = 0
16 while count <= 100:
17     sum += count
18     count += 1
19 print(sum)
20 
21 print('11')
22 while True:
23     print('222')
24     break
25     print('333')
26 print('abcd')

 

  3.while else   當while循環被break打斷時,不會走else。當while循環沒有被break打斷,而是while判斷的條件為False時則會走else

  while else 不會走else的例子

 1 count = 0
 2 while count <= 5:
 3     count += 1
 4     if count == 3:
 5         break;
 6     print('Loop', count)
 7 
 8 else:
 9     print('While循環正常結束')
10 
11 print('------out of while loop')

  while else會走else的例子

count = 0
while count <= 5:
    count += 1
    if count == 3:
        pass;
    print('Loop', count)

else:
    print('While循環正常結束')

print('------out of while loop')

 

  continue:結束本次循環,開始下次循環。  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM