前言:
在我们进行一门语言的学习时,循环成为了我们必要的使用工具,本篇文章将
分享一下关于Python中的for 循环.和while循环。
正文:
一、for循环的基本格式
1、for 循环的基本格式
for 变量 in 序列:
循环要执行的动作
2、序列的生成格式
range(stop): 0----stop - 1
range(start,stop): start ---- stop -1
range(start,stop,step): start ----stop-1 step(步长)
示例1:计算1---100的和
#求 1-100 的和
sum = 0
for i in range(1,100):
sum+=i
print('和为%d' %(sum))
示例i2:
题目要求:用户输入一整型数,求该数的阶乘
#用户输入一个数,求该数的阶乘
count = 1
num = int(input('请输入你要计算的阶乘数:'))
for i in range(1,num+1):
count *= i
print('%d的阶乘为%d' %(num,count))
二、break语句和contimue语句
break ###退出整个循环,不会再执行循环后面的内容
continue ###跳出本次循环,continue后面的代码将不再执行,但是循环依然执行
exit ###结束程序的运行
示例1:continue语句
for i in range(10):
if i == 5:
continue
print('hello world')
else:
print('hello python')
print('HELLO')
执行结果:
/home/kiosk/PycharmProjects/westos/venv/bin/python /home/kiosk/PycharmProjects/westos/continue.py
hello python
hello python
hello python
hello python
hello python
hello python
hello python
hello python
hello python
HELLO
Process finished with exit code 0
示例2:break语句
for i in range(10):
if i == 5:
break
print('hello world')
else:
print('hello python')
print('HELLO