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 integery
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()