python学习代码片段(三):循环、函数

1.循环

#取第一个列表成员(可迭代),暂称它数字(打印它)
#取列表的第二个成员(可迭代),暂时将其称为数字,等等......
for number in [23, 41, 12, 16, 7]: 
    print(number)

# 使用'''     '''可以定义换行的字符串   从文本中删除标点符号并将最终产品转换为列表
text = '''On a dark desert highway, cool wind in my hair Warm smell of colitas, 
rising up through the air Up ahead in the distance, 
I saw a shimmering light My head grew heavy and my sight grew dim 
I had to stop for the night There she stood in the doorway; 
I heard the mission bell And I was thinking to myself, 
"This could be Heaven or this could be Hell" Then she lit up a candle and she showed me the way'''
# 把标点符号全换成空格
for char in '-.,;\n"\'':
    text = text.replace(char,' ')
print(text)
# 以空格分割字符串为列表 取前20个词  另外空格字符串的长度为0,利用这点可以过滤掉字符串中的空格
text.split(' ')[0:20]

# 编写一个Python程序,它迭代整数从1到50(使用for循环)。
# 对于偶数的整数,将其附加到偶数列表中  对于奇数的整数,将其附加到奇数列表中
even_numbers = []
odd_numbers = []

for number in range(1,51):
    if number % 2 == 0:
        even_numbers.append(number)
    else: 
        odd_numbers.append(number)  
print("Even Numbers: ", even_numbers)
print("Odd Numbers: ", odd_numbers)

2.函数

# 函数外部的变量从内部可见,具有全局范围
# 函数内定义的参数和变量在外部不可见,具有局部范围
def greet(name,msg):
   """This function greets to
   the person with the provided message"""
   print("Hello",name + ', ' + msg)

# 打印函数的帮助信息
print(greet.__doc__)
greet("Monica","Good morning!")

# 函数参数可以有默认值,用赋值运算符(=)为参数提供默认值 
# 函数定义时,默认参数必须放在非默认参数之前 def greet(msg = "Good morning!", name):会报错
def greet(name, msg = "Good morning!"):
   """
   This function greets to
   the person with the
   provided message.

   If message is not provided,
   it defaults to "Good
   morning!"
   """

   print("Hello",name + ', ' + msg)

greet("Kate")
greet("Bruce","How do you do?")

# 当以关键字参数调用函数时 函数参数顺序可以改变
greet(msg = "How do you do?",name = "Bruce") 

# 具有任意数量参数的函数 在函数定义中,在参数名称前使用星号(*)来表示这种参数、
# 使用多个参数调用该函数时这些参数在传递给函数之前被包装到元组中。在函数内部,使用for循环来检索所有参数
def greet(*names):
   """This function greets all
   the person in the names tuple."""

   # names is a tuple with arguments
   for name in names:
       print("Hello",name)

greet("Monica","Luke","Steve","John")


#从列表中去除重复元素
def remove_duplicates(duplicate): 
    uniques = [] 
    for num in duplicate: 
        if num not in uniques: 
            uniques.append(num) 
    return(uniques)
      
duplicate = [2, 4, 10, 20, 5, 2, 20, 4] 
print(remove_duplicates(duplicate)) 
发布了23 篇原创文章 · 获赞 25 · 访问量 866

猜你喜欢

转载自blog.csdn.net/qq_42878057/article/details/105184624
今日推荐