Problem Set 1
官网一共有五题,前面三题较为简单,故不放置代码
Math Interpreter
def main():
expression = input("Expression: ")
result = calculate(expression)
print(result)
def calculate(formula):
# 注意 split 的用法
x, y, z = formula.split(" ")
x = float(x)
z = float(z)
if y == "+":
num = x + z
return round(num, 1)
elif y == "-":
num = x - z
return round(num, 1)
elif y == "*":
num = x * z
return round(num, 1)
elif y == "/":
if z != 0.0:
num = x / z
return round(num, 1)
else:
return "y can't be zero"
else:
return "The expression is not correct"
main()
# def calculate(formula):
# formula = formula.strip()
# if "+" in formula:
# num = float(formula[0]) + float(formula[4])
# return round(num, 1)
# elif "-" in formula:
# num = float(formula[0]) - float(formula[4])
# return round(num, 1)
# elif "*" in formula:
# num = float(formula[0]) * float(formula[4])
# return round(num, 1)
# elif "/" in formula:
# if formula[4] != "0":
# num = float(formula[0]) / float(formula[4])
# return round(num, 1)
# else:
# return "y can't be zero"
# else:
# return "The expression is not correct"
Meal Time
def main():
time_input = input("What time is it? ")
time_input = convert(time_input)
if 7.00 <= time_input <= 8.00:
print("breakfast time")
elif 12.00 <= time_input <= 13.00:
print("lunch time")
elif 18.00 <= time_input <= 19.00:
print("dinner time")
def convert(time):
# 12 小时制
if time.endswith("a.m"):
time = time.removesuffix("a.m").strip()
hour, minute = time.split(":")
hour = float(hour)
minute = round(float(minute) / 60, 2)
return hour + minute
elif time.endswith("p.m"):
time = time.removesuffix("p.m").strip()
hour, minute = time.split(":")
hour = float(hour) + 12.0
minute = round(float(minute) / 60, 2)
return hour + minute
else:
# 24h 制
hour, minute = time.split(":")
hour = float(hour)
minute = round(float(minute) / 60, 2)
return hour + minute
# def convert(time):
# # 24h 制
# hour, minute = time.split(":")
# hour = float(hour)
# minute = round(float(minute) / 60, 2)
# return hour + minute
if __name__ == "__main__":
main()