Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
>>> c = 0
>>> if (c): print("The b variable has been set")
>>>

So be careful when evaluating variables for Boolean values!


Evaluating Function Results


A feature related to Boolean comparisons is Python’s ability to test the result of functions. When you
run a function in Python, the function returns a return code. You can test the return code by using the
if statement to determine whether the function succeeded or failed.


A good example of this is using the isdigit() method in Python. The isdigit() method checks
whether the supplied value can be converted to a number, and it returns a True Boolean value if it
can. You can use this to check whether a value provided to your script by a user is a number. Listing
6.6 shows an example of how to use it.


LISTING 6.6 Using Functions in Conditions


Click here to view code image


#!/usr/bin/python

name = input("Please enter your name: ")
age = input("Please enter your age: ")
if (age.isdigit()):
print("Hello", name, ",your age is", age)
else:
print("Sorry, the age you entered is not a number")

The if statement checks whether the age variable is a digit. If it is, the script displays the data. If
not, it displays an error message.


Here’s an example of running the program to test it out:


Click here to view code image


$ python3 script0606.py
Please enter your name: Rich
Please enter your age: test
Sorry, the age you entered is not a number
$ python script0606.py
Please enter your name: Rich
Please enter your age: 10
Hello Rich, your age is 10
$

The first test uses bad data for the age value, and the script catches that! The second test uses correct
data, and that works just fine.


Checking Complex Conditions


So far in this hour, all the examples have used just one comparison check within the condition. Python
also allows you to group multiple comparisons together in a single if statement. This section show

Free download pdf