#I want to understand this expression, what is it saying? what does "if x:" means? usualy there is always a condition after the if statement, but this one doesn have one. how do I make sense of this? and what is it doing in this fuction? Show
asked Mar 28, 2017 at 7:32
2 It is to check whether x is true or false(binary).
returns true when the x value is not equal to 0(when x is a number) and it returns true if it has at least a character(when x is a string). It returns false if x is equal to '0' or '' or 'None' For Eg:
This prints '10'
This prints 'DaiMaria'
Prints 0.1
Prints nothing as it returned False.
Prints nothing as it returns False.
Prints nothing as it returns False. answered Mar 28, 2017 at 8:01
NMNNMN 3523 silver badges16 bronze badges The condition is whether or not x is a truthy value answered Mar 28, 2017 at 7:33
Your Some examples:
answered Mar 28, 2017 at 7:49
timgebtimgeb 74.5k20 gold badges114 silver badges139 bronze badges 3.1.1. Simple Conditions¶The statements introduced in this chapter will involve tests or conditions. More syntax for conditions will be introduced later, but for now consider simple arithmetic comparisons that directly translate from math into Python. Try each line separately in the Shell 2 < 5 3 > 7 x = 11 x > 10 2 * x < x type(True) You see that conditions are either Note The Boolean values 3.1.2. Simple if Statements¶Run this example program, suitcase.py. Try it at least twice, with inputs: 30 and then 55. As you an see, you get an extra result, depending on the input. The main code is: weight = float(input("How many pounds does your suitcase weigh? ")) if weight > 50: print("There is a $25 charge for luggage that heavy.") print("Thank you for your business.") The middle two
line are an The general Python syntax for a simple If the condition is true, then do the indented statements. If the condition is not true, then skip the indented statements. Another fragment as an example: if balance < 0: transfer = -balance # transfer enough from the backup account: backupAccount = backupAccount - transfer balance = balance + transfer As with other kinds of statements with a heading and an indented block, the block can have more than one statement. The assumption in the example above is that if an account goes negative, it is brought back to 0 by transferring money from a backup account in several steps. In the examples above the choice is between doing something (if the condition is 3.1.3. if-else Statements¶Run the example program, temperature = float(input('What is the temperature? ')) if temperature > 70: print('Wear shorts.') else: print('Wear long pants.') print('Get some exercise outside.') The middle four lines are an if-else statement. Again it is close to English, though you might say “otherwise” instead of
“else” (but else is shorter!). There are two indented blocks: One, like in the simple A line is also
shown dedented next, removing indentation, about getting exercise. Since it is dedented, it is not a part of the if-else statement: Since its amount of indentation matches the The general Python
These statement blocks can have any number of statements, and can include about any kind of statement. See Graduate Exercise 3.1.4. More Conditional Expressions¶All the usual arithmetic comparisons may be made, but many do not use standard mathematical symbolism, mostly for lack of proper keys on a standard keyboard.
There should not be space between the two-symbol Python substitutes. Notice that the obvious choice for equals, a single equal sign, is not used to check for equality. An annoying second equal sign is required. This is because the single equal sign is already used for assignment in Python, so it is not available for tests. Warning It is a common error to use only one equal sign when you mean to test for equality, and not make an assignment! Tests for equality do not make an assignment, and they do not require a variable on the left. Any expressions can be tested for equality or inequality ( x = 5 x x == 5 x == 6 x x != 6 x = 6 6 == x 6 != x 'hi' == 'h' + 'i' 'HI' != 'hi' [1, 2] != [2, 1] An equality check does not make an assignment. Strings are case sensitive. Order matters in a list. Try in the Shell: When the comparison does not make sense, an Exception is caused. [1] Following up on the discussion of the inexactness of float arithmetic in String Formats for Float Precision, confirm that Python does not consider .1 + .2 to be equal to .3: Write a simple condition into the Shell to test. Here is another example: Pay with Overtime. Given a person’s work hours for the week and regular hourly wage, calculate the total pay for the week, taking into account overtime. Hours worked over 40 are overtime, paid at 1.5 times the normal rate. This is a natural place for a function enclosing the calculation. Read the setup for the function: 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. ''' The problem clearly indicates two cases: when no more than 40 hours are worked or when more than 40 hours are worked. In case more than 40 hours are worked, it is convenient to introduce a variable overtimeHours. You are encouraged to think about a solution before going on and examining mine. You can try running my complete example program, wages.py, also shown below. The format operation at the end of the main function uses the floating point format (String Formats for Float Precision) to show two decimal places for the cents in the answer: 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 <= 40: totalWages = hourlyWage*totalHours else: overtime = totalHours - 40 totalWages = hourlyWage*40 + (1.5*hourlyWage)*overtime return totalWages def main(): hours = float(input('Enter hours worked: ')) wage = float(input('Enter dollars paid per hour: ')) total = calcWeeklyWages(hours, wage) print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.' .format(**locals())) main() Here the input was intended to be numeric, but it could be decimal so the conversion from string was via Below is an equivalent alternative version of the body of if totalHours <= 40: regularHours = totalHours overtime = 0 else: overtime = totalHours - 40 regularHours = 40 return hourlyWage*regularHours + (1.5*hourlyWage)*overtimeThe in boolean operator:There are also Boolean operators that are applied to types others than numbers. A useful Boolean operator is >>> vals = ['this', 'is', 'it] >>> 'is' in vals True >>> 'was' in vals False It can also be used with >>> vals = ['this', 'is', 'it] >>> 'is' not in vals False >>> 'was' not in vals True In general the two versions are:
Detecting the need for 3.1.4.1. Graduate Exercise¶Write a program, 3.1.4.2. Head or Tails Exercise¶Write a program In your main program have a simple repeat loop that calls 3.1.4.3. Strange Function Exercise¶Save the example program The 3.1.5. Multiple Tests and if-elif Statements¶Often you want to distinguish between more than two distinct cases, but conditions only have two possible results, def letterGrade(score): if score >= 90: letter = 'A' else: # grade must be B, C, D or F if score >= 80: letter = 'B' else: # grade must be C, D or F if score >= 70: letter = 'C' else: # grade must D or F if score >= 60: letter = 'D' else: letter = 'F' return letter This repeatedly increasing indentation with an def letterGrade(score): if score >= 90: letter = 'A' elif score >= 80: letter = 'B' elif score >= 70: letter = 'C' elif score >= 60: letter = 'D' else: letter = 'F' return letter The most elaborate syntax for an
The Be careful of the strange Python contraction. It is See Grade Exercise. A final alternative for With an if weight > 120: print('Sorry, we can not take a suitcase that heavy.') elif weight > 50: print('There is a $25 charge for luggage that heavy.') This 3.1.5.1. Sign Exercise¶Write a program 3.1.5.2. Grade Exercise¶In Idle, load Be sure to run your new version and test with different inputs that test all the different paths through the program. Be careful to test around cut-off points. What does a grade of 79.6 imply? What about exactly 80? 3.1.5.3. Wages Exercise¶* Modify the
You may find Be sure to test all paths through the program! Your program is likely to be a modification of a program where some choices worked before, but once you change things, retest for all the cases! Changes can mess up things that worked before. 3.1.6. Nesting Control-Flow Statements¶The power of a language like Python comes largely from the variety of ways basic statements can be combined. In particular, numbers from an arbitrary list of numbers in a function with the following heading. Read the pieces for now. def printAllPositive(numberList): '''Print only the positive numbers in numberList.''' For example, suppose but a for some of them. That seems like a major obstacle, but think closer at what needs to happen concretely. As a human, who has eyes of amazing capacity, you are drawn immediately to the actual correct numbers, 3, 2, and 7, but clearly a computer doing this systematically will have to check every number. In fact, there is a consistent action required: Every number must be tested to see if it should be printed. This suggests an def printAllPositive(numberList): '''Print only the positive numbers in numberList.''' for num in numberList: if num > 0: print(num) printAllPositive([3, -5, 2, -1, 0, 7]) This idea of nesting The rest of this section deals with graphical examples. Run example program The parameters give the amount the shape moves in each animation step. You can try 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 case the direction of motion changes with every bounce. The program has a graphic object but in this case, dx and dy have to change when the ball gets to a boundary. For instance, imagine the ball getting to the left side as it is moving to the left and up. The bounce obviously alters the horizontal part of the motion, in fact reversing it, but the ball would still continue up. The reversal of the horizontal part of the motion means that the horizontal shift changes direction and therefore its sign: but The edge of the window is at coordinate 0, but Animation goes quickly in small steps, so I cheat. I allow the ball to take one (small, quick) step past where it really should go ( There are similar bounding variables if x < xLow: dx = -dx if x > xHigh: dx = -dx if y < yLow: dy = -dy if y > yHigh: dy = -dy This approach would cause there to be some extra testing: If it is true that if x < xLow: dx = -dx elif x > xHigh: dx = -dx if y < yLow: dy = -dy elif y > yHigh: dy = -dy Note that the middle The program also uses several methods to read part of the state of graphics objects that we have not used in examples yet. Various graphics objects,
like the circle we are using as the shape, know their center point, and it can be accessed with the This explains the new features in the central function defined for bouncing around in a box, def bounceInBox(shape, dx, dy, xLow, xHigh, yLow, yHigh): ''' Animate a shape moving in jumps (dx, dy), bouncing when its center reaches the low and high x and y coordinates. ''' delay = .005 for i in range(600): shape.move(dx, dy) center = shape.getCenter() x = center.getX() y = center.getY() if x < xLow: dx = -dx elif x > xHigh: dx = -dx if y < yLow: dy = -dy elif y > yHigh: dy = -dy time.sleep(delay) The program starts the ball from an arbitrary point inside the allowable rectangular bounds. This is encapsulated in a utility function included in the program, def getRandomPoint(xLow, xHigh, yLow, yHigh): '''Return a random Point with coordinates in the range specified.''' x = random.randrange(xLow, xHigh+1) y = random.randrange(yLow, yHigh+1) return Point(x, y) The full program is listed below, repeating ''' 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 low and high x and y coordinates. ''' delay = .005 for i in range(600): shape.move(dx, dy) center = shape.getCenter() x = center.getX() y = center.getY() if x < xLow: dx = -dx elif x > 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 Point with coordinates in the range specified.''' x = random.randrange(xLow, xHigh+1) y = random.randrange(yLow, yHigh+1) return Point(x, y) def makeDisk(center, radius, win): '''return a red disk that is drawn in win with given center and radius.''' disk = Circle(center, radius) disk.setOutline("red") disk.setFill("red") disk.draw(win) return disk def bounceBall(dx, dy): '''Make a ball bounce around the screen, initially moving by (dx, dy) at each jump.''' win = GraphWin('Ball Bounce', 290, 290) win.yUp() radius = 10 xLow = radius # center is separated from the wall by the radius at a bounce xHigh = win.getWidth() - radius yLow = radius yHigh = win.getHeight() - radius center = getRandomPoint(xLow, xHigh, yLow, yHigh) ball = makeDisk(center, radius, win) bounceInBox(ball, dx, dy, xLow, xHigh, yLow, yHigh) win.close() bounceBall(3, 5) 3.1.6.1. Short String Exercise¶Write a program def printShort(strings): '''Given a list of strings, print the ones with at most three characters. >>> printShort(['a', 'long', one']) a one ''' In your main program, test the function, calling it several times with different lists of strings. Hint: Find the length of each string with the The function documentation here models a common approach: illustrating the behavior of the function with a Python Shell interaction. This part begins with a line starting with
3.1.6.2. Even Print Exercise¶Write a program def printEven(nums): '''Given a list of integers nums, print the even ones. >>> printEven([4, 1, 3, 2, 7]) 4 2 ''' In your main program, test the function, calling it several times with different lists of integers. Hint: A number is even if its remainder, when dividing by 2, is 0. 3.1.6.3. Even List Exercise¶Write a program def chooseEven(nums): '''Given a list of integers, nums, return a list containing only the even ones. >>> chooseEven([4, 1, 3, 2, 7]) [4, 2] ''' In your main program, test the function, calling it several times with different lists of integers and printing the results in the main program. (The documentation string illustrates the function 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 function, create a new list, and append the appropriate numbers to it, before returning the result. 3.1.6.4. Unique List Exercise¶* The Copy def uniqueList(aList): ''' Return a new list that includes the first 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 order. >>> vals = ['cat', 'dog', 'cat', 'bug', 'dog', 'ant', 'dog', 'bug'] >>> uniqueList(vals) ['cat', 'dog', 'bug', 'ant'] ''' Hint: Process After perfecting the Check that your 3.1.7. Compound Boolean Expressions¶To be eligible to graduate from Loyola University Chicago, you must have 120 credits and a GPA of at least 2.0. This translates directly into Python as a compound condition: credits >= 120 and GPA >=2.0 This
is true if both credits = float(input('How many units of credit do you have? ')) GPA = float(input('What is your GPA? ')) if credits >= 120 and GPA >=2.0: print('You are eligible to graduate!') else: print('You are not eligible to graduate.') The new Python syntax is for the operator
The compound condition is true if both of the component conditions are true. It is false if at least one of the conditions is false. See Congress Exercise. In the last example in the previous section, there was an if x < xLow: dx = -dx elif x > xHigh: dx = -dx There is a simpler way to state 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
is true if at least one of the conditions is true. It is false if both conditions are false. This corresponds to one way the word “or” is used in English. Other times in English “or” is used to mean exactly one alternative is true. Warning When translating a problem stated in English using “or”, be careful
to determine whether the meaning matches Python’s It is often convenient to encapsulate complicated tests inside a function. Think how to complete the function starting: def isInside(rect, point): '''Return True if the point is inside the Rectangle rect.''' pt1 = rect.getP1() pt2 = rect.getP2() Recall that a Suppose that I introduce variables for the x coordinates of Unfortunately, this is not enough: The
only requirement for the two corner points is that they be diagonally opposite, not that the coordinates of the second point are higher than the corresponding coordinates of the first point. It could be that is False. The 100 and 200 need to be reversed in this case. This makes a complicated situation. Also this is an
issue which must be revisited for both the x and y coordinates. I introduce an auxiliary function def isBetween(val, end1, end2): '''Return True if val is between the ends. The ends do not need to be in increasing order.''' Clearly this is true if the original expression, A correct but redundant function body would be: if end1 <= val <= end2 or end2 <= val <= end1: return True else: return False Check the meaning: if the compound expression is return end1 <= val <= end2 or end2 <= val <= end1 Note In general you should not
need an A side comment on expressions like Other than the two-character operators, this is like standard math syntax, chaining comparisons. In Python any number of comparisons can be chained in this way, closely approximating mathematical notation. Though this is good Python, be aware that if you try other high-level languages like Java and C++, such an expression is gibberish. Another way the expression can be expressed (and which translates directly to other languages) is: end1 <= val and val <= end2 So much for the auxiliary function 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 case we need the point to be both between the sides and between the top and bottom, so the proper connector is and. Think how to finish the Sometimes you want to test the opposite of a condition. As in English you can use the word not isInside(rect, point) In general,
is The example program The
program includes the functions The present main 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 '''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 True if x is between the ends or equal to either. The ends do not need to be in increasing order.''' return end1 <= x <= end2 or end2 <= x <= end1 def isInside(point, rect): '''Return True if the point 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 color specified.''' corner2 = corner.clone() corner2.move(width, -height) rect = Rectangle(corner, corner2) rect.setFill(color) rect.draw(win) return rect def main(): win = GraphWin('pick Colors', 400, 400) win.yUp() # right side up coordinates redButton = makeColoredRect(Point(310, 350), 80, 30, 'red', win) yellowButton = makeColoredRect(Point(310, 310), 80, 30, 'yellow', win) blueButton = makeColoredRect(Point(310, 270), 80, 30, 'blue', win) house = makeColoredRect(Point(60, 200), 180, 150, 'gray', win) door = makeColoredRect(Point(90, 150), 40, 100, 'white', win) roof = Polygon(Point(50, 200), Point(250, 200), Point(150, 300)) roof.setFill('black') roof.draw(win) msg = Text(Point(win.getWidth()/2, 375),'Click to choose a house color.') msg.draw(win) pt = win.getMouse() if isInside(pt, redButton): color = 'red' elif isInside(pt, yellowButton): color = 'yellow' elif isInside(pt, blueButton): color = 'blue' else : color = 'white' house.setFill(color) msg.setText('Click to choose a door color.') pt = win.getMouse() if isInside(pt, redButton): color = 'red' elif isInside(pt, yellowButton): color = 'yellow' elif isInside(pt, blueButton): color = 'blue' else : color = 'white' door.setFill(color) win.promptClose(msg) main() The only further new feature used is in the long return statement in return isBetween(point.getX(), pt1.getX(), pt2.getX()) and \ isBetween(point.getY(), pt1.getY(), pt2.getY()) Recall that Python is smart enough to realize that a statement continues to the next line if there
is an unmatched pair of parentheses or brackets. Above is another situation with a long statement, but there are no unmatched parentheses on a line. For readability it is best not to make an enormous long line that would run off your screen or paper. Continuing to the next line is recommended. You can make the final character on a line be a backslash ( return (isBetween(point.getX(), pt1.getX(), pt2.getX()) and isBetween(point.getY(), pt1.getY(), pt2.getY()) ) The chooseButton1.py program is long partly because of repeated code. The next section gives another version involving lists. 3.1.7.1. Congress Exercise¶A person is eligible to be a US Senator who is at least 30 years old and has been a US citizen for at least 9 years. Write an initial version of a program A
person is eligible to be a US Representative who is at least 25 years old and has been a US citizen for at least 7 years. Elaborate your program
3.1.8. More String Methods¶Here are a few more string methods useful in the next exercises, assuming the methods are applied to a string
3.1.8.1. Article Start Exercise¶In library alphabetizing, if the initial word is an article (“The”, “A”, “An”), then it is ignored when ordering entries. Write a program completing this function, and then testing it: def startsWithArticle(title): '''Return True if the first 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 be testing for? 3.1.8.2. Is Number String Exercise¶** In the later
Safe Number Input Exercise, it will be important to know if a string can be converted to the desired type of number. Explore that here. Save example A legal whole number string consists entirely of digits. Luckily strings have an
In both parts be sure to test carefully. Not only confirm that all appropriate strings return
What if there is no condition in if statement?C - General Programming - Return value of a if statement without any condition. To test a condition in a if statement without any condition, the result has to be other than 0 to test a true condition. Result: $ True - Value was -1.
Can we write if statement without condition?An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.
How do you do if not condition in Python?Using the 'if not' Python statement to check if it negates the output of an 'if' statement. As you can see, the code under the 'if' block was returned although the condition returned false. This is because the 'not' operator negated its value.
Can I use an IF statement without else in Python?You can write Python one line if without else statement by just avoiding an else. For it just writes the if statement in a single line! No needed tricks (like using the semicolon) that help you create one-liner statements.
|