hamcrest: how to input Boolean value - python

I am not sure why I see error when I have this code. all_is_valid is highlighted in yellow and when I hover over I see below error message. How do I avoid not highlighting it?
Expected type 'Matcher[bool]' (matched generic type 'Matcher[T]'), got 'bool' instead
all_is_valid=True
actual = None
if not actual:
all_is_valid = False
assert_that(True, all_is_valid,"test failed")

Trying to convert your input to bool won't work like that. Python considers any non-empty string True. So doing bool(input()) is basically the same as doing input() != ''. Both return true even if the input wasn't "True". Just compare the input given directly to the strings "True and "False":`isTrue = True
while isTrue:
isTrue = bool(int(input("Continue? 1 for yes, 0 for no: ")))`

Related

How return value of QCheckBox? [duplicate]

I came across a strange behaviour of python comparing a string with True/False.
I thought that python would print in the following:
if "Test" == True:
print("Hello1")
but it does not.
So I wrote some Test cases and I do not understand some of them.
if "Test" == True:
print("Hello1")
if "Test" == False:
print("Hello2")
#This I understand
if bool("Test") == True:
print("Hello3")
#This I understand too
if bool("") == False:
print("Hello4")
if "Test":
print("Hello5")
Output
>> Hello3
>> Hello4
>> Hello5
So I do not understand:
If Hello1 is not printed why is not Hello2 either?
Why does Hello5 get printed, is the cast to bool("Test") made implicit?
In the first two comparisons, you are checking whether the string "Test" has the same value as the object True or False. This is a value comparison.
If they have a different type, the comparison will return False. You can see this also when comparing lists, numbers etc.: [1]==1 (false), (1,)==[1] (false).
In the third and fourth comparisons, you are still doing a value comparison, but since both sides are of the same type (boolean), it will compare the values.
Hello5 is printed because it is not the null string "". You can see this by trying "Test" != None, which returns True.
While it is a comparison to None when it comes to most classes(None is Python's null value), Python's standard data types are compared to their "null" value, which are:
The empty string "" for strings,
[] for lists (similary () for tuples, {} for dictionaries),
0 for ints and floats,
just like a boolean comparison. Therefore it is not wrong to think of if expression as an implicit cast to if bool(expression).
What is going on under the hood is the evaluation of the __non-zero__(python2.x) or __bool__(python3.x) method of the class.
In the case of Hello1, Hello2 and Hello5 there is an object comparison and not boolean comparions.
That means that
the string-object "Test" is not the same as object True ("Hello1")
the string object "Test" is not the same as object False("Hello2")
but the string object "Test" is not None ("Hello5")

Unexpected behavior from Python

I'm new to Python and I am a bit confused with the way Python treats an empty object.
Consider this code piece;
a = {}
if a:
print "a is alive!"
else:
print "a is NOT alive!"
if not a:
print "NOT a!"
else:
print "a!"
if a is None:
print "a is None!"
else:
print "a is NOT None!"
I get the following output for this code piece.
a is NOT alive!
NOT a!
a is NOT None!
Edit::
I am under the assumption that an object initialized by {} is a Valid Object. Why doesn't Python treat it that way? and why do I get diff output for diff If conditions?
Edit 2::
In C++, when I say
Object obj;
if (obj){
}
It will enter the IF block if obj is NOT NULL(regardless if it is garbage value or whatever)
But the same thing when I translate to python.
a = {} #This is a valid object
if a:
# Doesn't work!
Why? and I read Python evaluates {} as False. Why is that?
Empy dict/sets/lists etc are evaluated as false. None is its own type, with only one possible value.
https://docs.python.org/2.4/lib/truth.html Tells you what is evaluated as true and false
I see nothing weird in your output.
Let's go step-by-step:
a is dictionary, more specifically a dictionary object;
a is a dictionary, but it's empty, so its truth value is False
Therefore:
The first if, since a is False, prints the else statement and that's right;
The second if, since not a evaluates to True because a is False, prints the if part and that's right too.
Last, but not least a is not a None object, but a dict object, so it's right too that the else part is taken and printed.
It is a valid python object, but it is empty, so it is treated as a False, the same goes for lists [] or numbers 0. You do have a dict, but it is not a None object.
with
a = {}
you are creating an dictionary object which is not NoneType you can
check the class of your object with
type(a)
which will give you:
type dict
if not a:
will return False if a has already any members and True if a is just and empty list

How to check if two strings are the same

H guys
silly question but one that is confusing me
print test
print test == "None"
in the terminal this prints out
None
False
as you can see test is None, but the check to see if they are the same comes back false
why is this ?
In python then None is a data type, so where you can have a number, or a string, you can also have None.
In your case, to check if it's None just remove the quotes:
print test == None
But you got the principle for testing if two strings are the same right:
test = "Hello"
print test
print test == "Hello"
Gives:
Hello
True
Try this:
print test
print test == "None"
print test == None
print type(test)
I don't think that you assigned the string "None" to test. It's likely that test is a NoneType so you should test it like this:
print test is None
The result is the same as test == None but the PEP8 says that you should use the keyword is instead of == to test for equality of singleton objects, like None.
It is because None is not a string, it is of type NoneType. Compare it to other languages 'null'. The string with value "None" is not the same as None.
Perhaps the documentation can help you more.

Are booleans mutable in python?

I have the following code in python:
def update(request, id):
success = 0
try:
product = Mattress.objects.get(id=id)
success = 1
except Mattress.DoesNotExist:
pass
if success == 1:
return render_to_response("success.html")
else:
return render_to_response('failure.html')
Is this code a valid way to check the "success" boolean. If the code passes through the try statement, will "success" be changed to 1 or is it remaining at 0?
Answering your question:
Are booleans mutable in python?
Yes and no. Variables that are assigned a boolean value are (probably always, and definitely in this case) mutable, yes. They're also not restricted to being assigned boolean values, as variables are not staticly typed.
But the booleans True and False themselves are not mutable. They are singletons that cannot be modified.
Looking at your actual code:
if success = 1:
Is not valid syntax, you want a == there. Also, idiomatically speaking you should not use 0 and 1 for success and failure values you should use True and False. So you should refactor to something like this:
def update(request):
success = False
try:
product = Mattress.objects.get(id=id)
success = True
except Mattress.DoesNotExist:
pass
if success:
return render_to_response("success.html")
else:
return render_to_response('failure.html')
Yes. success will be changed to 1 on success.
There are a few things wrong with this snippet.
Firstly, you're not using a boolean type. Python's booleans are True and False.
Second, you're not comparing in your if statement. That line isn't valid in Python 3. What you're looking for is: if success == 1: or if success == True:
You would still be able to assign a boolean value to a variable regardless of boolean immutability. I believe they are stored as a primitive type, so they're as immutable as any other primitive type.
You should consider using an actual boolean and not an integer. You can set success to true or false and Python will interpret them as keywords to the values of 1 and 0. Using numbers can be a bit tricky as some languages interpret things different. In some languages 0 is false but any value besides 0 is considered true. However the answer to your question is yes, it will work just fine.
Probably the question you are asking is not even related with the problem you are trying to solve. I think there is a a Pythonic way to achieve what you want by:
def update(request):
try:
product = Mattress.objects.get(id=id)
except Mattress.DoesNotExist:
template_name = 'failure.html'
else:
template_name = 'success.html'
return render_to_response(template_name)
Basically if the exception is thrown, i.e., the template you will render will be 'failure.html'. On the other hand, if the query is performed successfully, 'success.html' will be rendered.

Break statement in Python

I am trying to break out of a for loop, but for some reason the following doesn't work as expected:
for out in dbOutPut:
case_id = out['case_id']
string = out['subject']
vectorspace = create_vector_space_model(case_id, string, tfidf_dict)
vectorspace_list.append(vectorspace)
case_id_list.append(case_id)
print len(case_id_list)
if len(case_id_list) >= kcount:
print "true"
break
It just keeps iterating untill the end of dbOutput. What am I doing wrong?
I'm guessing, based on your previous question, that kcount is a string, not an int. Note that when you compare an int with a string, (in CPython version 2) the int is always less than the string because 'int' comes before 'str' in alphabetic order:
In [12]: 100 >= '2'
Out[12]: False
If kcount is a string, then the solution is add a type to the argparse argument:
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('-k', type = int, help = 'number of clusters')
args=parser.parse_args()
print(type(args.k))
print(args.k)
running
% test.py -k 2
yields
<type 'int'>
2
This confusing error would not arise in Python3. There, comparing an int and a str raises a TypeError.
Could it happen that kcount is actually a string, not an integer and, therefore, could never become less than any integer?
See string to int comparison in python question for more details.

Categories