Loops | CS50P 2022 | CS50’s Introduction to Programming with Python | edX
Notes
cat
# Introduces continue, break
while True:
n = int(input("What's n? "))
if n <= 0:
continue
else:
break
for _ in range(n):
print("meow")
hogwarts
## list
## Demonstrates iterating over and index into a dict
# students = {
# "Hermione": "Gryffindor",
# "Harry": "Gryffindor",
# "Ron": "Gryffindor",
# "Draco": "Slytherin",
# }
# for student in students:
# print(student, students[student], sep=", ")
## dictionary
# Demonstrates iterating over a list of dict objects
students = [
{"name": "Hermione", "house": "Gryffindor", "patronus": "Otter"},
{"name": "Harry", "house": "Gryffindor", "patronus": "Stag"},
{"name": "Ron", "house": "Gryffindor", "patronus": "Jack Russell terrier"},
{"name": "Draco", "house": "Slytherin", "patronus": None},
]
for student in students:
print(student["name"], student["house"], student["patronus"], sep=", ")
mario
# Prints square of bricks using a function with nested loops
def main():
print_square(3)
def print_square(size):
for i in range(size):
for j in range(size):
print("#", end="")
print()
main()
作业
camel
get_name=input("camelCase: ").strip()
print("snake_case:",end="")
for a in get_name:
if a.islower():
print(a,end="")#保证输出不换行
if a.isupper():
print("_"+a.lower(),end="")#用“+”而不是“,”,因为避免空格
难点: 去掉空格,逐字符输出,用_
相连
print(a,end="")
的end=""
保证了输出不换行
coke
# 可乐机,只能投25,10,5,直至找零或完结
print("Amount Due: 50")
remain=50
while True:
get=int(input("Insert Coin: "))
if get==25 or get==10 or get==5:
remain=remain-get
if remain>0:
print("Amount Due:",remain)
else:
print("Change Owed:",-remain)
break
else:
print("Amount Due:",remain)
难点: while死循环,小于等于0的情况要注意
if get==25 or get==10 or get==5:
多条件判断
twttr
getin=input("Input:")
print("Output:",end="")
for short in getin:
if short.lower()=="a" or short.lower()=="e" or short.lower()=="i" or short.lower()=="u" or short.lower()=="o":
print("",end="")
else:
print(short,end="")
难点: 逐字符判断输出,用lower函数减少讨论大写情况
if short.lower()=="a" or short.lower()=="e" or short.lower()=="i" or short.lower()=="u" or short.lower()=="o":
多条件判断,是否为元音字母,如果是,就去掉(不输出);反之,输出字符
plates
# “All vanity plates must start with at least two letters.”
# “… vanity plates may contain a maximum of 6 characters (letters or numbers) and a minimum of 2 characters.”
# “Numbers cannot be used in the middle of a plate; they must come at the end. For example, AAA222 would be an acceptable … vanity plate; AAA22A would not be acceptable. The first number used cannot be a ‘0’.”
# “No periods, spaces, or punctuation marks are allowed.”
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if s[0:2].isalpha() and 2<=len(s)<=6:
for ch in s[2:]:
#排除不是字母或者数字的
if ch.isalpha()==False and ch.isdigit()==False:
return False
for ch in s[2:]:
#字母的ok
if ch.isdigit():
#不能0打头
if ch=="0":
return False
else:
#实现第三个功能
#循环到第一位数字,无论怎样,都return,不再继续遍历ch
first_number_position=s.index(ch)
#s[i:j]切片
for i in s[first_number_position:]:
if i.isalpha():
return False
return True
#全是字母的情况
else:
return True
#排除前两位不是字母的和长度不对的
else:
return False
main()
难点: 判断字母所在位置,判断字符是字母还是数字
一旦出现了数字,后面只能是数字,list切片
#获取第一位数字
first_number_position=s.index(ch)
#s[i:j]切片
for i in s[first_number_position:]:
if i.isalpha():
return False
return True
nutrition
FDA = {
"Apple":"130",
"Avocado":"50",
"Banana":"110",
"Cantaloupe":"50",
"Grapefruit":"60",
"Grapes":"90",
"Honeydew Melon":"50",
"Kiwifruit":"90",
"Lemon":"15",
"Lime":"20",
"Nectarine":"60",
"Orange":"80",
"Peach":"60",
"Pear":"100",
"Pineapple":"50",
"Plums":"70",
"Strawberries":"50",
"Sweet Cherries":"100",
"Tangerine":"50",
"Watermelon":"80",
}
item=input("Item: ").title()
# 判断是否在FDA里
if item in FDA:
print("Calories:",FDA[item])
难点: 判断对象是否在list中
if item in FDA: