Home > Blockchain >  Python For-Loop, range() with conditions
Python For-Loop, range() with conditions

Time:11-02

My code as follows:

`x = input("Please enter the value of x: ")
y = input("Please enter the value of y: ")
sum = 0

for num in range(x, y 1):
    islessthanorzero = int(x) <= 0 or int(y) <= 0
    isgreaterthanx = int(x) > int(y)
    if x.isnumeric() and y.isnumeric():
        if islessthanorzero:
            print('not greater than zero')
            exit()    
        if isgreaterthanx: 
            print('not greater than y')
            exit()
        else: 
            print ('not numeric')
            exit()
    else:
        sum  = num
    
print(f"The sum of numbers between {x} and {y} is {sum}")  
`

Requirement: users to input 2 values. sum of all numbers from x to y Conditions:

  1. x and y are numeric
  2. x and y are higher than zero
  3. y must be greater than
  4. Use a for loop to calculate the sum of numbers from x to y

The program will have to make sure all the conditions met before adding the sum of all numbers from x to y, else terminates the program.

The logic for if-else works but I'm not able to implement into the for loop.

Please help

CodePudding user response:

Your if-else conditions were wrong placed:

x = input("Please enter the value of x: ")
y = input("Please enter the value of y: ")
s = 0

if x.isnumeric() and y.isnumeric():
    if int(x) <= 0 or int(y) <= 0:
        print('not greater than zero')  
    if int(x) > int(y): 
        print('not greater than y')
        exit()
    else: 
        s  = sum(list(range(int(x), int(y))))
else:
    print ('not numeric')
    exit()
    
print(f"The sum of numbers between {x} and {y} is {s}") 

CodePudding user response:

The input gives a string which you need to convert it to a integer before using them in a mathematical expression.

So I'd suggest you to cast the values as integers:

x = int(input("Please enter the value of x: "))

y = int(input("Please enter the value of y: "))

  • Related