Python基础 您所在的位置:网站首页 python开发一个循环5次计算的小游戏叫什么 Python基础

Python基础

2024-02-14 13:43| 来源: 网络整理| 查看: 265

Python基础------几种循环结构详解

在所有的编程语言中,循环结构是必不可少了,Python也一样。在python主要有一下几种循环结构:for…in…、while、range()三种最为常见。 Python循环结构

1.for…in…

该格式在python中是最为常见的一种格式,使用极为广泛。

格式:for 参数 in 循环体: pass

上述格式中,可以做循环体的内容有很多,如元组、列表、字符串等等。只要可以遍历、可循环的的内容均可作为循环体存在。 其中的参数,主要是用来存放每次循环体送来的单个元素,实现循环的作用。在实际使用中,常和if判断语句联合使用。

#input str_01 = '时间都去哪了!!!' for i in str_01: print(i) #output 时 间 都 去 哪 了 ! ! ! 2.while

while循环和for…in…循环的不同之处在于,while要先将循环变量初始化或者直接使用while True 这种死循环形式。

格式:i = 0 while i >=10: pass i +=1

在我们平时使用中,这种格式使用频率,相比较于for…in…是比较低的。而对于while循环,最为常见的格式是:

格式:while True: pass

该格式,在大部分项目中都会用到。

#input while True: print('hello world!!!__hello python!!!') #output hello world!!!__hello python!!! hello world!!!__hello python!!! hello world!!!__hello python!!! hello world!!!__hello python!!! hello world!!!__hello python!!! hello world!!!__hello python!!! hello world!!!__hello python!!! hello world!!!__hello python!!! hello world!!!__hello python!!! . . . . . . 3.range()

range()的使用主要是和for循环一起出现的。 range()的形式有三种:

range(stop) :默认从0开始,给出结束的int型参数即可range(start,stop) :range(start,stop,step)

上述中的stop参数,都是取不到的,结尾的参数为stop-1。这也是python的一大特点,我学习一个多月以来,所有用括号扩起来的循环或者取值,都是***左取右不取***

#input for i in range(5): print(i) print('*'*10) for x in range(1,7): print(x) print('*'*10) for y in range(2,19,3): print(y) print('*'*10) #output 0 1 2 3 4 ********** 1 2 3 4 5 6 ********** 2 5 8 11 14 17 **********

for循环搭配range()的形式,极为常见。如我们常见的九九乘法表,使用for循环和range()搭配的形式,就可以轻松完成。

九九乘法表——for循环搭配range()实现# 输入层数 #input #九九乘法表,for循环++range()实现 a = int(input('请输入层数:')) for i in range(1, 10): for j in range(i, 10): print('{}*{}={:


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有