Python基础(3)if_else、for、while、break与continue

时间:2024-06-27 18:34:26

1、if ... else

 a=6
if a>=5:
print("The a is bigger than 5")
else:
print("The a is smaller than 5")
x = float(input('x = '))
if x > 1:
y = 3 * x - 5
elif x >= -1:
y = x + 2
else:
y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))

2、for循环

 #for i in range(10):#默认从0开始,步进为1相当于c语言for(i=0;i<10;i++)
for i in range(1,10,3):#从1开始,步进为3
print("loop:", i )
  • range(101)可以产生一个0到100的整数序列。
  • range(1, 100)可以产生一个1到99的整数序列。
  • range(1, 100, 2)可以产生一个1到99的奇数序列,其中的2是步长,即数值序列的增量。

3、while循环

 count=0
while True:
print("你是风儿我是沙,缠缠绵绵到天涯...",count)
count +=1

4、break与continue

 #break用于完全退出本层循环
while True:
print ("break:123")
break
print( "") #continue用于退出本次循环,继续下一次循环
while True:
print( "continue:123")
continue
print( "")

5、while+else

#与其它语言else 一般只与if 搭配不同,在Python 中还有个while ...else 语句,while 后面的else 作用是指,
当while 循环正常执行完,中间没有被break 中止的话,就会执行else后面的语句