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

5
  • Are you calling fname any where ? You don't have any else statements anywhere Commented Oct 27, 2015 at 18:59
  • yes. I add fname() in the end. Commented Oct 27, 2015 at 19:09
  • umm... do you do realize that a can never be simultaneously under 6 and over 10, right Commented Oct 27, 2015 at 19:15
  • These are the conditions: #if less than 5 b is 100; #greater than or equal 5 and less than 10 b is 200; #greater than or equal 10 and less than 20 b is 300; Commented Oct 27, 2015 at 19:36
  • printing b before calling fname() is not going to show changes made by fname. Commented Oct 27, 2015 at 19:36

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Could also make the conditions more readable using comparison chaining: elif 5 <= a_number <= 10:
@EthanFurman: You could also change all elif's to simple if's, because each return ends the function.
@VPfB: True, but if just scanning the code the elifs make it clear that only one branch will be executed.
how do i test the value of b?
@EthanFurman: Just found this: stackoverflow.com/questions/9191388/… We have just different personal preferences.
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.