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

时间:2024-07-25 22:37:08

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

代码:

 #!user/bin/env python3
# -*- coding: gbk -*-
luck_num = 19
input_num = int(input("please input the luck num:"))
if input_num == 19:
print("Bingo!")
elif input_num > luck_num:
print("the num is Bigger!")
else:
print("the num is smaller")

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

 #!user/bin/env python3
# -*- coding: gbk -*-
luck_num = 19
input_num = int(input("please input the luck num:"))
if input_num == 19:
print("Bingo!")
elif input_num > luck_num:
print("the num is Bigger!")
else:
print("the num is smaller")

For 循环方式:

 for num_of_times in range(3):
# When failure exit after three times.
input_num = int(input("please input the luck num:"))
if input_num == 19:
print("Bingo!")
break
elif input_num > luck_num:
print("the num is Bigger!")
else:
print("the num is smaller")
else:
print("you try too many times.")

continue,跳过

break,中断

 for i in range(10):
if i < 5:
continue
print(i) #result
5
6
7
8
9

continue 和 break的区别

continue 是跳过当前循环块的剩余语句,进行下一次循环。break 是跳出当前循环块,停止当前循环。