Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Use of if - and operators
#1
Hi,

Is use of the code below accurate? I believe it is not however, my friend tells me it is.

age=int(input("Enter your age: "))

if  21<age<=25 :
    money=125

elif 21<age :
    money=100

else:
    money=250

print(money)
Reply
#2
It is valid python code, but I can't tell you if it produces the results you want. You didn't describe what the code is supposed to do

It is confusing because the 21 < age overlaps with 21<age<=25. The overlap is resolved because ages in the range 21 to 25 match the first comparison, and the rest of the if statement is skipped. Below is code that might be less confusing, but produces the same results:
if  21<age<=25 :
    money=125
 
elif 25<age :
    money=100
 
else:
    money=250
I think the following code is easier to read, but it might only be easier to read if you are a programmer. Here we have tons of overlap in the ranges, but like the code in your post, the overlap is resolved by the order of the comparisons.
if age < 21:
    money = 250
elif age <= 25:
    money = 125
else:
    money = 100
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Mixing Boolean and comparison operators Mark17 3 1,430 Jul-11-2022, 02:20 AM
Last Post: perfringo
  Magic Method Arithmetic Operators ClownPrinceOfCrime 3 2,336 Jan-10-2021, 03:24 PM
Last Post: ndc85430
  Class and Operators in Python rsherry8 1 2,001 May-27-2020, 07:09 PM
Last Post: buran
  Trying Comparison Operators PythonGainz 3 2,731 Mar-28-2020, 10:46 AM
Last Post: PythonGainz
  Mathematical Operators in String AgileAVS 1 2,405 Mar-04-2020, 04:14 PM
Last Post: Gribouillis
  A doubt with 'in' and 'not in' operators with strings newbieAuggie2019 7 3,620 Oct-23-2019, 03:11 PM
Last Post: perfringo
  understanding exponential and bitwise operators srm 1 2,063 Jun-15-2019, 11:14 AM
Last Post: ThomasL
  please help with this question about using operators to multiply a string? GilesTwigg 3 4,408 Feb-27-2019, 04:13 PM
Last Post: ichabod801
  Understanding compound operators -= NewatCode 3 3,195 Apr-25-2018, 05:03 PM
Last Post: Larz60+
  Pycharm shortcuts and operators don't run AzD 6 7,975 Oct-17-2017, 05:46 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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