1

Please help me with if and else statements in python. I like to set b according to value of a.

a=5
b=0
def fname():
    #less than 5
    if (a < 5): 
        b=100
    #greater than 5 or less than 10
    elif (a >= 5) and (a <= 10):
        b=200
    #greater than 10 or less than 20
    elif (a >10) and (a <= 20):
        b=300
print (b)
fname()

Thanks

Jorge Ben
  • 51
  • 7

2 Answers2

3

The b in fname is not the same b that is in the global/outer scope.

An ugly hack to make that work is to add global b inside fname.

A better way is to pass in the value for a to fname and have fname return the new value for b and assign it:

def fname(a_number):
    #less than 5
    if a_number < 5: 
        return 100
    #greater than 5 or less than 10
    elif 5 <= a_number <= 10:
        return 200
    #greater than 10 or less than 20
    elif 10 < a_number <= 20:
        return 300        

b = fname(a)

See this question for more information about scoping and Python.

Community
  • 1
  • 1
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
0
a = 5
b = 0


def fname():
    # less than 5
    if (a < 5):
        b = 100
        print(b)
    # greater than 5 or less than 10
    elif (a >= 5) and (a <= 10):
        b = 200
        print(b)
    # greater than 10 or less than 20
    elif (a > 10) and (a <= 20):
        b = 300
        print(b)


fname()

if u want to learn about if and else go to - https://youtu.be/no8c4KMYBdU