• No results found

There’s one final if statement trick that Python programmers like to use. Sometimes when you’re writing if/else statements, it comes in handy to reverse the order of the

“then” and else code blocks.

This can be because one of the code blocks is longer than the other, so you want to list the shorter one first. It also might be because the script logic says it makes more sense to check for a negative condition.

You can negate the result of a condition check by using the logical not operator (refer to Hour 5):

Click here to view code image

>>> a=1

>>> if not(a == 1): print(“The ‘a’ variable is not equal to 1”)

>>> if not(a == 2): print(“The ‘a’ variable is not equal to 2”) The ‘a’ variable is not equal to 2

>>>

The not operator reverses the normal result from the equality comparison—a False return code changes to a True. The opposite action occurs from what would have happened without the not operator.

By the Way: Negating Conditions

You might have noticed that you can negate a condition result by either using the not operand or by using the opposite numeric operand (!= instead of ==). Both methods produce the same result in your Python script.

Summary

This hour covers the basics of using the if structured command. The if statement enables you to set up one or more condition checks on the data you use in your Python script. This comes in handy when you need to program any type of logical comparisons in your Python scripts. The if statement by itself allows you to execute one or more

statements based on the result of a comparison test. You can add the else statement to provide an alternative group of statements to execute if the comparison fails.

You can expand the comparisons by using one or more elif statements in the if statement. You can just continue stringing elif statements together to continue comparing additional values.

In the next hour, we take a look at some more advanced control statements you can use to make your scripts more dynamic. We discuss the Python statements that let you loop through sections of your code multiple times!

Q&A

Q. Does Python support the select and case statements that are often found in other programming languages?

A. No, you have to use the elif statement to string together multiple if condition checks.

Q. Is there a limit on how many statements I can place in an if or else code block?

A. No, you can add as many statements as you need to control inside the if or else code blocks.

Q. Is there a limit on how many elif statements I can place in an if statement?

A. No, you can nest as many elif statements together as you need to check in your code. However, you might want to be careful because the more elif statements, the longer it will take for Python to evaluate the code values.

Workshop Quiz

1. Which comparison should you use to check whether the value stored in the z variable is greater than or equal to 10?

a. >

b. <

c. >=

d. ==

2. How would you write the if statement to display a message only if the value stored in the z variable is between 10 and 20 (not including those values)?

3. The semicolon (;) in an if statement acts as a “then.” True or false?

4. An if statement’s condition returns either a(n) _____ or a(n) _____ logic value.

5. Python uses _______ to designate a group of statements as being within an if statement code block.

6. When the if statement’s condition returns a False value code, statements within the ________ code block are executed, assuming no elif statements are included.

a. then b. elif c. outside d. else

7. Which of the following is not a numeric comparison operator?

a. !=

b. >

c. =>

d. ==

8. Which is greater: the string “Hello” or the string “Goodbye”?

9. When you run a function in Python, the function returns a(n) _____ _____, which can be tested in an if statement.

10. How would you write an if statement to give a game player status messages if a guess falls within 5, 10, or 15 of the actual value?

Answers

1. c. A common mistake in writing conditions is to forget that the greater-than and less-than symbols don’t include the specified number!

2. You can nest the variable between two numbers using greater-than or less-than symbols:

Click here to view code image

if 10 < z < 20: print(“This is the message”)

3. False. The colon (:) acts as the “then” in an if statement.

4. An if statement’s condition returns either a True or a False logic value.

5. Python uses indentation to designate a group of statements as being within an if statement code block.

6. d. else. When the if statement’s condition returns a False value code,

statements within the else code block are executed, assuming no elif statements are included.

7. c. =>. The => is not a numeric comparison operator; however, >= is a numeric comparison operator.

8. The string “Hello” is greater than the string “Goodbye” because it would come after “Goodbye” in a sort method and it is further along in the alphabet than

“Goodbye”.

9. When you run a function in Python, the function returns a return code, which can be tested in an if statement.

10. You can use the elif statement to add additional checks for a range of values. It’s important to remember to check smaller ranges first because the larger ranges will include the smaller ranges:

Click here to view code image

pi@raspberrypi:~$ cat py3prog/script0607.py

# Test for Answer within Range

#

answer=42 print()

guess=int(input(“What is your guess? “)) print()

#

####################################################

#

if (guess == answer):

print(“Correct!”)

#

elif (guess >= answer - 5) and (guess <= answer + 5):

print(“You’re within 5 of the correct number”)

#

elif (guess >= answer - 10) and (guess <= answer + 10):

print(“You’re within 10 of the correct number”)

#

elif (guess >= answer - 15) and (guess <= answer + 15):

print(“You’re within 15 of the correct number”)

# else:

print(“Sorry. You are WAY off of the correct number.”)

#

print()

pi@raspberrypi:~$

pi@raspberrypi:~$ python3 py3prog/script0607.py What is your guess? 42

Correct!

pi@raspberrypi:~$ python3 py3prog/script0607.py What is your guess? 57

You’re within 15 of the correct number pi@raspberrypi:~$

Hour 7. Learning About Loops

What You’ll Learn in This Hour:

How to perform repetitive tasks How to use the for loop

How to use the while loop How to use nested loops

In this hour, you learn about additional structured commands that help you reach your script’s goals using Python. Specifically, the focus is on repetitive tasks and which constructs are needed to accomplish those tasks.