Question

def isdark():
    dark = True

dark = isdark()

if dark:
    print('bt')
else:
    print('dasd')

Im trying to make it so that it prints bt but instead is prints dasd, why isn't the dark = is dark() condition working?

Was it helpful?

Solution 2

isdark() is a function with no return statement, so it returns None by default. So dark never evaluates to true.

You're confusing yourself by using the same variable in two different ways. Here's how I would do it:

dark = True
def isdark():
     return dark

if isdark():
    print('bt')
else:
     print('dasd')

or more simply:

isdark = True

if isdark:
    print('bt')
else:
     print('dasd')

or even more simply:

isdark = True
print('bt' if isdark else 'dasd')

OTHER TIPS

def isdark():
     dark = True

Here, you are not assigning to the global variable, but creating a local variable and assigning True to it. Instead, you can return the value from the function like this

def isdark():
     return True

Since, you are assigning the returned value to the dark variable with this line

dark = isdark()

whatever you return from isdark will be assigned to dark.

Apart from that, if you are using that just to check that if condition, you can rewrite the code like this

if isdark():
    print('bt')
else:
    print('dasd')

You need to return dark, like this:

def isdark():
     dark = True
     return dark

dark = isdark()

if dark:
    print('bt')
else:
     print('dasd')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top