Home > Blockchain >  How do I increment a value in a while loop in Python>?
How do I increment a value in a while loop in Python>?

Time:10-01

I'm trying to find the area of a space under a curve on a graph. This is being done by getting the area of multiple rectangles with a constant base but incrementing heights. The rectangles are between two endpoints given my the user. The incrementations are from point a and by 0.1 until it reaches point b. My question is, how do I increment the x in a while loop if I can't use a range? I tried using the = bit so x= a =1 but that gives a syntax error.

print("Computing the area under the curve x^2   x   1")
a = int(input("Enter the left end point a: x ="))
b = int(input("Enter the left end point b: x ="))


base = 0.1
x = 0

while (a <= x <= b):
    area = (x**2   x   1) * base
    x  = area

CodePudding user response:

Try increment left end point variable a instead of defining and incrementing x.

print("Computing the area under the curve x^2   x   1")
a = int(input("Enter the left end point a: x = "))
b = int(input("Enter the right end point b: x = "))

base = 0.1
total_area = 0

while (a <= b):
    sub_area = (a**2   a   1) * base
    total_area  = sub_area
    a  = base
    
print("The area under the curve is "   str(total_area))

CodePudding user response:

  1. x should be equal to a, because the range of x is from a to b.
  2. In each loop, you have to let a add 0.1.
  3. Set a new variable to record the total area, such as 'total_area' as follows.
    print("Computing the area under the curve x^2   x   1")
    a = int(input("Enter the left end point a: x ="))
    b = int(input("Enter the left end point b: x ="))
    
    
    base = 0.1
    x = a # 1
    total_area = 0
    
    while (a <= x <= b):
        area = (x**2   x   1) * base
        x  = base # 2
        total_area  = area # 3
    
    print(total_area)
  • Related