Python if This Condition Is Met Then Try Again
3.1. If Statements¶
3.1.1. Simple Conditions¶
The statements introduced in this chapter will involve tests or conditions. More syntax for weather will be introduced later on, but for at present consider simple arithmetic comparisons that directly translate from math into Python. Effort each line separately in the Shell
ii < v three > 7 x = 11 10 > ten 2 * x < x type ( True )
You see that weather condition are either True
or False
. These are the merely possible Boolean values (named subsequently 19th century mathematician George Boole). In Python the name Boolean is shortened to the blazon bool
. It is the type of the results of true-imitation conditions or tests.
Annotation
The Boolean values True
and Simulated
accept no quotes effectually them! Just as '123'
is a string and 123
without the quotes is not, 'Truthful'
is a string, not of type bool.
3.1.2. Elementary if
Statements¶
Run this example program, suitcase.py. Endeavour it at least twice, with inputs: 30 and then 55. As you an encounter, you get an extra result, depending on the input. The main code is:
weight = bladder ( input ( "How many pounds does your suitcase weigh? " )) if weight > 50 : impress ( "There is a $25 charge for baggage that heavy." ) print ( "Thank you for your business organization." )
The centre 2 line are an if
statement. It reads pretty much similar English. If it is true that the weight is greater than l, then print the statement about an extra charge. If it is not true that the weight is greater than 50, then don't practice the indented office: skip press the extra luggage accuse. In any event, when y'all have finished with the if
statement (whether it really does annihilation or not), become on to the next statement that is not indented under the if
. In this case that is the statement printing "Thanks".
The general Python syntax for a simple if
argument is
If the condition is true, so do the indented statements. If the condition is not true, then skip the indented statements.
Another fragment every bit an example:
if remainder < 0 : transfer = - balance # transfer plenty from the fill-in account: backupAccount = backupAccount - transfer residual = balance + transfer
As with other kinds of statements with a heading and an indented block, the block tin have more than than ane statement. The assumption in the instance above is that if an account goes negative, it is brought back to 0 past transferring coin from a backup account in several steps.
In the examples in a higher place the option is between doing something (if the condition is True
) or nothing (if the condition is Simulated
). Often there is a option of two possibilities, only ane of which will exist done, depending on the truth of a condition.
iii.i.3. if
- else
Statements¶
Run the case plan, clothes.py
. Try it at to the lowest degree twice, with inputs 50 and then eighty. As y'all tin can see, you go different results, depending on the input. The main code of clothes.py
is:
temperature = float ( input ( 'What is the temperature? ' )) if temperature > seventy : print ( 'Wear shorts.' ) else : print ( 'Article of clothing long pants.' ) impress ( 'Get some do outside.' )
The middle four lines are an if-else statement. Again information technology is close to English language, though you might say "otherwise" instead of "else" (but else is shorter!). In that location are two indented blocks: One, like in the elementary if
statement, comes right after the if
heading and is executed when the condition in the if
heading is true. In the if
- else
course this is followed by an else:
line, followed past another indented cake that is only executed when the original condition is false. In an if
- else
statement exactly ane of two possible indented blocks is executed.
A line is also shown dedented adjacent, removing indentation, most getting exercise. Since it is dedented, it is non a part of the if-else argument: Since its amount of indentation matches the if
heading, it is always executed in the normal forward flow of statements, later the if
- else
argument (whichever block is selected).
The general Python if
- else
syntax is
if
status :indentedStatementBlockForTrueCondition
else:
indentedStatementBlockForFalseCondition
These statement blocks can have any number of statements, and can include about any kind of argument.
See Graduate Exercise
3.1.four. More Provisional Expressions¶
All the usual arithmetic comparisons may be made, but many exercise not employ standard mathematical symbolism, mostly for lack of proper keys on a standard keyboard.
Significant | Math Symbol | Python Symbols |
---|---|---|
Less than | < | < |
Greater than | > | > |
Less than or equal | ≤ | <= |
Greater than or equal | ≥ | >= |
Equals | = | == |
Non equal | ≠ | != |
There should not be infinite between the two-symbol Python substitutes.
Notice that the obvious option for equals, a single equal sign, is not used to cheque for equality. An annoying second equal sign is required. This is because the unmarried equal sign is already used for assignment in Python, so information technology is not available for tests.
Warning
It is a common error to utilise merely i equal sign when y'all mean to test for equality, and not make an assignment!
Tests for equality do not brand an assignment, and they do not require a variable on the left. Whatever expressions tin can exist tested for equality or inequality ( !=
). They exercise non need to be numbers! Predict the results and try each line in the Beat out:
x = 5 x x == v x == vi 10 x != half dozen x = 6 six == ten 6 != x 'hi' == 'h' + 'i' 'Howdy' != 'hi' [ one , 2 ] != [ 2 , 1 ]
An equality check does not make an assignment. Strings are case sensitive. Order matters in a list.
Try in the Beat:
When the comparison does non make sense, an Exception is caused. [1]
Following upwards on the word of the inexactness of float arithmetic in String Formats for Float Precision, confirm that Python does not consider .1 + .two to be equal to .3: Write a simple condition into the Beat out to exam.
Here is another example: Pay with Overtime. Given a person'southward work hours for the calendar week and regular hourly wage, calculate the total pay for the calendar week, taking into account overtime. Hours worked over 40 are overtime, paid at 1.v times the normal rate. This is a natural identify for a function enclosing the calculation.
Read the setup for the function:
def calcWeeklyWages ( totalHours , hourlyWage ): '''Return the full weekly wages for a worker working totalHours, with a given regular hourlyWage. Include overtime for hours over twoscore. '''
The trouble clearly indicates 2 cases: when no more than than 40 hours are worked or when more than xl hours are worked. In case more than 40 hours are worked, information technology is convenient to introduce a variable overtimeHours. Y'all are encouraged to think about a solution before going on and examining mine.
Y'all can endeavour running my complete case program, wages.py, also shown below. The format functioning at the end of the principal office uses the floating signal format (Cord Formats for Float Precision) to bear witness two decimal places for the cents in the reply:
def calcWeeklyWages ( totalHours , hourlyWage ): '''Return the total weekly wages for a worker working totalHours, with a given regular hourlyWage. Include overtime for hours over 40. ''' if totalHours <= twoscore : totalWages = hourlyWage * totalHours else : overtime = totalHours - 40 totalWages = hourlyWage * 40 + ( 1.v * hourlyWage ) * overtime return totalWages def main (): hours = float ( input ( 'Enter hours worked: ' )) wage = bladder ( input ( 'Enter dollars paid per hour: ' )) total = calcWeeklyWages ( hours , wage ) print ( 'Wages for {hours} hours at ${wage:.2f} per hr are ${total:.2f}.' . format ( ** locals ())) main ()
Here the input was intended to be numeric, but it could be decimal and so the conversion from string was via bladder
, not int
.
Below is an equivalent culling version of the body of calcWeeklyWages
, used in wages1.py
. It uses just i general calculation formula and sets the parameters for the formula in the if
argument. There are generally a number of ways you lot might solve the same problem!
if totalHours <= twoscore : regularHours = totalHours overtime = 0 else : overtime = totalHours - forty regularHours = 40 render hourlyWage * regularHours + ( 1.five * hourlyWage ) * overtime
- The
in
boolean operator: -
There are also Boolean operators that are applied to types others than numbers. A useful Boolean operator is
in
, checking membership in a sequence:>>> vals = [ 'this' , 'is' , 'information technology] >>> 'is' in vals Truthful >>> 'was' in vals Imitation
It tin can also be used with
not
, asnot in
, to hateful the opposite:>>> vals = [ 'this' , 'is' , 'it] >>> 'is' not in vals False >>> 'was' not in vals True
In full general the two versions are:
item
in
sequenceparticular
not in
sequence
Detecting the need for if
statements: Similar with planning programs needing``for`` statements, you desire to be able to translate English descriptions of bug that would naturally include if
or if
- else
statements. What are some words or phrases or ideas that advise the use of these statements? Call back of your own and then compare to a few I gave: [2]
3.i.4.1. Graduate Exercise¶
Write a plan, graduate.py
, that prompts students for how many credits they have. Print whether of not they take enough credits for graduation. (At Loyola University Chicago 120 credits are needed for graduation.)
three.ane.four.ii. Head or Tails Exercise¶
Write a program headstails.py
. It should include a function flip()
, that simulates a unmarried flip of a money: It randomly prints either Heads
or Tails
. Attain this by choosing 0 or one arbitrarily with random.randrange(2)
, and employ an if
- else
statement to print Heads
when the result is 0, and Tails
otherwise.
In your main program have a simple repeat loop that calls flip()
ten times to examination it, so you generate a random sequence of x Heads
and Tails
.
iii.1.iv.3. Strange Function Exercise¶
Salve the instance program jumpFuncStub.py
every bit jumpFunc.py
, and consummate the definitions of functions jump
and master
as described in the function documentation strings in the program. In the jump
role definition use an if
- else
statement (hint [3]). In the main
function definition utilize a for
-each loop, the range function, and the leap function.
The jump
part is introduced for use in Foreign Sequence Practise, and others later that.
3.ane.five. Multiple Tests and if
- elif
Statements¶
Often you want to distinguish betwixt more than than two distinct cases, simply conditions just accept ii possible results, True
or Fake
, and so the just direct choice is between ii options. As anyone who has played "20 Questions" knows, you can distinguish more cases by further questions. If there are more than two choices, a single test may only reduce the possibilities, but further tests can reduce the possibilities farther and farther. Since most any kind of statement can be placed in an indented statement block, one choice is a farther if
argument. For example consider a function to convert a numerical form to a letter course, 'A', 'B', 'C', 'D' or 'F', where the cutoffs for 'A', 'B', 'C', and 'D' are 90, 80, 70, and 60 respectively. I mode to write the function would be exam for one grade at a time, and resolve all the remaining possibilities inside the next else
clause:
def letterGrade ( score ): if score >= ninety : letter = 'A' else : # grade must be B, C, D or F if score >= 80 : alphabetic character = 'B' else : # class must be C, D or F if score >= 70 : letter = 'C' else : # class must D or F if score >= 60 : letter = 'D' else : letter = 'F' return letter
This repeatedly increasing indentation with an if
statement every bit the else
block can be abrasive and distracting. A preferred alternative in this situation, that avoids all this indentation, is to combine each else
and if
block into an elif
cake:
def letterGrade ( score ): if score >= 90 : letter = 'A' elif score >= 80 : letter = 'B' elif score >= 70 : letter = 'C' elif score >= 60 : letter of the alphabet = 'D' else : letter of the alphabet = 'F' return letter
The most elaborate syntax for an if
- elif
- else
statement is indicated in general below:
if
condition1:
indentedStatementBlockForTrueCondition1
elif
condition2:
indentedStatementBlockForFirstTrueCondition2
elif
condition3:
indentedStatementBlockForFirstTrueCondition3
elif
condition4:
indentedStatementBlockForFirstTrueCondition4
else:
indentedStatementBlockForEachConditionFalse
The if
, each elif
, and the final else
lines are all aligned. There can be any number of elif
lines, each followed past an indented block. (Iii happen to be illustrated above.) With this construction exactly 1 of the indented blocks is executed. It is the ane respective to the first True
condition, or, if all atmospheric condition are False
, it is the block after the concluding else
line.
Exist conscientious of the strange Python wrinkle. It is elif
, not elseif
. A program testing the letterGrade function is in example program grade1.py
.
See Grade Exercise.
A final culling for if
statements: if
- elif
-.... with no else
. This would mean changing the syntax for if
- elif
- else
above and then the concluding else:
and the cake after it would be omitted. Information technology is similar to the bones if
argument without an else
, in that information technology is possible for no indented block to exist executed. This happens if none of the conditions in the tests are true.
With an else
included, exactly one of the indented blocks is executed. Without an else
, at most one of the indented blocks is executed.
if weight > 120 : print ( 'Sorry, we tin non take a suitcase that heavy.' ) elif weight > 50 : print ( 'There is a $25 accuse for luggage that heavy.' )
This if
- elif
statement only prints a line if there is a trouble with the weight of the suitcase.
iii.1.5.1. Sign Do¶
Write a program sign.py
to inquire the user for a number. Print out which category the number is in: 'positive'
, 'negative'
, or 'nothing'
.
3.one.5.2. Course Exercise¶
In Idle, load grade1.py
and save it as grade2.py
Modify grade2.py
so it has an equivalent version of the letterGrade function that tests in the contrary guild, first for F, then D, C, .... Hint: How many tests do you need to do? [4]
Be sure to run your new version and test with different inputs that test all the unlike paths through the program. Be careful to test around cut-off points. What does a grade of 79.6 imply? What well-nigh exactly 80?
3.ane.five.3. Wages Practice¶
* Change the wages.py
or the wages1.py
example to create a plan wages2.py
that assumes people are paid double time for hours over 60. Hence they go paid for at most 20 hours overtime at ane.5 times the normal rate. For instance, a person working 65 hours with a regular wage of $x per hr would piece of work at $10 per hour for forty hours, at 1.5 * $10 for twenty hours of overtime, and 2 * $10 for 5 hours of double time, for a full of
ten*40 + ane.v*10*20 + ii*10*5 = $800.
You lot may find wages1.py
easier to arrange than wages.py
.
Be sure to test all paths through the program! Your plan is likely to be a modification of a program where some choices worked before, just in one case you change things, retest for all the cases! Changes can mess up things that worked before.
3.one.6. Nesting Command-Flow Statements¶
The power of a language similar Python comes largely from the variety of ways bones statements can exist combined. In particular, for
and if
statements can exist nested inside each other'south indented blocks. For example, suppose you want to print only the positive
numbers from an arbitrary list of numbers in a function with the post-obit heading. Read the pieces for now.
def printAllPositive ( numberList ): '''Impress only the positive numbers in numberList.'''
For example, suppose numberList
is [iii, -5, 2, -1, 0, 7]
. You want to process a list, so that suggests a for
-each loop,
but a for
-each loop runs the aforementioned code torso for each element of the list, and we only want
for some of them. That seems like a major obstruction, but recall closer at what needs to happen concretely. As a human, who has eyes of amazing capacity, you are fatigued immediately to the actual right numbers, 3, two, and seven, only clearly a reckoner doing this systematically will have to check every number. In fact, there is a consistent action required: Every number must be tested to run across if it should be printed. This suggests an if
statement, with the condition num > 0
. Endeavour loading into Idle and running the case plan onlyPositive.py
, whose code is shown below. It ends with a line testing the function:
def printAllPositive ( numberList ): '''Print simply the positive numbers in numberList.''' for num in numberList : if num > 0 : print ( num ) printAllPositive ([ 3 , - 5 , two , - 1 , 0 , 7 ])
This idea of nesting if
statements enormously expands the possibilities with loops. Now different things can be done at different times in loops, equally long as there is a consequent exam to allow a selection between the alternatives. Shortly, while
loops will too exist introduced, and you will encounter if
statements nested inside of them, besides.
The rest of this section deals with graphical examples.
Run example plan bounce1.py
. It has a red ball moving and bouncing obliquely off the edges. If you lot watch several times, y'all should encounter that information technology starts from random locations. Besides yous tin can echo the program from the Vanquish prompt after you take run the script. For instance, right after running the program, try in the Shell
The parameters give the amount the shape moves in each animation step. Yous can attempt other values in the Shell, preferably with magnitudes less than 10.
For the remainder of the description of this example, read the extracted text pieces.
The animations before this were totally scripted, saying exactly how many moves in which direction, but in this example the direction of motion changes with every bounciness. The program has a graphic object shape
and the central blitheness step is
only in this instance, dx and dy accept to change when the ball gets to a boundary. For instance, imagine the brawl getting to the left side as it is moving to the left and up. The bounciness obviously alters the horizontal part of the motion, in fact reversing it, merely the ball would still continue upwards. The reversal of the horizontal part of the motion means that the horizontal shift changes management and therefore its sign:
but dy
does not demand to modify. This switch does not happen at each animation pace, but only when the ball reaches the edge of the window. It happens simply some of the time - suggesting an if
statement. Still the condition must be determined. Suppose the center of the brawl has coordinates (10, y). When x reaches some particular x coordinate, call it xLow, the brawl should bounciness.
The edge of the window is at coordinate 0, but xLow
should non exist 0, or the ball would exist one-half way off the screen before bouncing! For the border of the ball to hit the edge of the screen, the x coordinate of the center must be the length of the radius away, then actually xLow
is the radius of the ball.
Animation goes quickly in small steps, then I cheat. I let the ball to take i (small, quick) stride by where it really should go ( xLow
), and so we reverse it so it comes back to where it belongs. In particular
There are similar bounding variables xHigh
, yLow
and yHigh
, all the radius abroad from the bodily edge coordinates, and similar conditions to test for a bounciness off each possible border. Note that whichever edge is striking, one coordinate, either dx or dy, reverses. I way the drove of tests could be written is
if x < xLow : dx = - dx if x > xHigh : dx = - dx if y < yLow : dy = - dy if y > yHigh : dy = - dy
This approach would crusade in that location to be some extra testing: If information technology is true that x < xLow
, then information technology is impossible for it to exist truthful that x > xHigh
, so we do not need both tests together. We avert unnecessary tests with an elif clause (for both 10 and y):
if 10 < xLow : dx = - dx elif ten > xHigh : dx = - dx if y < yLow : dy = - dy elif y > yHigh : dy = - dy
Note that the middle if
is not inverse to an elif
, because it is possible for the ball to achieve a corner, and need both dx
and dy
reversed.
The program also uses several methods to read part of the country of graphics objects that we have not used in examples yet. Diverse graphics objects, like the circle we are using as the shape, know their middle point, and information technology can exist accessed with the getCenter()
method. (Actually a clone of the indicate is returned.) Also each coordinate of a Indicate
tin can exist accessed with the getX()
and getY()
methods.
This explains the new features in the central role divers for billowy around in a box, bounceInBox
. The animation arbitrarily goes on in a simple repeat loop for 600 steps. (A later instance volition better this behavior.)
def bounceInBox ( shape , dx , dy , xLow , xHigh , yLow , yHigh ): ''' Breathing a shape moving in jumps (dx, dy), bouncing when its center reaches the low and high ten and y coordinates. ''' delay = . 005 for i in range ( 600 ): shape . move ( dx , dy ) center = shape . getCenter () ten = center . getX () y = middle . getY () if 10 < xLow : dx = - dx elif 10 > xHigh : dx = - dx if y < yLow : dy = - dy elif y > yHigh : dy = - dy fourth dimension . sleep ( delay )
The program starts the ball from an arbitrary bespeak inside the commanded rectangular bounds. This is encapsulated in a utility function included in the plan, getRandomPoint
. The getRandomPoint function uses the randrange
function from the module random
. Note that in parameters for both the functions range
and randrange
, the end stated is past the last value actually desired:
def getRandomPoint ( xLow , xHigh , yLow , yHigh ): '''Render a random Point with coordinates in the range specified.''' 10 = random . randrange ( xLow , xHigh + 1 ) y = random . randrange ( yLow , yHigh + 1 ) return Point ( ten , y )
The full program is listed below, repeating bounceInBox
and getRandomPoint
for completeness. Several parts that may be useful later, or are easiest to follow as a unit of measurement, are separated out every bit functions. Make sure you see how it all hangs together or ask questions!
''' Show a ball bouncing off the sides of the window. ''' from graphics import * import time , random def bounceInBox ( shape , dx , dy , xLow , xHigh , yLow , yHigh ): ''' Animate a shape moving in jumps (dx, dy), bouncing when its center reaches the depression and high x and y coordinates. ''' filibuster = . 005 for i in range ( 600 ): shape . move ( dx , dy ) center = shape . getCenter () x = center . getX () y = center . getY () if 10 < xLow : dx = - dx elif ten > xHigh : dx = - dx if y < yLow : dy = - dy elif y > yHigh : dy = - dy time . sleep ( delay ) def getRandomPoint ( xLow , xHigh , yLow , yHigh ): '''Return a random Indicate with coordinates in the range specified.''' ten = random . randrange ( xLow , xHigh + 1 ) y = random . randrange ( yLow , yHigh + 1 ) render Bespeak ( x , y ) def makeDisk ( eye , radius , win ): '''return a cherry disk that is drawn in win with given eye and radius.''' deejay = Circumvolve ( center , radius ) deejay . setOutline ( "red" ) disk . setFill ( "blood-red" ) disk . depict ( win ) return disk def bounceBall ( dx , dy ): '''Make a ball bounce around the screen, initially moving past (dx, dy) at each jump.''' win = GraphWin ( 'Ball Bounce' , 290 , 290 ) win . yUp () radius = ten xLow = radius # centre is separated from the wall by the radius at a bounce xHigh = win . getWidth () - radius yLow = radius yHigh = win . getHeight () - radius eye = getRandomPoint ( xLow , xHigh , yLow , yHigh ) ball = makeDisk ( center , radius , win ) bounceInBox ( brawl , dx , dy , xLow , xHigh , yLow , yHigh ) win . close () bounceBall ( three , 5 )
three.1.half-dozen.one. Short String Exercise¶
Write a program short.py
with a part printShort
with heading:
def printShort ( strings ): '''Given a listing of strings, print the ones with at near three characters. >>> printShort(['a', 'long', i']) a 1 '''
In your main program, examination the function, calling it several times with different lists of strings. Hint: Find the length of each string with the len
function.
The function documentation hither models a mutual approach: illustrating the beliefs of the office with a Python Beat out interaction. This part begins with a line starting with >>>
. Other exercises and examples volition also document behavior in the Beat out.
three.1.half-dozen.2. Even Impress Exercise¶
Write a program even1.py
with a role printEven
with heading:
def printEven ( nums ): '''Given a list of integers nums, impress the even ones. >>> printEven([4, ane, 3, two, 7]) 4 2 '''
In your main program, test the role, calling it several times with dissimilar lists of integers. Hint: A number is even if its residual, when dividing by two, is 0.
3.1.6.3. Fifty-fifty List Exercise¶
Write a program even2.py
with a office chooseEven
with heading:
def chooseEven ( nums ): '''Given a listing of integers, nums, render a list containing just the even ones. >>> chooseEven([4, 1, iii, 2, vii]) [iv, 2] '''
In your main program, test the function, calling it several times with different lists of integers and printing the results in the chief program. (The documentation cord illustrates the function phone call in the Python shell, where the return value is automatically printed. Remember, that in a program, you only print what you explicitly say to print.) Hint: In the part, create a new list, and append the advisable numbers to it, earlier returning the outcome.
3.i.6.4. Unique List Do¶
* The madlib2.py
plan has its getKeys
function, which first generates a list of each occurrence of a cue in the story format. This gives the cues in order, merely probable includes repetitions. The original version of getKeys
uses a quick method to remove duplicates, forming a set from the list. There is a disadvantage in the conversion, though: Sets are not ordered, and so when you iterate through the resulting ready, the order of the cues will likely bear no resemblance to the club they beginning appeared in the listing. That outcome motivates this problem:
Copy madlib2.py
to madlib2a.py
, and add a part with this heading:
def uniqueList ( aList ): ''' Render a new listing that includes the showtime occurrence of each value in aList, and omits later repeats. The returned list should include the first occurrences of values in aList in their original gild. >>> vals = ['true cat', 'dog', 'cat', 'bug', 'domestic dog', 'emmet', 'dog', 'bug'] >>> uniqueList(vals) ['cat', 'domestic dog', 'bug', 'ant'] '''
Hint: Process aList
in guild. Use the in
syntax to but append elements to a new listing that are non already in the new list.
Afterward perfecting the uniqueList
part, replace the last line of getKeys
, and then it uses uniqueList
to remove duplicates in keyList
.
Check that your madlib2a.py
prompts you lot for cue values in the guild that the cues first appear in the madlib format string.
3.1.7. Compound Boolean Expressions¶
To be eligible to graduate from Loyola University Chicago, you lot must have 120 credits and a GPA of at to the lowest degree 2.0. This translates directly into Python as a chemical compound condition:
credits >= 120 and GPA >= 2.0
This is true if both credits >= 120
is truthful and GPA >= two.0
is truthful. A brusk example programme using this would be:
credits = bladder ( input ( 'How many units of credit do you have? ' )) GPA = bladder ( input ( 'What is your GPA? ' )) if credits >= 120 and GPA >= 2.0 : print ( 'You are eligible to graduate!' ) else : print ( 'Yous are not eligible to graduate.' )
The new Python syntax is for the operator and
:
condition1
and
condition2
The compound status is truthful if both of the component conditions are truthful. It is imitation if at least one of the weather is imitation.
Run into Congress Exercise.
In the last example in the previous section, there was an if
- elif
statement where both tests had the same block to exist done if the condition was truthful:
if 10 < xLow : dx = - dx elif ten > xHigh : dx = - dx
There is a simpler way to land this in a sentence: If x < xLow or x > xHigh, switch the sign of dx. That translates directly into Python:
if x < xLow or x > xHigh : dx = - dx
The word or
makes some other chemical compound condition:
condition1
or
condition2
is true if at to the lowest degree one of the conditions is true. It is false if both conditions are imitation. This corresponds to one way the word "or" is used in English. Other times in English "or" is used to mean exactly 1 alternative is true.
Warning
When translating a problem stated in English using "or", be conscientious to determine whether the significant matches Python's or
.
It is oft user-friendly to encapsulate complicated tests inside a function. Think how to complete the function starting:
def isInside ( rect , signal ): '''Return Truthful if the signal is inside the Rectangle rect.''' pt1 = rect . getP1 () pt2 = rect . getP2 ()
Think that a Rectangle
is specified in its constructor past two diagonally oppose Point
south. This example gives the first use in the tutorials of the Rectangle
methods that recover those two corner points, getP1
and getP2
. The program calls the points obtained this way pt1
and pt2
. The x and y coordinates of pt1
, pt2
, and point
can exist recovered with the methods of the Point
blazon, getX()
and getY()
.
Suppose that I introduce variables for the 10 coordinates of pt1
, point
, and pt2
, calling these 10-coordinates end1
, val
, and end2
, respectively. On first endeavour you might decide that the needed mathematical relationship to test is
Unfortunately, this is not enough: The merely requirement for the 2 corner points is that they exist diagonally opposite, not that the coordinates of the 2nd betoken are higher than the corresponding coordinates of the first indicate. It could exist that end1
is 200; end2
is 100, and val
is 120. In this latter case val
is between end1
and end2
, merely substituting into the expression higher up
is Simulated. The 100 and 200 need to be reversed in this example. This makes a complicated state of affairs. Also this is an issue which must be revisited for both the x and y coordinates. I innovate an auxiliary role isBetween
to deal with one coordinate at a time. It starts:
def isBetween ( val , end1 , end2 ): '''Return True if val is between the ends. The ends do not need to exist in increasing order.'''
Clearly this is true if the original expression, end1 <= val <= end2
, is truthful. You lot must also consider the possible case when the order of the ends is reversed: end2 <= val <= end1
. How exercise we combine these 2 possibilities? The Boolean connectives to consider are and
and or
. Which applies? You only demand one to exist true, and then or
is the proper connective:
A right but redundant function body would be:
if end1 <= val <= end2 or end2 <= val <= end1 : return True else : return Faux
Check the significant: if the compound expression is Truthful
, return Truthful
. If the condition is False
, return False
– in either case render the same value equally the exam status. See that a much simpler and neater version is to merely render the value of the condition itself!
render end1 <= val <= end2 or end2 <= val <= end1
Note
In general y'all should not demand an if
- else
statement to choose between true and false values! Operate straight on the boolean expression.
A side comment on expressions similar
Other than the two-graphic symbol operators, this is similar standard math syntax, chaining comparisons. In Python any number of comparisons tin be chained in this way, closely approximating mathematical annotation. Though this is good Python, be aware that if you lot endeavour other high-level languages like Java and C++, such an expression is gibberish. Some other mode the expression can be expressed (and which translates directly to other languages) is:
end1 <= val and val <= end2
Then much for the auxiliary function isBetween
. Back to the isInside
function. Yous can employ the isBetween
part to cheque the x coordinates,
isBetween ( point . getX (), p1 . getX (), p2 . getX ())
and to check the y coordinates,
isBetween ( point . getY (), p1 . getY (), p2 . getY ())
Again the question arises: how do you combine the two tests?
In this example we need the indicate to exist both between the sides and between the top and bottom, so the proper connector is and.
Remember how to finish the isInside
method. Hint: [5]
Sometimes yous want to examination the opposite of a condition. As in English you can utilise the word non
. For instance, to test if a Indicate was not inside Rectangle Rect, you could use the condition
not isInside ( rect , signal )
In general,
not
condition
is True
when condition is Imitation
, and Simulated
when status is True
.
The example plan chooseButton1.py
, shown beneath, is a complete program using the isInside
function in a simple awarding, choosing colors. Pardon the length. Do check it out. It will be the starting point for a number of improvements that shorten information technology and get in more powerful in the next department. First a brief overview:
The program includes the functions isBetween
and isInside
that have already been discussed. The program creates a number of colored rectangles to use as buttons and also equally flick components. Bated from specific information values, the code to create each rectangle is the aforementioned, and then the action is encapsulated in a role, makeColoredRect
. All of this is fine, and will be preserved in later versions.
The nowadays master function is long, though. It has the usual graphics starting code, draws buttons and picture elements, and then has a number of code sections prompting the user to choose a color for a picture element. Each code section has a long if
- elif
- else
test to encounter which button was clicked, and sets the colour of the motion-picture show element appropriately.
'''Make a choice of colors via mouse clicks in Rectangles -- A demonstration of Boolean operators and Boolean functions.''' from graphics import * def isBetween ( x , end1 , end2 ): '''Return Truthful if ten is betwixt the ends or equal to either. The ends practice not need to be in increasing order.''' render end1 <= x <= end2 or end2 <= x <= end1 def isInside ( bespeak , rect ): '''Return True if the betoken is inside the Rectangle rect.''' pt1 = rect . getP1 () pt2 = rect . getP2 () return isBetween ( point . getX (), pt1 . getX (), pt2 . getX ()) and \ isBetween ( point . getY (), pt1 . getY (), pt2 . getY ()) def makeColoredRect ( corner , width , height , color , win ): ''' Return a Rectangle drawn in win with the upper left corner and colour specified.''' corner2 = corner . clone () corner2 . move ( width , - height ) rect = Rectangle ( corner , corner2 ) rect . setFill ( color ) rect . depict ( win ) return rect def master (): win = GraphWin ( 'option Colors' , 400 , 400 ) win . yUp () # right side up coordinates redButton = makeColoredRect ( Point ( 310 , 350 ), 80 , 30 , 'red' , win ) yellowButton = makeColoredRect ( Bespeak ( 310 , 310 ), lxxx , 30 , 'yellow' , win ) blueButton = makeColoredRect ( Indicate ( 310 , 270 ), 80 , 30 , 'blueish' , win ) business firm = makeColoredRect ( Point ( 60 , 200 ), 180 , 150 , 'gray' , win ) door = makeColoredRect ( Point ( 90 , 150 ), 40 , 100 , 'white' , win ) roof = Polygon ( Point ( 50 , 200 ), Indicate ( 250 , 200 ), Signal ( 150 , 300 )) roof . setFill ( 'black' ) roof . draw ( win ) msg = Text ( Point ( win . getWidth () / 2 , 375 ), 'Click to choose a house color.' ) msg . describe ( win ) pt = win . getMouse () if isInside ( pt , redButton ): color = 'red' elif isInside ( pt , yellowButton ): color = 'xanthous' elif isInside ( pt , blueButton ): color = 'bluish' else : color = 'white' house . setFill ( color ) msg . setText ( 'Click to choose a door color.' ) pt = win . getMouse () if isInside ( pt , redButton ): colour = 'red' elif isInside ( pt , yellowButton ): color = 'yellowish' elif isInside ( pt , blueButton ): color = 'blue' else : colour = 'white' door . setFill ( color ) win . promptClose ( msg ) main ()
The merely further new feature used is in the long return statement in isInside
.
return isBetween ( point . getX (), pt1 . getX (), pt2 . getX ()) and \ isBetween ( point . getY (), pt1 . getY (), pt2 . getY ())
Recall that Python is smart plenty to realize that a statement continues to the next line if there is an unmatched pair of parentheses or brackets. Above is some other state of affairs with a long statement, simply in that location are no unmatched parentheses on a line. For readability information technology is best not to make an enormous long line that would run off your screen or paper. Standing to the adjacent line is recommended. Y'all can make the final character on a line be a backslash ( '\\'
) to indicate the statement continues on the next line. This is non particularly bully, only information technology is a rather rare situation. Nigh statements fit neatly on one line, and the creator of Python decided it was best to make the syntax simple in the most mutual situation. (Many other languages require a special statement terminator symbol similar ';' and pay no attention to newlines). Extra parentheses here would not hurt, so an alternative would be
render ( isBetween ( point . getX (), pt1 . getX (), pt2 . getX ()) and isBetween ( point . getY (), pt1 . getY (), pt2 . getY ()) )
The chooseButton1.py program is long partly considering of repeated code. The next department gives some other version involving lists.
three.1.7.one. Congress Exercise¶
A person is eligible to be a United states Senator who is at least xxx years old and has been a US citizen for at to the lowest degree 9 years. Write an initial version of a program congress.py
to obtain age and length of citizenship from the user and print out if a person is eligible to be a Senator or not.
A person is eligible to exist a The states Representative who is at to the lowest degree 25 years old and has been a US citizen for at least 7 years. Elaborate your plan congress.py
so information technology obtains historic period and length of citizenship and prints out only the one of the following three statements that is accurate:
- You lot are eligible for both the Firm and Senate.
- You eligible only for the Firm.
- You are ineligible for Congress.
3.1.eight. More String Methods¶
Here are a few more than string methods useful in the adjacent exercises, assuming the methods are applied to a string s
:
-
s
.startswith(
pre)
returns
True
if cord southward starts with string pre: Both'-123'.startswith('-')
and'downstairs'.startswith('down')
areTrue
, but'ane - 2 - 3'.startswith('-')
isFalse
. -
due south
.endswith(
suffix)
returns Truthful if string southward ends with string suffix: Both
'whoever'.endswith('e'er')
and'downstairs'.endswith('airs')
areTruthful
, only'i - 2 - 3'.endswith('-')
isFake
. -
s
.supersede(
sub,
replacement,
count)
returns a new string with upward to the first count occurrences of string sub replaced past replacement. The replacement can be the empty string to delete sub. For instance:
south = '-123' t = s . replace ( '-' , '' , i ) # t equals '123' t = t . replace ( '-' , '' , 1 ) # t is yet equal to '123' u = '.2.3.4.' v = u . replace ( '.' , '' , 2 ) # 5 equals '23.iv.' due west = u . supercede ( '.' , ' dot ' , 5 ) # w equals 'ii dot iii dot four dot '
3.one.8.1. Commodity Starting time Exercise¶
In library alphabetizing, if the initial discussion is an article ("The", "A", "An"), and so it is ignored when ordering entries. Write a programme completing this function, so testing it:
def startsWithArticle ( title ): '''Return True if the starting time word of title is "The", "A" or "An".'''
Be careful, if the title starts with "There", it does not start with an article. What should you exist testing for?
3.1.8.2. Is Number String Practice¶
** In the later Safe Number Input Exercise, it will be of import to know if a cord can be converted to the desired type of number. Explore that here. Relieve example isNumberStringStub.py
equally isNumberString.py
and complete it. It contains headings and documentation strings for the functions in both parts of this exercise.
A legal whole number string consists entirely of digits. Luckily strings have an isdigit
method, which is true when a nonempty string consists entirely of digits, so '2397'.isdigit()
returns True
, and '23a'.isdigit()
returns False
, exactly corresponding to the situations when the cord represents a whole number!
In both parts exist sure to test carefully. Non only confirm that all appropriate strings render Truthful
. Too be sure to test that y'all return False
for all sorts of bad strings.
-
Recognizing an integer cord is more than involved, since it tin can start with a minus sign (or not). Hence the
isdigit
method is not enough by itself. This part is the most straightforward if you have worked on the sections String Indices and Cord Slices. An alternate approach works if you use the count method from Object Orientation, and some methods from this section.Complete the office
isIntStr
. -
Consummate the function
isDecimalStr
, which introduces the possibility of a decimal point (though a decimal bespeak is non required). The string methods mentioned in the previous part remain useful.
[ane] | This is an improvement that is new in Python 3. |
[2] | "In this case do ___; otherwise", "if ___, then", "when ___ is truthful, and then", "___ depends on whether", |
[three] | If you divide an even number past 2, what is the remainder? Use this idea in your if condition. |
[4] | iv tests to distinguish the v cases, as in the previous version |
[five] | Once again, you are calculating and returning a Boolean event. You lot exercise non demand an if - else statement. |
Source: http://anh.cs.luc.edu/handsonPythonTutorial/ifstatements.html
Post a Comment for "Python if This Condition Is Met Then Try Again"