1、打开Pycharm,创建Python文件,复制代码,保存运行!
"""
Time : 2024/1/16 14:18
Author : XFL
"""
def list_while_func():
"""
# 1、使用while遍历列表
:return: None
"""
mylist = ["xppp","xpp","acb","hello","xpp","pycharm","java","xpp"]
index = 0
while index < len(mylist):
print(f"使用while遍历列表:{mylist[index]}")
index += 1
print(f"while循环执行{index}次")
def list_for_func():
"""
# 2、使用for遍历列表
:return: None
"""
mylist = ["xppp", "xpp", "acb", "hello", "xpp", "pycharm", "java", "xpp"]
index = 0
for index in range(0,len(mylist)):
print(f"使用for循环遍历列表:{mylist[index]}")
index += 1
print(f"for循环执行{index}次")
# 函数的调用
list_while_func()
list_for_func()
# 定义一个列表,内容是:[1,2,3,4,5,6,7,8,9,10]
# 遍历列表,取出列表内的偶数,并存入一个新的列表对象中
# 使用while循环和for循环各操作一次
def list_while_double():
"""
使用while输出偶数,并插入新的列表中
:return: None
"""
mylist1 = [1,2,3,4,5,6,7,8,9,10]
list_double = []
index = 0
while index < len(mylist1):
if mylist1[index] % 2 == 0:
list_double.append(mylist1[index])
index += 1
print(f"使用while输出偶数的结果{list_double}")
def list_for_double():
"""
使用for输出偶数,并插入新的列表中
:return: None
"""
mylist1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list_double = []
index = 0
for index in range(0,len(mylist1)):
if mylist1[index] % 2 == 0:
list_double.append(mylist1[index])
index += 1
print(f"使用for输出偶数的结果{list_double}")
# 函数的调用
list_while_double()
list_for_double()