bigted5 2 years ago Question: Assume that two variables, varA and varB, are assigned values, either numbers or strings. Write a piece of Python code that prints out one of the following messages: "string involved" if either varA or varB are strings "bigger" if varA is larger than varB "equal" if varA is equal to varB "smaller" if varA is smaller than varB Answer I tried: if (type(varA) or type(varB))=='str': print ("string involved") else: if varA>varB: print("bigger") if varA=varB: print("equal") if varA<varB: print("smaller") Shows wrong

• This Question is Open
1. BPX

There are two mistakes in your solution. The first is: Correct if varA=varB: if varA == varB: print("equal") print("equal") '=' is the assignment operator, and says 'put varB in varA' '==' is the equality operator, and says 'is varA equal to varB?' The second: if (type(varA) or type(varB))=='str': print ("string involved") Correct if type(varA) == type('a') or type(varB) == type('a'): print("string involved") type(varA) returns a 'type' object with the value of 'str', if varA is string. You can't compare a 'type' to a string (=='str'), so this doesn't work. Instead, compare the type of varA to the type of a string (for the example, I compared it to the type of 'a', you could do any string, or type(23) to get the 'int' type, etc.

2. harsimran_hs4

yes BPX pointed out correctly about assignment and equality operator and for comparision part BPX made it complex, tough it would work but to check if it`s string or not no need to do type('a') just do str for the comparision of string use: if (type(varA) or type(varB)) == str: don`t do 'str' as this implies that you are comapring the type of variable to the string str which is incorrect so use str only as it`s a data type

3. bwCA

use isinstance() for type checking http://docs.python.org/2.7/library/functions.html#isinstance http://docs.python.org/2.7/library/functions.html#type

4. bwCA
5. Mathuba

Just tried your method of type checking BPX, worked fine for me: name = 450 if(type(name) == str): print 'Yay a string' else: print 'No string here'

6. storozh

Another way of compare if your variables belong to type "string" is: if (type(a) == type(str()) or type(b) == type(str())):