python中有for
循环和while
循环两种形式。
1. for 循环
可以用for
循环来遍历不同类型的对象,如数组、列表、元组、字典、集合或字符串,并对每个元素执行一段代码。
1.1 数组的for循环
用for循环遍历一个数组,并打印出每个元素:
import numpy as np
a=np.arange(5)
for i in a:
print(i)
输出:
0
1
2
3
4
1.2 列表的for循环
用for循环遍历一个列表,并打印出每个元素:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
输出:
apple
banana
cherry
1.3 元组的for循环
用for循环遍历一个元组,并打印出每个元素:
colors = ("red", "green", "blue")
for color in colors:
print(color)
输出:
red
green
blue
1.4 字典的for循环
用for循环遍历一个字典,并打印出每个键值对:
person = {"name": "Alice", "age": 25, "gender": "female"}
for key, value in person.items():
print(key, "=", value)
输出:
name = Alice
age = 25
gender = female
1.5 集合的for循环
用for循环遍历一个集合,并打印出每个元素:
numbers = {1, 2, 3, 4}
for number in numbers:
print(number)
输出:
1
2
3
4
1.6 字符串的for循环
用for循环遍历一个字符串,并打印出每个字符:
word = "hello"
for letter in word:
print(letter)
输出:
h
e
l
l
o
2. while循环
Python的while循环是用来重复执行一段代码,直到某个条件不满足为止。while循环的语法是:
while condition:
# body of while loop
这里,
- while循环先判断条件是否为真。
- 如果条件为真,就执行循环体中的代码。
- 然后再次判断条件是否为真。
- 这个过程会一直重复,直到条件为假,才退出循环。
2.1 例1
用while循环打印1到5的数字:
i = 1
while i <= 5:
print(i)
i += 1
输出:
1
2
3
4
5
2.2 例2
用while循环和break语句实现猜数字游戏:
import random
number = random.randint(1,10) # 随机生成一个1到10的整数
guess = None # 初始化猜测变量
while guess != number: # 当猜测不等于目标数时,继续循环
guess = int(input("请输入一个1到10的整数:")) # 获取用户输入并转换为整数
if guess < number: # 如果猜测小于目标数,提示太小了,并继续循环
print("太小了!")
elif guess > number: # 如果猜测大于目标数,提示太大了,并继续循环
print("太大了!")
else: # 否则,说明猜对了,打印恭喜信息,并退出循环
print("恭喜你!你猜对了!")
break
输出:
请输入一个1到10的整数:5
太大了!
请输入一个1到10的整数:2
太大了!
请输入一个1到10的整数:1
恭喜你!你猜对了!