Address
:
[go:
up one dir
,
main page
]
Include Form
Remove Scripts
Session Cookies
Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
25 views
12 pages
Ch03 Conditionals
Computer Python Learning
Uploaded by
wawerucollins15
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save Ch03-Conditionals For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
25 views
12 pages
Ch03 Conditionals
Computer Python Learning
Uploaded by
wawerucollins15
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save Ch03-Conditionals For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 12
Search
Fullscreen
Chapter 3 Conditionals ‘The main topic of this chapter is the 3f statement, which executes different code depending on the state of the program. But first I want to introduce two new operators: floor division and modulus. 3.1. Floor division and modulus ‘The floor division operator, //, divides two numbers and rounds down to an integer. For ‘example, suppose the run time of a movie is 105 minutes. You might want to know how long that is in hours, Conventional division returns a floating-point number. But we don’t normally write hours with decimal points. Floor division returns the integer number of hours, rounding down: faimuces = 108 hours = minutes // 60 ‘To get the remainder, you could subtract off the number of hours in minutes: [remainder = minutes - hours + 60 An alternative is to use the modulus operator, , which divides two numbers and returns the remainder. [remainder = minutes 1 60 630 Chapter 3. Coné tionals The modulus operator is more useful than it seems. For example, you can check whether ‘one number is divisible by another—ifx 1, y is zero, then x is divisible by y. Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two digits. If you are using Python 2, division works differently, The division operator, /, performs floor division if both operands are integers, and floating-point division if either operand is afloat, 3.2. Boolean expressions A Boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces True if they are equal and False otherwise: t= ‘True and False are special values that belong to the type boo}; they are not strings: ype (irae) ype(Faize) ‘The =~ operator is one of the relational operators; the others are: x 4 x ds not equal te y x 4 x is greater than y x 4 x is less chan y x 4 x is greater than or equal to y xey 4 x is less than or equal to y Although these operations are probably familiar to you, the Python symbols are different from the mathematical symbols. A common error is to use a single equal sign (-) instead of 1 double equal sign (==). Remember that = is an assignment operator and == is a relational operator. There is no such thing as =< 3.3. Logical operators ‘There are three logical operators: and, or, and not. The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10.Conditional execution 31 U2 == 0 or ni3 == Ois trueif either or both of the conditions is true, thatis, if the number is divisible by 2 or 3. Finally, the not operator negates a Boolean expression, so not (x > y) is tueifx > yis false, that is, ifx is less than or equal to y. Strictly speaking, the operands of the logical operators should be Boolean expressions, but Python is not very strict. Any nonzero value is interpreted as True: a2 and Troe Troe This flexibility can be useful, but there are some subtleties to it that might be confusing. ‘You might want to avoid it (unless you know what you are doing). 3.4 Conditional execution In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement: ix 0: print (‘x ts poaitsve!) The Boolean expression after if is called the condition. If tis true, the indented statement runs. If not, nothing happens. Af statements have the same structure you'll use for repetition and function definitions: ‘a header followed by an indented body. Statements like this are called compound state- ments, There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, itis useful to have a body with no statements (usually as a place keeper for code you haven't written yet). In that case, you can use the pass statement, which does nothing, weed pass # TODO: need to handle negative values! 34.1 Example How would you program the following instructions: 1, Prompt the user for their velocity in kilometers per hour. 2. Print out the velocity in miles per hour. 3. Warn them they are above 70 mph and driving too fast. 4, War them they are below 40 mph and driving too slow.32 Chapter 3. Conditionals ae fa Jett Mecougn Jace main ph = float Camput CWnat 48 your eur ‘ph = kpheo, 621371392 spe an ups) (Velocity as mph = *, mph) rint(VAbove TOnph, driving too fast) Print(‘Below 40mph, driving too lov") pain 3.5 Alternative execution A second form of the if statement is “alternative execution”, in which there are two possi- bilities and the condition determines which one runs, Instead of having to code exka prine('x 42 even!) seek2 ie print('x 42 dé!) ‘The syntax looks like this: weak? rine (x 4a even") print (x 4 oda!) If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays an appropriate message. If the condition is false, the second set of statements rruns. Since the condition must be true or false, exactly one of the alternatives will run. The alternatives are called branches, because they are branches in the flow of execution, 3.5.1 Quadratic formula revisited In our previous quadratic formula example, when the expression inside the square root evaluated to a negative, the program would exit with an error. In this example, we will test the sign of the expression before we take a square root. Then we print out the results. [+ Progran: Compute roota of a quadratic import math Jaet main princ ("This program conputes the roots to a quadratic equat: prine('No real rosts') ‘sqroot = math. sqrs(aiserin) Feaet = (Cb + aqroot)/ ra) eae? = Cb — aqrost)/(ea)‘low symbols 33 Princo. Prine('The roots are: ", roott, root2) main 3.6 Flow symbols When working with more complicated logic, it can be very helpful to diagram the program, using symbols. A diagram illustrating the “flow” of the program is known as a flowchart. ‘A rectangle or square will indicate statements or certain computations, Arrows indicate the direction of computation or the "flow". A diamond shape will indicate a decision the code (a conditional). Note that not all authors will adhere to the same notation, but usually is pretty clear and these are just devices to convey the architecture of the program. Program Flow yes no Figure 3.1: Basic Flow Symbols ‘These figures have been produced by a Python module known as PyGraphViz. This module is just a wrapper for the GraphViz program. The source code is included in the Flowchart appendix. 3.6.1 Flowchart for Example 3.4.1 ‘The decision structure of the example can be expressed as a flowchart. This is shown in Figure 3.2Chapter 3. Conditio Figure 3.2: The decision structure of example 34.1 3.6.2. Flowchart for Example3.5.1 ‘The quadratic decision can also be viewed as flowchart. This is shown in Figure 3.3.is 35 Figure 33; The decision structure of example 35.1 3.7 Chained conditionals Sometimes there are more than two possibilities and we need more than two branches. ‘One way to express a computation like that is a chained conditional: weoy print (x se Ieee than 3") 40 greater than y") print ('x and y are equal!) eLif is an abbreviation of “else if”. Again, exactly one branch will run. There is no limit on the number of e1i£ statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one. Each condition is checked in order. Ifthe first is false, the next is checked, and so on. Ifone of them is true. the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first true branch runs.36 Chapter 3. Coné tionals 3.7.1 Rewriting Example 3.4.1 We can use the alternative execution construction to rework the example: fa Basie velocity program ft Jett Mecouga. Macleay ap = sa Nao ph eng to speed in uphs *)) asin 3.8 Nested conditionals ‘One conditional can also be nested within another. We could have written the example in the previous section like this: princ('x and y are equal) it x cy, print ('x 4s less than y') peint('x 1s greater than y') ‘The outer conditional contains two branches. The first branch contains a simple statement. ‘The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well Although the indentation of the statements makes the structure apparent, nested condi- tionals become difficult to read very quickly. It is a good idea to avoid them when you Logical operators often provide a way to simplify nested conditional statements. For ex: ample, we can rewrite the following code using a single conditional: » Print('x 1s @ positive single-digit aunbe ‘The print statement runs only if we make it past both conditionals, so we can get the same effect with the and operator: print('x 42 a positive single-digit number. ") For this kind of condition, Python provides a more concise option: if oex <0. Prine ('x 48 a positive single-digit number.)3.9, Debugging 37 3.8.1 Quadratic formula continued ‘The last quadratic formula example addressed the issue of having a negative discriminant which would raise an error, Another problem will occur when a = 0 which generates a division by zero error. We also split out the zero discriminant case for this example. ft Progran: Compute voots of a quedratic import auth der main) princ(*This progres computes the roots to « quedratic equation!” Print (tara + br te = 0% if boo. prine(Mio solseion") case! rint(*The single root is", (/e)) se: idiserin = bob 4 st diserie © 0 rint('Ne real roots") aif dlseria = 0; ‘root = ()/(24a) print("\aThere ia a double root at: ', root) ‘aqroot = meth. sqrt (aizeris) f= Cb + eqroet)/(2ea) eat? = (b= agrost)/@ea) print('\aThe roate are: ', roott, reat) pain 3.9 Debugging When a syntax or runtime error occurs, the error message contains a lot of information, but itcan be overwhelming. The most useful parts are usually: © What kind of error it was, and + Where it occurred Syntax errors are usually easy to find, but there are a few gotchas, Whitespace errors can be tricky because spaces and tabs are invisible and we are used to ignoring them, er In this example, the problem is that the second line is indented by one space. But the error ‘message points to y, which is misleading. In general, error messages indicate where the problem was discovered, but the actual error might be earlier in the code, sometimes on a previous line,38 Chapter 3. Coné tionals ‘The same is true of runtime errors, Suppose you are trying to compute a signal-to-noise ratio in decibels. The formula is SNRg = 101og;o(Pyignat/ Prose) - In Python, you might write something like this: sport sath signal pover = 9 ratio = signal_pover // noise_pover [decibels = 0 + mach 1ogi0(ratio) prine (decibels) When you run this program, you get an exception: Traceback (most recent call last) File “snr-py", line 5, in? decibels = 10 + math.1ogi0(ratie) ValueError: math domain error ‘The error message indicates line 5, but there is nothing wrong with that line. To find the real error, it might be useful to print the value of ratio, which turns out to be 0. The problem is in line 4, which uses floor division instead of floating-point division. You should take the time to read error messages carefully, but don’t assume that everything. they say is correct. 3.10 Glossary floor division: An operator, denoted //, that divides two numbers and rounds down (to- ward negative infinity) to an integer. modulus operator: An operator, denoted with a percent sign ((h), that returns the remain- der after floor division, Boolean expression: An expression whose value is either True or False. relational operator: One of the operators that compares its operands: = < >.< >e,and logical operator: One of the operators that combines boolean expressions: and, or, and not. conditional statement: A statement that controls the flow of execution depending on some condition, condition: The boolean expression in a conditional statement that determines which branch runs. ‘compound statement: A statement that consists of a header and a body. The header ends with a colon (). The body is indented relative to the header. branch: One of the alternative sequences of statements in a conditional statement. chained conditional: A conditional statement with a series of alternative branches. nested conditional: A conditional statement that appears in one of the branches of another conditional statement.3. Exe ses 39 3.11 Exercises Exercise 1: ‘The time module provides a function, also named time.tine, that returns the current Greenwich Mean Time in “the epoch”, which is an arbitrary time used as a reference point. ‘On UNIX systems, the epoch is 1 January 1970. The whole number portion of the value returned by time.time( ) is the number of seconds since the epoch. >>> import time >>> time. tine() 1437746094..5735958 Write a script that reads the current time and converts it to a time of day in hours, minutes, and seconds, plus the number of days since the epoch. Exercise 2: Fermat's Last Theorem says that there are no positive integers a, b, and c such that for any values of n greater than 2. 1, Write a script named fermat py that prompts the user to input values for a, b, ¢ and n, converts them to integers and checks to see if Fermat's theorem holds. If m is greater than 2 and yea the program should print, “Holy smokes, Fermat was wrong!” Otherwise the pro- gram should print, “No, that doesn’t work.” Exercise 3: If you are given three sticks, you may or may not be able to arrange them in a triangle. For ‘example, if one of the sticks is 12 inches long and the other two are one inch long, you will not be able to get the short sticks to meet in the middle, For any three lengths, there is a simple test to see if itis possible to form a triangle If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle, Otherwise, you can. (If the sum of two lengths equals the third, they form what is called a “degenerate” triangle.) 1. Write a script named is_triangle. py that prompts the user to input three stick lengths, converts them to integers, and then prints either “Yes” or “No”, depending. on whether you can or cannot form a triangle from sticks with the given lengths. Exercise 4: Assuming the user has entered numeric values for temp and wind, what is displayed when this code executes with the following data values?40 Chapter 3. Conditionals Af texp > 50: print( "Fine veather" ) mp > 30 if wind < 10: print( "Wear jacket" ) mp > 10 and vind < 20 print( "Wear coat" ) else print ( "Wear parka" ) elif elif 1. temp = 35, wind = 8 2. temp = 15, wind = 18 3. temp =52, wind =5 4, temp =42, wind = 15 5. There's a flaw in this code, such that some value pairs don’t display anything. How would you correct the code to cover all situations?
You might also like
Python Session 5 Conditional
PDF
No ratings yet
Python Session 5 Conditional
24 pages
Lec03 Control Flow
PDF
No ratings yet
Lec03 Control Flow
52 pages
Operators Control Structure
PDF
No ratings yet
Operators Control Structure
57 pages
Python
PDF
No ratings yet
Python
119 pages
Introduction To Python Programming
PDF
No ratings yet
Introduction To Python Programming
121 pages
Unit III
PDF
No ratings yet
Unit III
77 pages
Py Unit - 3
PDF
No ratings yet
Py Unit - 3
53 pages
CEN111: Programming I Lecture 4: Conditionals and Recursion: International Burch University
PDF
No ratings yet
CEN111: Programming I Lecture 4: Conditionals and Recursion: International Burch University
9 pages
GE8151 Unit III
PDF
No ratings yet
GE8151 Unit III
40 pages
Condional Statement N Loops
PDF
No ratings yet
Condional Statement N Loops
39 pages
Module 3. Control Structures
PDF
No ratings yet
Module 3. Control Structures
27 pages
PSPP UNIT Three New
PDF
No ratings yet
PSPP UNIT Three New
33 pages
02 - Conditional Execution and Functions
PDF
No ratings yet
02 - Conditional Execution and Functions
56 pages
Pythonlearn. Chapter 3. Extract (43-54)
PDF
No ratings yet
Pythonlearn. Chapter 3. Extract (43-54)
12 pages
Python Unit II SPN 2023
PDF
No ratings yet
Python Unit II SPN 2023
38 pages
Conditionals and Iteration
PDF
No ratings yet
Conditionals and Iteration
42 pages
Form 1 4 Functional Writings Samples
PDF
No ratings yet
Form 1 4 Functional Writings Samples
58 pages
Unit Iii Control Flow
PDF
No ratings yet
Unit Iii Control Flow
45 pages
Lecture04 Conditionalexecution
PDF
No ratings yet
Lecture04 Conditionalexecution
31 pages
Unit Iii Control Flow, Functions
PDF
No ratings yet
Unit Iii Control Flow, Functions
55 pages
DMPP Selection Mathematical Functions
PDF
No ratings yet
DMPP Selection Mathematical Functions
30 pages
03programming and Mathematical Thinking A Gentle Introduction To Discrete Math Featuring Python (Allan M. Stavely) (Z-Library) - 43-54
PDF
No ratings yet
03programming and Mathematical Thinking A Gentle Introduction To Discrete Math Featuring Python (Allan M. Stavely) (Z-Library) - 43-54
12 pages
Python Unit 3 Complete Notes
PDF
No ratings yet
Python Unit 3 Complete Notes
21 pages
ENGG1003 08 PythonBasics-A
PDF
No ratings yet
ENGG1003 08 PythonBasics-A
27 pages
Unit-5 - Control Flow - Functions - File Handling
PDF
No ratings yet
Unit-5 - Control Flow - Functions - File Handling
20 pages
01 Boolean Values Conditional Execution Loops List Processing and Bitwise Operation
PDF
No ratings yet
01 Boolean Values Conditional Execution Loops List Processing and Bitwise Operation
27 pages
Python Control Structures - 2
PDF
No ratings yet
Python Control Structures - 2
30 pages
Lbobgdt-04-Python Branch Iteration
PDF
No ratings yet
Lbobgdt-04-Python Branch Iteration
11 pages
Conditionals and Iterations
PDF
No ratings yet
Conditionals and Iterations
20 pages
Conditionals and Iterations
PDF
No ratings yet
Conditionals and Iterations
21 pages
Lecture 3
PDF
No ratings yet
Lecture 3
11 pages
Lesson3 Python
PDF
No ratings yet
Lesson3 Python
12 pages
Conditional Execution: Boolean Expressions
PDF
No ratings yet
Conditional Execution: Boolean Expressions
12 pages
3.1. If Statements: 3.1.1. Simple Conditions
PDF
No ratings yet
3.1. If Statements: 3.1.1. Simple Conditions
24 pages
Unit Iii Control Flow, Functions 9
PDF
No ratings yet
Unit Iii Control Flow, Functions 9
34 pages
3.2.5 Conditional Execution
PDF
No ratings yet
3.2.5 Conditional Execution
5 pages
3.2 Logical Operators: True True
PDF
No ratings yet
3.2 Logical Operators: True True
5 pages
Unit III PDF
PDF
No ratings yet
Unit III PDF
38 pages
New - Unit 3
PDF
No ratings yet
New - Unit 3
61 pages
Day - 03 More On Conditional Statements
PDF
No ratings yet
Day - 03 More On Conditional Statements
50 pages
Intro To CS Lec05
PDF
No ratings yet
Intro To CS Lec05
36 pages
Conditional Execution: 3.1 Boolean Expressions
PDF
No ratings yet
Conditional Execution: 3.1 Boolean Expressions
12 pages
UNIT1 - PDS - Basic Python
PDF
No ratings yet
UNIT1 - PDS - Basic Python
130 pages
Grade 6 - Handout On Python Programming 2023-24
PDF
No ratings yet
Grade 6 - Handout On Python Programming 2023-24
12 pages
Conditionals and Iterations
PDF
No ratings yet
Conditionals and Iterations
38 pages
Module-4-INTEGRATIVE PROGRAMMING 2
PDF
No ratings yet
Module-4-INTEGRATIVE PROGRAMMING 2
7 pages
GE3151 Unit III
PDF
No ratings yet
GE3151 Unit III
38 pages
Lecture 3.1 - Conditions in Python
PDF
No ratings yet
Lecture 3.1 - Conditions in Python
39 pages
Chapter 03
PDF
No ratings yet
Chapter 03
98 pages
Conditional Execution: Boolean Expressions
PDF
No ratings yet
Conditional Execution: Boolean Expressions
12 pages
Hill. rs2020
PDF
No ratings yet
Hill. rs2020
11 pages
Conditionals and Loops - Beginning Python Programming For Aspiring Web Developers
PDF
No ratings yet
Conditionals and Loops - Beginning Python Programming For Aspiring Web Developers
16 pages
2 Python Control Structures
PDF
No ratings yet
2 Python Control Structures
39 pages
2 Conditional
PDF
No ratings yet
2 Conditional
16 pages
Chapter 03
PDF
No ratings yet
Chapter 03
98 pages
SSG Slide 6&7 (Control Flow)
PDF
No ratings yet
SSG Slide 6&7 (Control Flow)
28 pages
Unit 1
PDF
No ratings yet
Unit 1
51 pages
Parallelism and Contrast Workshop
PDF
No ratings yet
Parallelism and Contrast Workshop
3 pages
Turner
PDF
No ratings yet
Turner
3 pages
CH 5 - Eng - Decisions
PDF
No ratings yet
CH 5 - Eng - Decisions
22 pages
Python
PDF
No ratings yet
Python
27 pages
Topic 4 - Python-Conditional Execution 2
PDF
No ratings yet
Topic 4 - Python-Conditional Execution 2
39 pages
TKD2019 NAB A4-Preview
PDF
No ratings yet
TKD2019 NAB A4-Preview
1 page
Introduction To Programming With Python
PDF
No ratings yet
Introduction To Programming With Python
34 pages
Ch04 Iteration
PDF
No ratings yet
Ch04 Iteration
12 pages
Ch06 Strings
PDF
No ratings yet
Ch06 Strings
12 pages
Acting Fundamentals Brochure Optimized
PDF
No ratings yet
Acting Fundamentals Brochure Optimized
2 pages
Common Name of Water Hyacinth
PDF
No ratings yet
Common Name of Water Hyacinth
2 pages