CS50python 作业LECUTR 1

In deep.py, implement a program that prompts the user for the answer to the Great Question of Life, the Universe and Everything, outputting Yes if the user inputs 42 or forty-two or forty two. Otherwise output No.

x = input(
    "What is the Answer to the Great Question of Life, the Universe, and Everything?")
x.strip() 
if x == "42":
    print("yes")
elif x =="forty-two":
    print("yes")
elif x =="forty two":
    print("yes")
else:
    print("no")

In a file called bank.py, implement a program that prompts the user for a greeting. If the greeting starts with “hello”, output $0. If the greeting starts with an “h” (but not “hello”), output $20. Otherwise, output $100. Ignore any leading whitespace in the user’s greeting, and treat the user’s greeting case-insensitively.

def main():
    welcome = input("Greeting:").strip()
    bank(welcome)
def bank(words):
    if words.startswith("hello"):
        print("$0") 
    elif words.startswith("h"):
        print("$20")
    else:
        print("$100")

main()

In a file called extensions.py, implement a program that prompts the user for the name of a file and then outputs that file’s media type if the file’s name ends, case-insensitively, in any of these suffixes:

  • .gif
  • .jpg
  • .jpeg
  • .png
  • .pdf
  • .txt
  • .zip

If the file’s name ends with some other suffix or has no suffix at all, output application/octet-stream instead, which is a common default.

def main():
    name = input("File Name:")
    what_tpye(name)
def what_tpye(tpye):
    if tpye.endswith(".gif"):
        print("image/gif")
    elif tpye.endswith(".jpg"):
        print("image/jpg")
    elif tpye.endswith(".pdf"):
        print("image/pdf")
    else:
        print("application/octet-strea")
main()

In a file called interpreter.py, implement a program that prompts the user for an arithmetic expression and then calculates and outputs the result as a floating-point value formatted to one decimal place. Assume that the user’s input will be formatted as x y z, with one space between x and y and one space between y and z, wherein:

  • x is an integer
  • y is +-*, or /
  • z is an integer

For instance, if the user inputs 1 + 1, your program should output 2.0. Assume that, if y is /, then z will not be 0.

Note that, just as python itself is an interpreter for Python, so will your interpreter.py be an interpreter for math!

eval函数、split、format函数

def main():
    expression = input("Expression:") 
    calculate(expression)

# python eval() 函数的功能:将字符串str当成有效的表达式来求值并返回计算结果。
def calculate(some):
    x,y,z = some.split(" ")
    x = int(x)
    z = int(z)
    result = eval(f"{x} {y} {z}")
    print(f"{result:.1f}")
main()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值