If a variable can take n values should we check for the validity of the values or assume that if all the n-i checks fail it would be the nth value.
For example if we have a variable that stores gender as M or F. Use this:
If gender = "M"
do male_processing
else
do female_processing
endif
Or this:
If gender = "M"
do male_processing
else
if gender = "F"
do female_processing
else
print "Something has gone wrong Gender has a value " Gender
endif
endif
As per the latest statistics, Python is the main coding language for around 80% of developers. The presence of extensive libraries in Python facilitates artificial intelligence, data science, and machine learning processes. Currently, Python is trending and can be regarded as the king of programming languages.
JavaScript and Python, two of the most popular languages in the startup industry, are in high demand. Most startups use Python-based backend frameworks such as Django (Python), Flask (Python), and NodeJS (JavaScript). These languages are also considered to be the best programming languages to learn for beginners.
For that example, I wouldn't use IF at all, I'd either use SWITCH for your second example
switch (gender)
case "M":
do male_processing
break
case "F":
do female_processing
break
default:
print "Something has gone wrong Gender has a value " Gender
endswitch
or for your first example, I'd simply treat exceptions as an error using ASSERT
assert (gender = "M" or gender = "F")
Shortly - that depends on what type the variable is. If it's a boolean or an enumeration of some sort and there's no other value it can possible have (including null
), a simple else
clause will suffice.
You can even add a simple comment like so:
if male:
do_male_stuff()
else: #obviously female
do_female_stuff()
Having something like this just seems wrong:
bool = SOME_BOOLEAN_VALUE
if bool:
do1()
elif not bool:
do2()
else:
huh() #?!?!
Bottom line: have an if
/else
/else if
clause for each possible scenario, but no more than that, and keep it readable.
...or, in OO world you could create a base class, say Gender
and extend it with Male
and Female
classes. Instead of assigning value 'M' or 'F' to a variable, you could assign an instance of Male or Female class. Then simply call a method specified in the base class, for example doGenderSpecificStuff()
. No need for if-elses there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With