python基礎4--控制流
1、if語句
結構:
if condition:
do something
elif other_condition:
do something
number = 60 guess = int(input('Enter an integer : ')) if (guess == number): # New block starts here print('Bingo! you guessed it right.') # New block ends here elif (guess < number): # Another block print('No, the number is higher than that') # You can do whatever you want in a block ... else: print('No, the number is alower than that') # you must have guessed > number to reach here print('Done')
2、迴圈語句允許我們執行一個語句或語句組多次,下面是在大多數程式語言中的迴圈語句的一般形式:
3、for語句
for i in range(1, 10): print(i) else: print('The for loop is over') #遍歷List a_list = [1, 3, 5, 7, 9] for i in a_list: print(i) #遍歷Tuple a_tuple = (1, 3, 5, 7, 9) for i in a_tuple: print(i) #遍歷Dict a_dict = {'Tom':'111', 'Jerry':'222', 'Cathy':'333'} for key in a_dict: print(key, a_dict[key]) for (key, elem) in a_dict.items(): print(key, elem)
執行結果:
4、while語句
number = 59 guess_flag = False while (guess_flag == False): guess = int(input('Enter an integer : ')) if guess == number: guess_flag = True elif guess < number: print('No, the number is higher than that, keep guessing') else: print('No, the number is alower than that, keep guessing') print('Bingo! you guessed it right.')
5、break, continue, pass
(1) break 語句:跳出迴圈
(2) continue 語句:進行下一次 迴圈
(3) pass 語句:什麼都不做
number = 59 while True: guess = int(input('Enter an integer : ')) if guess == number: break if guess < number: print('No, the number is higher than that, keep guessing') continue else: print('No, the number is alower than that, keep guessing') continue print('Bingo! you guessed it right.') print('Done')