Python - if语句,如果输入是某个字符串

时间:2017-02-11 19:14:12

标签: python python-3.x if-statement input

所以我试图创建一种处理所有类型方程的计算器。您所要做的就是输入您需要帮助的内容,它会根据您需要帮助的方程式向您询问一系列问题,并返回一个值。我试图这样做,以便当输入某个字符串时,它会询问一系列问题。但是,无论我输入什么,它都会询问所有问题。 我正在使用Python 3.6。

    whichEquation = input("What are you having trouble with?   ")

if whichEquation:
    "interest"

r = float(input("What is the interest rate?: "))
C = float(input("Deposit cash: "))
t = float(input("For how many years will your deposit be invested?: "))
n = float(input("How many times per year is the interest compounded?: "))

interest = C * (1 + r/n)**(n*t)


print("Your future value is: ",interest,"dollars")

if whichEquation:
    "slope"

y1 = float(input("First y point: "))
y2 = float(input("Second y point: "))
x1 = float(input("First X point: "))
x2 = float(input("Second X point: "))

slope = (y2 - y1)/(x2 - x1)

print("The slope is:",slope)

那么,如果哪个等式是斜率或者兴趣,我怎么才能显示'斜率'方程或'兴趣'方程。

4 个答案:

答案 0 :(得分:2)

您的缩进不正确,应该是

if whichEquation == "slope":
    y1 = float(input("First y point: "))
    y2 = float(input("Second y point: "))
    x1 = float(input("First X point: "))
    x2 = float(input("Second X point: "))

    slope = (y2 - y1)/(x2 - x1)

    print("The slope is:",slope)

这是因为if语句下面缩进的任何内容都是if语句的操作。

这适用于两种IF语句,而不仅仅是斜率。

最后,IF语句使用“==”运算符检查某个项是否与特定内容匹配,这基本上是“等于”,因此if whichEquation == "slope"if (what ever is stored in) whichEquation is equal to "slope"相同

答案 1 :(得分:0)

解决此问题的最短方法是将所有相关代码置于if block

if whichEquation == "interest":
    r = float(input("What is the interest rate?: ")) 
    C = float(input("Deposit cash: ")) 
    t = float(input("For how many years will your deposit be invested?: "))
    n = float(input("How many times per year is the interest compounded?: ")) 
    interest = C * (1 + r/n)**(n*t) 
    print("Your future value is: ",interest,"dollars") 

希望这个帮助

答案 2 :(得分:0)

您可以像这样格式化代码:

whichEquation = input("What are you having trouble with?   ")

if whichEquation == "interest":

     r = float(input("What is the interest rate?: "))
     C = float(input("Deposit cash: "))
     t = float(input("For how many years will your deposit be   
     invested?: "))
     n = float(input("How many times per year is the interest compounded?: "))

     interest = C * (1 + r/n)**(n*t)


     print("Your future value is: ",interest,"dollars")

 elif whichEquation == "slope":
      y1 = float(input("First y point: "))
      y2 = float(input("Second y point: "))
      x1 = float(input("First X point: "))
      x2 = float(input("Second X point: "))

      slope = (y2 - y1)/(x2 - x1)

      print("The slope is:",slope)

这样,你的空格是正确的,并且会正确读取每个条件

答案 3 :(得分:0)

我相信你所说的,你希望程序根据选择的输入提出问题。

要完成此操作,必须添加==以检查两个变量是否相等。

if whichEquation == "slope":

这是因为python是使用if语句测试变量的多种方法。一些与数学相关的常见问题是:

*小于< *

*大于> *

小于或等于< =

大于或等于> =

等于==

不等于!=

我建议转到This python 3 doc,它会演示不同的IF声明条件。