【Python中的】for 循环 和 while 循环

本文介绍了Python中的for循环和while循环。for循环包括基本格式和序列生成,如计算1-100的和及求阶乘。同时讲解了break和continue语句的应用。while循环部分涵盖基本格式、死循环示例以及用户登录程序的实现,涉及多次尝试和错误提示。文章通过实例演示了循环在实际问题中的应用,如数字计算、字符串输出和猜数字游戏。
摘要由CSDN通过智能技术生成

前言:

       在我们进行一门语言的学习时,循环成为了我们必要的使用工具,本篇文章将

分享一下关于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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值