CS50P week2 loop

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:

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值