python if evaluating True for False value - python

I have the following object field:
is_vendor = models.BooleanField(default=False)
I have the following if statement:
print(customer.is_vendor) //This prints False
if customer.is_vendor:
print('im a vendor') //This prints even the value above is false
else:
print('im not a vendor')
Why is this occurring?

You have a string in the field -- "False" as opposed to False. Which is cool for Django but not python. Try customer.is_vendor.to_python() instead. That will wrangle it into a boolean for you.
if "False": print 'True!' # is True
if False: print 'True!' # Nope.
if customer.is_vendor.to_python():
print "Is a vendor!"

Related

How to break the while loop if the condition is False?

I have a long function in which I am checking for different parameters and if any of the parameters is False, I don't want to execute the code further.
For your understanding, this is how I want to make it work
Email = True
while(Email == True):
print("Execute Me")
Email = False # Break the while loop here
print("Never execute me")
Here is the pseudo version of my code:
def users_preferences(prefs):
for pref in prefs:
send_email = True
while(send_email == True):
# Set send_email = False if email is not verified and don't move to the next line
# Set send_email = False if user's email is not a part of specific group
...
...
How can I break the loop if the condition is False at any point without further executing the code?
Edit: The problem with break statements is that it will become cumbersome to check the condition before running a new statement where you have number of statements
You can use a normal break statement:
Email = True
while Email:
print("Execute Me")
Email = False # Break the while loop here
if not Email:
break
print("Never execute me")
Edit: If the while loop doesn't do anything special, the code can be modified to be:
for pref in prefs:
if not is_email_verified(email) or not is_user_in_group(user, group):
continue
send_email(email)
Hello your code needs to be better indented. Also why haven't you tried using break statement to get out of the loop?
Email = True
while Email:
# do something
break
# continue doing something

handling if statement in python

following is the example of the code:
if test = "true":
print "hello"
elif test = "false":
pass
else:
print "Error"
In above code if test = "false" ,it will print "Error", but i want code to print nothing if test = "false" and exit
I tried with "continue" instead of "pass" , still the same. Can any one help me.
Thanks in Advance.
You are not comparing values but assigning them in your code.
Use '==' to compare values. Using single "=" will return in assigning a value, and it will be a syntax error when using with if
Assuming that test is a string.
So instead of :
if test = "true":
print "hello"
elif test = "false":
pass
else:
print "Error"
Do this:
if test == "true":
print "hello"
elif test == "false":
pass
else:
print "Error"
If test is a boolean, use:-
if test == True:
Or better simply:
if test:

Django ChoiceField changes Input from False to True

In Django, I have a ChoiceField that looks like this:
completed = forms.ChoiceField(choices = COMPLETED_CHOICES, required = True)
Here's the COMPLETED_CHOICES:
COMPLETED_CHOICES = (
('', ''),
(True, "Yes"),
(False, "No")
)
This is my model.py:
completed = models.BooleanField(choices = COMPLETED_CHOICES)
My problem is that every time I make a new instance, if I chose "No" on the form, the value will be saved as True. Meanwhile, if I chose "Yes", it'll save as True, which works as expected. Why is "No" only being affected?
Here's the relevant part of views.py
completed = form.cleaned_data['completed']
book = Book(
completed = completed,
)
book.save()
Your False value is probably passed from a form as a string. Take a look at the following code:
>>>print False
False
>>>
>>>print "False"
False
>>>
>>>
>>>if False:
... print 1
>>>
>>>if "False":
... print 1
1
Then you will need to parse the value from string by using for example
completed = form.cleaned_data['completed'] == 'True'
You can always check the type of given value by using type( form.cleaned_data['completed'] )

Python: Looping If Statement

friends = ["Bob","Mike","Ana","Tim","Dog"]
def is_buddy(name):
for friend in friends:
print friend
if friend == name:
return True
else:
return
print (is_buddy('Tim'))
What is the problem here? Why do I get False if I put in "Tim" or anyone else other than Bob?
Try:
def is_buddy(name):
for friend in friends:
if friend == name:
return True
return False
The problem is that you checked name against the first entry of the list which is Bob and you decided to make a boolean decision. You should have returned False only at the end where you checked against every element of the list.
The pythonic way to do what you want:
friends = ["Bob","Mike","Ana","Tim","Dog"]
def is_buddy(name):
if name in friends:
return True
else:
return False
print (is_buddy('Tim'))
Your problem is that else statement tigers return which causes the end of the for loop after 1'st iteration
What you probably want to do is to continue looping. So just remove else part from your function or replace return with something like print "not found"

use statement True and False in Python 2.7

i wish to use a statement "True" and "False" for my Python (2.7) command prompt
segmentation_accuracy(reference=REFERENCE, segmented=SEGMENTED, output=OUTPUT, method=METHOD, threshold=THRESHOLD, sep=SEP, header=HEADER)
if header is True print a text file with an header, if header is False print a text file without an header.
in Command Prompt:
REFERENCE = raw_input("Reference (*.shp):")
SEGMENTED = raw_input("Segmented (*.shp):")
METHOD = raw_input("Method (ke, pu, clinton):")
if METHOD != "ke" and METHOD != "pu" and METHOD != "clinton":
raise ValueError("%s is not a valid method" % METHOD)
if METHOD == "ke" or METHOD == "clinton":
THRESHOLD = input("Threshold (0.0 - 1.0):")
if not check_threshold(THRESHOLD):
raise AccuracyException("Threshold of %s is not valid" % THRESHOLD)
else:
THRESHOLD = None
SEP = raw_input("Sep:")
HEADER = raw_input("Header (True/False):")
if HEADER is not True or HEADER is not False:
raise ValueError("%s is not valid" % HEADER)
# output
OUTPUT = raw_input("Output (*.txt):")
when i run the command prompt in windows if i set raw_input("Header (True/False):") True or False, I always get the ValueError
i also used the combination
if HEADER != True or HEADER != False:
raise ValueError("%s is not valid" % HEADER)
with the same problem
The return value from raw_input is a string and not a boolean. Hence your is not True and is not False tests, although they have well-defined meaning, that meaning is not the meaning that you intend. You need to compare HEADER against string values.
So you would need, for example, code like this:
if HEADER.lower() == 'true':
I used tolower() to effect case-insensitive comparison. You may also want to strip off white space:
if HEADER.strip().lower() == 'true':
I'm sure you can fill in the test against false yourself.
Even if you did have a boolean, you should not use code like is not True or is False. You should test for truth with:
if somebool:
or
if not somebool:
because it is much more readable.
HEADER is a string, not a boolean. This will cause the is check to fail. Your comparison runs like this:
>>> "True" is not True
True
>>> "True" is not False
True
Note that a comparison with == will also fail:
>>> "True" == True
False
>>> "True" == False
False
Try comparing the value as a string:
if HEADER.tolower() == 'true':
#do something
elif HEADER.tolower() == 'false:
#do something else

Categories