从美国来的Python

2024-04-25 04:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

数学语句是“将x1和x2相加”

python的输出是:
输入语句或“E”退出程序:

然后用户输入:
加35和5

输出为:
答:加35和5=40

如何使用python编写这个输出?
输入语句或“E”退出程序:添加35和5
答:加35和5=40


Tags: 用户程序数学语句x1x2
2条回答

您需要使用.split()来分隔字符串中包含的用户输入。 (https://docs.python.org/3/library/stdtypes.html#str.split

user_input=input("enter the statement:")
x1=int(user_input.split()[0])
x2=int(user_input.split()[1])
print("Answer: Add {} and {} = {}".format(x1,x2,x1+x2))

但是您应该检查用户是否使用了“add”和“and”using if,以确保用户语句符合您的要求。你知道吗

action = input("Enter the statement [add] or E to exit the program: ")
if action == "add":
    x1 = int(input("enter the first number: "))
    x2 = int(input("enter the second number: "))
    print("Answer: Add {} and {} = {}". format(x1,x2,x1+x2))
elif action == "E" or action == "e":
    # exit action 
    exit("Goodbye")
else:
    # unexpected action
    exit("Error: invaild action {}".format(action))

相关问题 更多 >