CS50P week1 condition

本文详细展示了Python中的条件语句、比较运算、逻辑判断(如if-else、elif)、函数定义以及字符串处理(如输入验证、字符串分割和判断),并介绍了如何使用这些概念解决实际问题,如成绩评定、时间转换等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

条件语句

if

compare

x=int(input("x="))
y=int(input("y="))
if x<y:
    print("x is less than y")
elif x>y:
    print("x is greater than y")
else:
    print("x is equal to y")

grade

score=int(input("please input your score:"))

if score>=90 and score<=100:
    print("grade:A")
elif 80<=score<90:
    print("grade:B")
elif score>=70:
    print("grade=C")
elif score>=60:
    print("grade=D")
else:
    print("grade=E")

parity

def main():
    x=int(input("x="))
    if is_even(x)==True:
    #if is_even(x):
        print("Even")
    else:
        print("Odd")

def is_even(x):
    return x%2==0
    
main()

match

name = input("What's your name? ")
"""
if name == "Harry" or name == "Hermione" or name == "Ron": 
    print("Gryffindor")
elif name == "Draco":
    print("Slytherin")
else:
    print("Who?")
"""

match name: 
    case "Harry" | "Hermione" | "Ron":
        print("Gryffindor")
    case "Draco":
        print("Slytherin")
    case _:
        print("Who?")

作业

deep

answer=input("what's is the answer to the great question of life,the universe,and everything? ").strip().lower()
match answer:
    case "42"|"forty two"|"forty-two"|42:
        print("Yes")
    case _:
        print("No")

难点: 要把空格,随意大小写给转换掉(全部换为小写)
answer=input("what's is the answer to the great question of life,the universe,and everything? ").strip().lower()

bank

greet=input("Greeting:").strip().lower()
if greet.startswith("hello"):
    print("$0")
elif greet.startswith("h"):
    print("$20")
else :
    print("$100")

难点: 判断变量的前面几个字符
greet.startswith("hello")

extensions

file=input("File name: ").strip().lower()
if file.endswith(".gif"):
    print("image/gif")
elif file.endswith(".jpg"):
    print("image/jpeg")
elif file.endswith(".jpeg"):
    print("image/jpeg")
elif file.endswith(".png"):
    print("image/png")
elif file.endswith(".pdf"):
    print("application/pdf")
elif file.endswith(".txt"):
    name=file.split('.')[0]
    print("text/"+name)
elif file.endswith(".zip"):
    print("application/zip")
else:
    print("application/octet-stream")

难点: 判断后缀返回文件名.前面的东西)
file.endswith(".txt")
name=file.split('.')[0] 表示以.为分界,[0]表示取前面的部分

interpreter

x,y,z=input("Expression:").split(" ")
x=int(x)
z=int(z)
if y=="+":
    print(f"{x+z:.1f}")
elif y=="-":
    print(f"{x-z:.1f}")
elif y=="*":
    print(f"{x*z:.1f}")
elif y=="/":
    print(f"{x/z:.1f}")

难点: 按照空格分割表达式强行将string数字转为int保留指定位小数

注释
print(f"{x-z:.1f}")保留一位小数
x=int(x)强行将string数字转为int
x,y,z=input("Expression:").split(" ")将表达式按照空格分隔开
#保留小数 #string转int

meal

def main():
    z=convert(input("What time is it? ").strip().lower())
    if 7<=z<=8:
        print("breakfast time")
    elif 12<=z<=13:
        print("lunch time")
    elif 18<=z<=19:
        print("dinner time")
    else :
        return 0


def convert(tim):
    x=int(tim.split(':')[0])
    y=int(tim.split(':')[1])
    t=x+round(y/60,2)
    return t
    

if __name__ == "__main__":
    main()

难点: 按照时间格式转化为小数强行将string数字转为intsplit

?a.m.与p.m.的进阶不太会

### 关于CS50P Problem Set 1 的资源与解决方案 对于学习者而言,解决问题的过程通常涉及运行代码、处理数据集并验证输出结果[^1]。然而,在寻找具体课程的解答或资源时,需注意遵循学术诚信原则。 #### 官方文档与教程 CS50P(Python Track)作为哈佛大学推出的入门级编程课程之一,其官方材料提供了详尽的学习指南和练习说明。建议优先查阅该课程官网上的Problem Set描述文件以及相关视频讲解。这些资料不仅涵盖了问题的核心要点,还提供了解决思路提示。 #### 社区支持平台 除了官方渠道外,还可以利用一些在线社区获取帮助。例如Stack Overflow或者Reddit中的r/learnprogramming板块都是不错的讨论场所。不过需要注意提问方式要清晰准确,并展示自己已有的尝试过程以便获得更有针对性的回答。 #### 推荐深入学习路径 如果希望进一步提升计算机视觉领域的能力,则可以考虑参加更高级别的培训项目比如斯坦福大学开设的CS231n课程【卷积神经网络应用于视觉识别】。此课程通过线上发布全部讲课录像连同配套讲义作业等形式为学员们构建了一个全面的知识体系框架;而在此之前如果有兴趣的话也可以先体验一下fast.ai第二部分或者是deeplearning.ai系列内容来打下坚实的基础[^2]。 ```python # 示例:简单的 Python 函数用于计算阶乘 def factorial(n): """Return the factorial of a non-negative integer n.""" if n < 0: raise ValueError("Factorial is not defined for negative numbers.") elif n == 0 or n == 1: return 1 else: result = 1 for i in range(2, n + 1): result *= i return result print(factorial(5)) # Output: 120 ``` 上述代码片段展示了如何定义一个基本函数以实现特定功能——这里是求解整数N的阶乘值。这只是一个非常基础的例子,旨在启发思考关于编写有效程序逻辑的重要性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值