循环 python 的语法记录ε=(´ο`*)))唉

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43880084/article/details/102574899

(假装自己会python

loop

  • for
# iterable of cities
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']

# for loop that iterates over the cities list
for city in cities:
    print(city.title())

在这里插入图片描述在这里插入图片描述在这里插入图片描述
range(start=0, stop, step=1)
在这里插入图片描述在这里插入图片描述

练习:创建用户名

写一个遍历 names 列表以创建 usernames 列表的 for 循环。要为每个姓名创建用户名,使姓名全小写并用下划线代替空格。对以下列表运行 for 循环:

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []

# write your for loop here
for kk in names:
    usernames.append(kk.lower().replace(" ","_"))

print(usernames)

->
output

['joey_tribbiani', 'monica_geller', 'chandler_bing', 'phoebe_buffay']
usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]

# write your for loop here
for kk in range(len(usernames)):
    usernames[kk]=usernames[kk].lower().replace(" ","_")

print(usernames)

练习:标记计数器

写一个 for 循环,用于遍历字符串列表 tokens 并数一下有多少个 XML 标记。XML 是一种类似于 HTML 的数据语言。如果某个字符串以左尖括号“<”开始并以右尖括号“>”结束,则是 XML 标记。使用 count 记录这种标记的数量。

你可以假设该字符串列表不包含空字符串。

tokens = ['<greeting>', 'Hello World!', '</greeting>']
count = 0

# write your for loop here
for kk in tokens:
    if kk[0]=='<' and kk[-1]=='>': count+=1;

print(count)
items = ['first string', 'second string']
html_str = "<ul>\n"  # "\ n" is the character that marks the end of the line, it does
                     # the characters that are after it in html_str are on the next line

# write your code here
for kk in items :
    html_str+=("<li>")
    html_str+=(kk)
    html_str+=("</li>")
    html_str+="\n"
html_str+=("</ul>")
print(html_str)
  • while
limit = 40
nearest_square=0 
num=1
# write your while loop here
while limit>=num*num:
    nearest_square=num*num
    num+=1
print(nearest_square)

nearest_square = num**2

example

manifest = [("bananas", 15), ("mattresses", 24), ("dog kennels", 42), ("machine", 120), ("cheeses", 5)]

# the code breaks the loop when weight exceeds or reaches the limit
print("METHOD 1")
weight = 0
items = []
for cargo_name, cargo_weight in manifest:
    print("current weight: {}".format(weight))
    if weight >= 100:
        print("  breaking loop now!")
        break
    else:
        print("  adding {} ({})".format(cargo_name, cargo_weight))
        items.append(cargo_name)
        weight += cargo_weight

print("\nFinal Weight: {}".format(weight))
print("Final Items: {}".format(items))

# skips an iteration when adding an item would exceed the limit
# breaks the loop if weight is exactly the value of the limit
print("\nMETHOD 2")
weight = 0
items = []
for cargo_name, cargo_weight in manifest:
    print("current weight: {}".format(weight))
    if weight >= 100:
        print("  breaking from the loop now!")
        break
    elif weight + cargo_weight > 100:
        print("  skipping {} ({})".format(cargo_name, cargo_weight))
        continue
    else:
        print("  adding {} ({})".format(cargo_name, cargo_weight))
        items.append(cargo_name)
        weight += cargo_weight

print("\nFinal Weight: {}".format(weight))
print("Final Items: {}".format(items))

METHOD 1
current weight: 0
  adding bananas (15)
current weight: 15
  adding mattresses (24)
current weight: 39
  adding dog kennels (42)
current weight: 81
  adding machine (120)
current weight: 201
  breaking loop now!

Final Weight: 201
Final Items: ['bananas', 'mattresses', 'dog kennels', 'machine']

METHOD 2
current weight: 0
  adding bananas (15)
current weight: 15
  adding mattresses (24)
current weight: 39
  adding dog kennels (42)
current weight: 81
  skipping machine (120)
current weight: 81
  adding cheeses (5)

Final Weight: 86
Final Items: ['bananas', 'mattresses', 'dog kennels', 'cheeses']


练习:截断字符串

用 break 语句写一个循环,用于创建刚好长 140 个字符的字符串 news_ticker。你应该通过添加 headlines 列表中的新闻标题创建新闻提醒,在每个新闻标题之间插入空格。如果有必要的话,将最后一个新闻标题从中间截断,使 news_ticker 刚好长 140 个字符。

注意,break 同时适用于 for 和 while 循环。使用你认为最合适的循环。考虑向代码中添加 print 语句以帮助你解决 bug。

# HINT: modify the headlines list to verify your loop works with different inputs
headlines = ["Local Bear Eaten by Man",
             "Legislature Announces New Laws",
             "Peasant Discovers Violence Inherent in System",
             "Cat Rescues Fireman Stuck in Tree",
             "Brave Knight Runs Away",
             "Papperbok Review: Totally Triffic"]

news_ticker = ""
# write your loop here
for kk in headlines:
    news_ticker+=kk+" "
    if len(news_ticker)>=140:
        news_ticker= news_ticker[:140]
        break

print(news_ticker)

猜你喜欢

转载自blog.csdn.net/weixin_43880084/article/details/102574899