簡單IF、for、while講解

IF函數

IF是一個判斷的概念,如果…就怎麼樣…

a = "h"
b = "h"
  
if a == b:  #當a=b的時候我們印出Welcome to my world!
    print("Welcome to my world!")
else :      #如果不等於印出Bye
  print('Bye')

當然也可以在else裡面再加入一個if,這種情況也滿常見的,接下來是elif介紹

a = "h"
b = "k"
  
if a == "a":
    print("Yes!")
elif a == b:
    print("No!")
else:
    print("What?")

elif可以解釋成第二個if,如果a=a印出YES,如果a != a,進入第二個if也就是elif判斷檢查,如果達成elif條件就執行他的程序,if只能有一個但是elif卻可以附著在if下面好幾個,去進行判斷

範例 : 輸入考試成績

score = int(input('請輸入考試分數 (1-100):'))
 
if score > 100:
    print('請勿亂輸入!')
elif score >= 90 and score <= 100:
    print('成績:A+')
elif score >= 80 and score < 90:
    print('成績:B+')
elif score >= 70 and score < 80:
    print('成績:B')
else:
    print('成績:C')
'''
請輸入考試分數 (1-100):85
成績:B+
'''

For迴圈

Python for循環可以遍歷任何序列的項目,如一個列表或者一個字符串。

for letter in 'Python':     
   print '字母 :', letter
   
字母 : P
字母 : y
字母 : t
字母 : h
字母 : o
字母 : n
 
fruits = ['grape', 'guava',  'peach']
for fruit in fruits:        
   print '水果 :', fruit
   
水果 : banana
水果 : apple
水果 : mango
 

while 迴圈

Python 編程中 while 語句用於循環執行程序,即在某條件下,循環執行某段程序,以處理需要重複處理的相同任務

舉個例子

count = 0
while (count < 10):  
   print 'The count is:', count 
   count = count + 1            	  
  
print "Good bye!"

以下面圖解做為演繹示範

寫while時有時候會不小心寫死,進入無限迴圈,這時候可以這樣做

可以使用 CTRL+C 來中斷循環。

HW

試著使用while 和 for 迴圈

寫出"乘法表" & 找出100以內2的倍數&從1累加到n

找質數、從1累加到n

乘法表不要有6的倍數
for x in range(1,11):
    if x == 0 :
        continue
    elif x == 12:
        break
    elif x == 6:
        continue
  
    for y in range(10):
        if y == 0 :
            continue
        print(x * y, end=" ")
    print()
1累加到n
sum = 0
x=1
while x < 101:
    sum = sum + x
    x+=1
    
print(sum)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值