输入某些输入后,我可以忽略某些代码吗?

时间:2020-09-01 04:16:02

标签: python if-statement math input user-input

我正在python上构建一个基本的计算器,以了解编程的基础知识和其他知识。基本上我的问题是,当我用计算器对一个数字进行平方运算时,它仍然会询问我的第二个数字,尽管它会吐出正确的答案,但我仍然希望它在使用平方函数时不询问我的第二个数字。 / p>

name = input("Enter your name: ")
lastname = input("Enter your last name: ")
print("Welome " + name + " " + lastname + "!")
num1 = float(input("Enter a number to calculate: "))
Component = input("*, /, +, -...?????: ")
num2 = float(input("Enter your last number...: "))
if Component == "*":
    print(num1 * num2)
if Component == "+":
    print(num1 + num2)
if Component == "/":
    print(num1 / num2)
if Component == "-":
    print(num1 - num2)
if Component == "sqr":
    print(num1 ** 2)
    

1 个答案:

答案 0 :(得分:1)

请尝试使用此num2 = float(input("Enter your last number...: ")) if Component.strip() != "sqr" else 0

完整代码在这里:

name = input("Enter your name: ")
lastname = input("Enter your last name: ")
print("Welome " + name + " " + lastname + "!")
num1 = float(input("Enter a number to calculate: "))
Component = input("*, /, +, -...?????: ")
num2 = float(input("Enter your last number...: ")) if Component.strip() != "sqr" else 0
if Component == "*":
    print(num1 * num2)
if Component == "+":
    print(num1 + num2)
if Component == "/":
    print(num1 / num2)
if Component == "-":
    print(num1 - num2)
if Component == "sqr":
    print(num1 ** 2)