Nesting “If Else” Can Seriously Damage Your Code Quality, Do THIS Instead In Python

Nesting “If Else” Can Seriously Damage Your Code Quality, Do THIS Instead In Python

Indently

1 год назад

131,794 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

DreamsAPI
DreamsAPI - 17.11.2023 04:00

Subscribed

Ответить
Klausberger
Klausberger - 25.10.2023 22:46

Missed the chance to also show people the match-case in python, as that is the next logical thing that a dev needs to know.

Ответить
William Cimini
William Cimini - 23.10.2023 01:22

def get_connection_status_message():
message = 'You are online!'
if not online:
message = 'You are offline'
if not internet:
message = 'No internet...'
if not paid:
message = 'User has not paid'
if not connection:
message = 'No connection...'
return message

print(get_connection_status_message())

Ответить
LegionLeague
LegionLeague - 03.10.2023 19:09

What about creating helper functions for each "if"? E.g. check_connection(), check_payment(), etc that return a boolean. And then the go_online() function would look like:
def go_online():
if all(check_connection(), check_payment(), check_internet()):
print("You are online!")

Would that work?

Ответить
Fco X
Fco X - 30.09.2023 06:36

dam not bad, nice vid

Ответить
Waffle
Waffle - 22.09.2023 21:27

This is also called inversion of your if statements. handle the sad paths first by inverting the statements, this forces the sad paths to the top

Ответить
Shivakumar Patil
Shivakumar Patil - 14.09.2023 17:35

What is the theme setup used in this video?

Ответить
Keanu Kim
Keanu Kim - 10.09.2023 06:52

THANK YOU FOR THIS VIDEO!❤

Ответить
Bilal Masud
Bilal Masud - 09.09.2023 13:40

No, I think creating a dictionary is a better option.

Ответить
Moroboshi Dan
Moroboshi Dan - 07.09.2023 21:57

I have a bit of a resistance for using more than one return into a function.

Ответить
sugo
sugo - 05.08.2023 21:42

never knew this is called a guard clause. i do this all the time because white space is an anti pattern. makes code too hard to read

Ответить
пажылой добряк 🇺🇦
пажылой добряк 🇺🇦 - 11.07.2023 19:06

Yandev be like: we don’t do that here

Ответить
TheBayru
TheBayru - 29.06.2023 11:15

This would be textbook case for "easier to ask forgiveness than permission" style in python?
try: connect()
except connection_error, payment_error, no_internet_error, user_not_online_exception: solve_the_problem

Ответить
Paulo de Tarso
Paulo de Tarso - 10.06.2023 14:08

I m not a programmer, but using lists or dictionaries couldn't be even better, like this:
connection=False
paid=True
internet=False
online=True
l=[ ( connection, 'Your connection is on', 'Your connection is off'),
(paid, 'You have paid', 'You haven\'t paid'),
(internet, 'No connection', 'Internet has offline'),
(online, 'You are online', 'You aren\'t online')]

for k,z,x in l:
if k == True:
print(f'{z}')
else:
print(f'{x}')

Could you comment this code?
TIA

Ответить
Ricardo Kazuo
Ricardo Kazuo - 28.05.2023 03:35

Nice! Is this a design pattern?

Ответить
Sándor Gombai
Sándor Gombai - 21.05.2023 22:42

What we see here is not the problem of nesting ifs but the the biggest design flaw of Python: the lack of block closing symbol.

Ответить
Cool Modder Jaydon
Cool Modder Jaydon - 11.04.2023 02:10

I mean, I'd use an if statement with &&/and to check every one of those. Unless I am in a situation where I can use return if certain conditions aren't met.

Ответить
Kevin Armengol
Kevin Armengol - 11.03.2023 17:47

Great tip. Much cleaner and readable.

Ответить
William Castro
William Castro - 25.01.2023 07:39

Excellent video! After watching your video Python makes more sense.
Question?
Originally i am familiar with JavaScript for a little over 1 year. Just switched to Python because I will be focused on backend for the Meta course.
From your personal experience do you feel learning Python gave you a better understanding of programming if you came from another programming language? Trying to understand how Python could improve my JavaScript Skills, thank you.

Ответить
OK Let’s Go
OK Let’s Go - 18.01.2023 15:07

Instead of having a return command inside every if statement, couldn’t you turn them into elif statements?

That way if one executes, the rest are skipped, no return command needed.

Then at the end have an “else” statement that confirms you are online if none of the other elif statements trigger .

Ответить
Hemanth
Hemanth - 16.01.2023 08:57

this really getting compact with those conditions 🤟🏾 me too not a fan of nested condition ,What if dependency b/w condition any idea ,

Ответить
sshah93
sshah93 - 15.01.2023 05:49

Hi thank you for another good tutorial and please take this as positive critism. I agree with you about the issue of reducing else statements, however I dont agree with your suggested solution, you have unnecessary return statements which could be avoided using `elif` statements instead.

Also I generally would have prefered one function call to print, here is my recommended solution for this:

def go_online():
message = 'You are online'

if not connection:
message = 'No connection...'

elif not paid:
message = 'User has not paid...'

elif not internet:
message = 'No Internet...'

print(message)

Ответить
Josip Drazin
Josip Drazin - 13.01.2023 01:13

Code damage is minor problem... I think that jumping from statement to variable to statement to function in memory can damage ram

Ответить
Jake Comay
Jake Comay - 12.01.2023 00:57

Can't you just do:

if not internet:
print("No internet")
elif not paid:
print("user has not paid")
else:
print("You are online")


it seems a lot more readable and it less lines of code

Ответить
Karl Braun
Karl Braun - 12.01.2023 00:34

I'm not sure why Pythonistas avoid elif in cases like this. It's exactly why the switch/case statements are added to other languages. Someone else mentioned that old-school methods strongly favor a single return point (back to the days of hardware debuggers, I think - also mathematical proofs of function correctness), and tend to go there as well, but also readability for simple boolean checks like this. (Obviously doesn't really apply to more complex checks where the elif is working on different types of comparisons - not readable at all).

Ответить
Federico Peralta
Federico Peralta - 11.01.2023 20:53

Can you do a quick follow-up video to check time efficiency?

Ответить
Pie Trader Detective
Pie Trader Detective - 11.01.2023 17:43

What about using np.select() ?

Ответить
coolcodingcat
coolcodingcat - 11.01.2023 17:40

I used to do a lot of nesting of if statement, but that was because I had read and had been taught it was bad to have more than one return statement per function.

Ответить
jimm
jimm - 11.01.2023 16:01

Why isnt my buddies `and` and `all` here!??

Ответить
Puzzled
Puzzled - 11.01.2023 11:00

I would use something like assert but instead it would print and not error

Ответить
Danchi
Danchi - 11.01.2023 10:10

I like to make those statements one liners

if not connection: return print("No connection")

Ответить
Natural Power
Natural Power - 11.01.2023 09:41

You know your code's bad when it looks like HTML but isn't HTML

Ответить
war10zx
war10zx - 11.01.2023 09:23

Ahh yes, the yandev indentation.

Ответить
Green_Irishman
Green_Irishman - 11.01.2023 08:59

def mult_checks(check_dict: dict[bool]) -> bool:
""" go through all items in dictionary
making sure they are True """

checks = all(list(check_dict.values()))

# Passed
if checks:
print('You are online...')
return True

# Failed
for k, v in check_dict.items():
if not v:
print(f'{k} Failed!')
return False



mult_checks({'online':True, 'paid': True, 'Internet': False})

Ответить
Moyo
Moyo - 11.01.2023 08:33

I can't thank you enough, keep these amazing videos coming please!

Ответить