Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help wioth elif
#1
a = int(input("What is your age : "))
b = int(input("How long have you beed in this address ? "))
c = float(input("What is your annual income ? "))
print (a)
print (b, " years")
print ("$ %8.2f" %c)

#age 

if ( a < 20 ):
    p = -10 
elif ( a > 21 & a < 30 ):
    p = 0 
elif ( a > 31 & a <= 50 ):
       print("Hi")
       p = 20
elif ( a > 50 ):
         p = 25 

print(p) 


if ( b < 1 ):
     p=p-5
elif ( b > 1 & b < 3 ):
     p=p+5
elif ( b > 4 & b < 8 ):
     p=p+12
elif ( b > 8 ):
     p=p+20

print(p)
Output
Output:
What is your age : 50 How long have you beed in this address ? 2 What is your annual income ? 200 50 2 years $ 200.00 0 5 
Can you please help as the 3rd elif does not get execued
buran write Dec-19-2021, 04:43 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
In Python the logical and is "and". "&" is a bitwise arithmetic and, just like it is in C. But this is Python so dump the unnecessary parenthesis. And while you are at it dump the 1 letter variable names. Use meaningful variable names.
if age < 20:
    p = -10
elif age >= 20 and age < 30:
    p = 0
This works, but it is still wrong. You aren't thinking about how the if and the elif work together. You are writing code like this:
if age < 20:
    p = -10  # I would rename p if I knew what it represented
if 20 <= age < 30:   # This is more readable than age >= 20 and age < 30, but it is still wrong.
    p = 0
if 30 <= age <= 50:
    p = 20
if age > 50:
    p = 25
Each of your conditional tests stands on it's own age < 20, 20 < age < 30 and so on. When you add an elif you are not taking advantage of what you already know.
if age < 20:
    p = -10
elif # How SHOULD we test for 20 <= age < 30?
If age is < 20 the program sets p to -10 and the jumps out of the if/elif. If the program reaches the elif you know that age is not < 20, so you don't need to test for that condition again.
if age < 20:
    p = -10
elif age < 30:  # We know age >= 20 if we get here.
    p = 0
The same goes for the next elif. If age < 30 you would not be reaching the next elif, so you don't have to test for < 30 again.
if age < 20:
    p = -10
elif age < 30:
    p = 0
elif age <= 50:
    p = 20
else:   # We know age > 50 if we get here.  No need to test
    p = 25
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Whats the right way to refactor this Big if/elif/elif ? pitosalas 1 2,237 Jul-28-2019, 05:52 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020