首页 > 代码库 > Python 基础之三条件判断与循环

Python 基础之三条件判断与循环

If……else 基本结构:

If condition:

do something

else:

do something

或者

If condition:

do something

elif condition:

do something

else:

do something

 

Python 通过缩进来确定一段代码的作用域,同一级别的代码缩进要保持一致,官方建议是4个空格。

提示:IndentationError,都为代码中存在缩进错误。

小练习:

# 猜luck number,n=6

# 猜的数字比6大,提示小一点

# 猜的数字比6小,提示大一点

#猜的数字等于6,提示Bingo

代码:

 

 1 #!user/bin/env python3 2 # -*- coding: gbk -*- 3 luck_num = 19 4 input_num = int(input("please input the luck num:")) 5 if input_num == 19: 6     print("Bingo!") 7 elif input_num > luck_num: 8     print("the num is Bigger!") 9 else:10     print("the num is smaller")

 

 

 

 

 

引入循环while,加入次数限制,代码:

 

 1 #!user/bin/env python3 2 # -*- coding: gbk -*- 3 luck_num = 19 4 input_num = int(input("please input the luck num:")) 5 if input_num == 19: 6     print("Bingo!") 7 elif input_num > luck_num: 8     print("the num is Bigger!") 9 else:10     print("the num is smaller")

 

 

 

For 循环方式:

 1 for num_of_times in range(3): 2     # When failure exit after three times. 3     input_num = int(input("please input the luck num:")) 4     if input_num == 19: 5         print("Bingo!") 6         break 7     elif input_num > luck_num: 8         print("the num is Bigger!") 9     else:10         print("the num is smaller")11 else:12     print("you try too many times.")

 

Python 基础之三条件判断与循环