Skip to content Skip to sidebar Skip to footer

That Is Not an Integer X Such That 0 X 100 Try Again Enter Score 2

4. Conditionals¶

4.1. The modulus operator¶

The modulus operator works on integers (and integer expressions) and yields the residue when the first operand is divided by the 2d. In Python, the modulus operator is a percent sign ( % ). The syntax is the aforementioned equally for other operators:

              >>>                            caliber              =              7              /              3              >>>                            print              quotient              2              >>>                            remainder              =              7              %              three              >>>                            print              remainder              1            

And so seven divided by three is 2 with ane left over.

The modulus operator turns out to be surprisingly useful. For case, yous can check whether one number is divisible by another—if x % y is zero, then x is divisible by y .

Also, you can extract the right-almost digit or digits from a number. For example, x % 10 yields the right-most digit of 10 (in base x). Similarly x % 100 yields the last 2 digits.

four.two. Boolean values and expressions¶

The Python type for storing true and faux values is called bool , named after the British mathematician, George Boole. George Boole created Boolean algebra, which is the basis of all modern reckoner arithmetic.

There are only two boolean values: True and False . Capitalization is of import, since true and false are non boolean values.

              >>>                            type              (              True              )              <blazon 'bool'>              >>>                            blazon              (              true              )              Traceback (most recent call concluding):              File              "<stdin>", line              1, in              <module>              NameError:              name 'true' is not defined            

A boolean expression is an expression that evaluates to a boolean value. The operator == compares 2 values and produces a boolean value:

              >>>                            5              ==              v              True              >>>                            5              ==              6              False            

In the first statement, the two operands are equal, and so the expression evaluates to True ; in the 2d argument, v is not equal to 6, so we get Faux .

The == operator is one of the comparison operators; the others are:

              x              !=              y              # x is not equal to y              x              >              y              # x is greater than y              x              <              y              # x is less than y              x              >=              y              # x is greater than or equal to y              10              <=              y              # 10 is less than or equal to y            

Although these operations are probably familiar to you lot, the Python symbols are different from the mathematical symbols. A common error is to use a single equal sign ( = ) instead of a double equal sign ( == ). Call up that = is an assignment operator and == is a comparing operator. Also, there is no such matter every bit =< or => .

iv.3. Logical operators¶

At that place are 3 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 merely if x is greater than 0 and less than 10.

due north % ii == 0 or n % 3 == 0 is true if either of the conditions is true, that is, if the number is divisible by two or three.

Finally, the non operator negates a boolean expression, and so non(10 > y) is true if (x > y) is imitation, that is, if x is less than or equal to y .

four.4. Conditional execution¶

In social club to write useful programs, we almost always need the ability to check weather and change the behavior of the programme accordingly. Conditional statements give us this power. The simplest grade is the ** if argument**:

              if              ten              >              0              :              print              "x is positive"            

The boolean expression after the if statement is called the condition. If it is true, so the indented statement gets executed. If not, cipher happens.

The syntax for an if statement looks like this:

              if              BOOLEAN              EXPRESSION              :              STATEMENTS            

As with the function definition from last chapter and other compound statements, the if argument consists of a header and a body. The header begins with the keyword if followed by a boolean expression and ends with a colon (:).

The indented statements that follow are called a block. The commencement unindented statement marks the end of the block. A statement block inside a compound statement is called the body of the statement.

Each of the statements inside the trunk are executed in order if the boolean expression evaluates to Truthful . The entire block is skipped if the boolean expression evaluates to False .

There is no limit on the number of statements that tin announced in the body of an if statement, but there has to exist at least ane. Occasionally, it is useful to have a body with no statements (unremarkably as a identify keeper for code you oasis't written yet). In that case, yous can use the laissez passer statement, which does nix.

              if              Truthful              :              # This is always true              pass              # so this is ever executed, but it does nothing            

4.5. Alternative execution¶

A second grade of the if statement is alternative execution, in which there are 2 possibilities and the condition determines which one gets executed. The syntax looks similar this:

              if              x              %              two              ==              0              :              print              10              ,              "is even"              else              :              impress              x              ,              "is odd"            

If the residual when ten is divided by 2 is 0, then we know that ten is even, and the program displays a bulletin to that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or false, exactly one of the alternatives will exist executed. The alternatives are chosen branches, because they are branches in the catamenia of execution.

As an aside, if you lot need to check the parity (evenness or oddness) of numbers often, you might wrap this code in a office:

              def              print_parity              (              x              ):              if              10              %              ii              ==              0              :              impress              x              ,              "is even"              else              :              print              x              ,              "is odd"            

For any value of x , print_parity displays an appropriate message. When you call it, y'all can provide whatsoever integer expression as an argument.

              >>>                            print_parity              (              17              )              17 is odd.              >>>                            y              =              41              >>>                            print_parity              (              y              +              i              )              42 is even.            

4.vi. Chained conditionals¶

Sometimes there are more than 2 possibilities and nosotros need more than two branches. One way to express a computation like that is a chained conditional:

              if              x              <              y              :              impress              x              ,              "is less than"              ,              y              elif              10              >              y              :              print              x              ,              "is greater than"              ,              y              else              :              print              x              ,              "and"              ,              y              ,              "are equal"            

elif is an abridgement of else if . Again, exactly one branch will be executed. There is no limit of the number of elif statements but but a single (and optional) else statement is immune and it must exist the terminal co-operative in the statement:

              if              selection              ==              'a'              :              function_a              ()              elif              option              ==              'b'              :              function_b              ()              elif              choice              ==              'c'              :              function_c              ()              else              :              print              "Invalid choice."            

Each condition is checked in order. If the offset is false, the side by side is checked, and and so on. If one of them is truthful, the corresponding branch executes, and the statement ends. Even if more than than 1 condition is true, only the first true branch executes.

4.7. Nested conditionals¶

One conditional can also be nested within another. We could have written the trichotomy example equally follows:

              if              ten              ==              y              :              print              x              ,              "and"              ,              y              ,              "are equal"              else              :              if              x              <              y              :              print              10              ,              "is less than"              ,              y              else              :              print              x              ,              "is greater than"              ,              y            

The outer provisional contains 2 branches. The start branch contains a simple output statement. The second branch contains another if argument, which has two branches of its own. Those two branches are both output statements, although they could have been conditional statements also.

Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. In general, it is a good idea to avert them when you can.

Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the post-obit code using a single conditional:

              if              0              <              x              :              if              x              <              10              :              impress              "x is a positive single digit."            

The print statement is executed merely if we make it past both the conditionals, so we can use the and operator:

              if              0              <              x              and              x              <              10              :              impress              "10 is a positive single digit."            

These kinds of conditions are mutual, so Python provides an culling syntax that is similar to mathematical notation:

              if              0              <              10              <              10              :              print              "x is a positive single digit."            

This condition is semantically the same as the compound boolean expression and the nested conditional.

four.viii. The return statement¶

The return statement allows you to finish the execution of a office before y'all reach the end. 1 reason to utilise it is if yous detect an fault status:

              def              print_square_root              (              10              ):              if              x              <=              0              :              print              "Positive numbers only, please."              render              result              =              x              **              0.5              print              "The foursquare root of"              ,              x              ,              "is"              ,              result            

The function print_square_root has a parameter named x . The starting time matter it does is cheque whether x is less than or equal to 0, in which instance it displays an error message and so uses render to leave the office. The flow of execution immediately returns to the caller, and the remaining lines of the office are not executed.

iv.nine. Keyboard input¶

In Input we were introduced to Python'southward congenital-in functions that get input from the keyboard: raw_input and input . Now permit's await at these again in greater depth.

When either of these functions are called, the program stops and waits for the user to blazon something. When the user presses Return or the Enter key, the program resumes and raw_input returns what the user typed as a string :

              >>>                            my_input              =              raw_input              ()              What are you waiting for?              >>>                            print              my_input              What are you lot waiting for?            

Before calling raw_input , it is a skillful idea to impress a bulletin telling the user what to input. This message is called a prompt. We can supply a prompt as an argument to raw_input :

              >>>                            name              =              raw_input              (              "What...is your name? "              )              What...is your proper name? Arthur, King of the Britons!              >>>                            print              name              Arthur, Male monarch of the Britons!            

Observe that the prompt is a string, and then it must be enclosed in quotation marks.

If we await the response to be an integer, we tin can employ the input function which evaluates the response as a Python expression:

              prompt              =              "What...is the airspeed velocity of an unladen swallow?              \n              "              speed              =              input              (              prompt              )            

If the user types a cord of digits, it is converted to an integer and assigned to speed . Unfortunately, if the user types characters that practise not make upwards a valid Python expression, the program crashes:

              >>>                            speed              =              input              (              prompt              )              What...is the airspeed velocity of an unladen swallow?              What practise you mean, an African or a European consume?              ...              SyntaxError: invalid syntax            

In the last example, if the user had made the response a valid Python expression by putting quotes around information technology, it would not have given an fault:

              >>>                            speed              =              input              (              prompt              )              What...is the airspeed velocity of an unladen swallow?              "What practice you mean, an African or a European swallow?"              >>>                            speed              'What practice you mean, an African or a European swallow?'              >>>            

To avert this kind of error, it is a good idea to use raw_input to go a string and then use conversion commands to convert it to other types.

4.10. Blazon conversion¶

Each Python type comes with a built-in command that attempts to convert values of another type into that blazon. The int(Argument) command, for example, takes any value and converts information technology to an integer, if possible, or complains otherwise:

              >>>                            int              (              "32"              )              32              >>>                            int              (              "Hi"              )              ValueError: invalid literal for int() with base x: 'Howdy'            

int tin also convert floating-point values to integers, but remember that it truncates the fractional part:

              >>>                            int              (              -              2.3              )              -2              >>>                            int              (              3.99999              )              3              >>>                            int              (              "42"              )              42              >>>                            int              (              one.0              )              1            

The float(ARGUMENT) command converts integers and strings to floating-point numbers:

              >>>                            float              (              32              )              32.0              >>>                            float              (              "3.14159"              )              3.14159              >>>                            float              (              ane              )              1.0            

It may seem odd that Python distinguishes the integer value 1 from the floating-point value 1.0 . They may represent the same number, but they vest to different types. The reason is that they are represented differently inside the computer.

The str(ARGUMENT) command converts any statement given to it to blazon cord :

              >>>                            str              (              32              )              '32'              >>>                            str              (              iii.14149              )              '3.14149'              >>>                            str              (              True              )              'True'              >>>                            str              (              truthful              )              Traceback (most recent call last):              File              "<stdin>", line              1, in              <module>              NameError:              name 'true' is not defined            

str(ARGUMENT) will work with any value and convert it into a string. As mentioned earlier, Truthful is boolean value; true is not.

For boolean values, the situation is especially interesting:

              >>>                            bool              (              i              )              True              >>>                            bool              (              0              )              Simulated              >>>                            bool              (              "Ni!"              )              True              >>>                            bool              (              ""              )              False              >>>                            bool              (              three.14159              )              True              >>>                            bool              (              0.0              )              Simulated            

Python assigns boolean values to values of other types. For numerical types like integers and floating-points, nothing values are false and non-zip values are truthful. For strings, empty strings are faux and not-empty strings are true.

4.11. GASP¶

GASP (Grandraphics API for Students of Python) will enable us to write programs involving graphics. Before you lot can apply GASP, it needs to exist installed on your automobile. If you are running Ubuntu GNU/Linux, see GASP in Appendix A. Current instructions for installing GASP on other platforms can be found at http://dev.laptop.org/pub/gasp/downloads.

Later on installing gasp, attempt the following python script:

              from              gasp              import              *              begin_graphics              ()              Circle              ((              200              ,              200              ),              60              )              Line              ((              100              ,              400              ),              (              580              ,              200              ))              Box              ((              400              ,              350              ),              120              ,              100              )              update_when              (              'key_pressed'              )              end_graphics              ()            

The second to the concluding control pauses and waits until a primal is pressed. Without it, the screen would flash by so rapidly you wouldn't see it.

Running this script, you should see a graphics window that looks like this:

GASP illustration 1

Nosotros will be using gasp from here on to illustrate (pun intended) computer programming concepts and to add together to our fun while learning. Y'all can find out more than well-nigh the GASP module past reading Appendix B.

iv.12. Glossary¶

block
A grouping of consecutive statements with the same indentation.
trunk
The cake of statements in a compound statement that follows the header.
boolean expression
An expression that is either true or false.
boolean value
There are exactly two boolean values: Truthful and False . Boolean values result when a boolean expression is evaluated by the Python interepreter. They have type bool .
branch
One of the possible paths of the flow of execution determined by conditional execution.
chained conditional
A conditional co-operative with more than than two possible flows of execution. In Python chained conditionals are written with if ... elif ... else statements.
comparison operator
Ane of the operators that compares 2 values: == , != , > , < , >= , and <= .
condition
The boolean expression in a conditional statement that determines which branch is executed.
provisional argument
A statement that controls the flow of execution depending on some condition. In Python the keywords if , elif , and else are used for conditional statements.
logical operator
One of the operators that combines boolean expressions: and , or , and not .
modulus operator
An operator, denoted with a percent sign ( % ), that works on integers and yields the residual when one number is divided past some other.
nesting
One program structure within some other, such as a conditional statement inside a branch of another provisional statement.
prompt
A visual cue that tells the user to input data.
blazon conversion
An explicit statement that takes a value of one type and computes a corresponding value of some other blazon.
wrapping code in a role
The process of adding a function header and parameters to a sequence of program statements is frequently refered to equally "wrapping the code in a function". This process is very useful whenever the program statements in question are going to be used multiple times.

4.13. Exercises¶

  1. Try to evaluate the following numerical expressions in your head, and then utilise the Python interpreter to check your results:

    1. >>> five % 2
    2. >>> 9 % 5
    3. >>> 15 % 12
    4. >>> 12 % xv
    5. >>> 6 % 6
    6. >>> 0 % 7
    7. >>> 7 % 0

    What happened with the last case? Why? If you were able to correctly conceptualize the computer's response in all but the last i, information technology is time to move on. If not, take time now to brand upward examples of your ain. Explore the modulus operator until you lot are confident you understand how information technology works.

  2.                   if                  x                  <                  y                  :                  impress                  x                  ,                  "is less than"                  ,                  y                  elif                  ten                  >                  y                  :                  impress                  x                  ,                  "is greater than"                  ,                  y                  else                  :                  print                  x                  ,                  "and"                  ,                  y                  ,                  "are equal"                

    Wrap this code in a function called compare(x, y) . Telephone call compare three times: one each where the beginning argument is less than, greater than, and equal to the 2d argument.

  3. To better understand boolean expressions, information technology is helpful to construct truth tables. Two boolean expressions are logically equivalent if and only if they have the same truth tabular array.

    The following Python script prints out the truth tabular array for any boolean expression in two variables: p and q:

                      expression                  =                  raw_input                  (                  "Enter a boolean expression in two variables, p and q: "                  )                  print                  " p      q                                    %s                  "                  %                  expression                  length                  =                  len                  (                  " p      q                                    %s                  "                  %                  expression                  )                  print                  length                  *                  "="                  for                  p                  in                  True                  ,                  Simulated                  :                  for                  q                  in                  Truthful                  ,                  False                  :                  impress                  "                  %-7s                                                      %-7s                                                      %-7s                  "                  %                  (                  p                  ,                  q                  ,                  eval                  (                  expression                  ))                

    You lot will learn how this script works in later capacity. For at present, you lot will use information technology to learn well-nigh boolean expressions. Copy this plan to a file named p_and_q.py , then run information technology from the command line and give it: p or q , when prompted for a boolean expression. You should become the following output:

                      p      q      p or q ===================== True    True    True Truthful    False   True Faux   True    True False   Simulated   False                

    At present that nosotros see how it works, allow's wrap it in a office to make it easier to use:

                      def                  truth_table                  (                  expression                  ):                  impress                  " p      q                                    %s                  "                  %                  expression                  length                  =                  len                  (                  " p      q                                    %s                  "                  %                  expression                  )                  impress                  length                  *                  "="                  for                  p                  in                  Truthful                  ,                  False                  :                  for                  q                  in                  True                  ,                  Faux                  :                  impress                  "                  %-7s                                                      %-7s                                                      %-7s                  "                  %                  (                  p                  ,                  q                  ,                  eval                  (                  expression                  ))                

    We tin import it into a Python shell and phone call truth_table with a cord containing our boolean expression in p and q every bit an argument:

                      >>>                                    from                  p_and_q                  import                  *                  >>>                                    truth_table                  (                  "p or q"                  )                  p      q      p or q                  =====================                  True    True    True                  True    Imitation   True                  False   Truthful    Truthful                  False   False   False                  >>>                

    Employ the truth_table functions with the following boolean expressions, recording the truth table produced each time:

    1. not(p or q)
    2. p and q
    3. not(p and q)
    4. not(p) or not(q)
    5. non(p) and not(q)

    Which of these are logically equivalent?

  4. Enter the following expressions into the Python shell:

                      True                  or                  Fake                  True                  and                  False                  not                  (                  False                  )                  and                  Truthful                  True                  or                  7                  False                  or                  7                  True                  and                  0                  False                  or                  8                  "happy"                  and                  "sad"                  "happy"                  or                  "sad"                  ""                  and                  "sad"                  "happy"                  and                  ""                

    Analyze these results. What observations can you make about values of unlike types and logical operators? Tin you write these observations in the form of simple rules well-nigh and and or expressions?

  5.                   if                  choice                  ==                  'a'                  :                  function_a                  ()                  elif                  selection                  ==                  'b'                  :                  function_b                  ()                  elif                  pick                  ==                  'c'                  :                  function_c                  ()                  else                  :                  print                  "Invalid choice."                

    Wrap this lawmaking in a function called acceleration(choice) . Then ascertain function_a , function_b , and function_c and then that they impress out a bulletin proverb they were chosen. For example:

                      def                  function_a                  ():                  print                  "function_a was called..."                

    Put the four functions ( dispatch , function_a , function_b , and function_c into a script named ch04e05.py . At the lesser of this script add together a call to dispatch('b') . Your output should be:

    Finally, modify the script so that user can enter 'a', 'b', or 'c'. Examination it past importing your script into the Python shell.

  6. Write a function named is_divisible_by_3 that takes a single integer equally an statement and prints "This number is divisible by 3." if the argument is evenly divisible past three and "This number is non divisible past three." otherwise.

    Now write a similar office named is_divisible_by_5 .

  7. Generalize the functions you wrote in the previous exercise into a function named is_divisible_by_n(x, due north) that takes two integer arguments and prints out whether the offset is divisible by the 2d. Salve this in a file named ch04e07.py . Import it into a beat and try it out. A sample session might look like this:

                      >>>                                    from                  ch04e07                  import                  *                  >>>                                    is_divisible_by_n                  (                  20                  ,                  four                  )                  Yeah, 20 is divisible by 4                  >>>                                    is_divisible_by_n                  (                  21                  ,                  eight                  )                  No, 21 is not divisible past 8                
  8. What will be the output of the post-obit?

                      if                  "Ni!"                  :                  impress                  'Nosotros are the Knights who say, "Ni!"'                  else                  :                  impress                  "Terminate it! No more than of this!"                  if                  0                  :                  impress                  "And now for something completely different..."                  else                  :                  print                  "What's all this, and then?"                

    Explain what happened and why it happened.

  9. The post-obit gasp script, in a file named house.py , draws a unproblematic house on a gasp canvas:

                      from                  gasp                  import                  *                  # import everything from the gasp library                  begin_graphics                  ()                  # open the graphics canvas                  Box                  ((                  xx                  ,                  20                  ),                  100                  ,                  100                  )                  # the house                  Box                  ((                  55                  ,                  20                  ),                  thirty                  ,                  l                  )                  # the door                  Box                  ((                  xl                  ,                  fourscore                  ),                  twenty                  ,                  20                  )                  # the left window                  Box                  ((                  fourscore                  ,                  80                  ),                  xx                  ,                  20                  )                  # the right window                  Line                  ((                  20                  ,                  120                  ),                  (                  70                  ,                  160                  ))                  # the left roof                  Line                  ((                  70                  ,                  160                  ),                  (                  120                  ,                  120                  ))                  # the right roof                  update_when                  (                  'key_pressed'                  )                  # keep the sheet open until a key is pressed                  end_graphics                  ()                  # close the sheet (which would happen                  # anyway, since the script ends here, but it                  # is ameliorate to be explicit).                

    Run this script and ostend that you get a window that looks like this:

    GASP illustration 2
    1. Wrap the firm code in a function named draw_house() .
    2. Run the script now. Do you run into a firm? Why not?
    3. Add a phone call to draw_house() at the botton of the script so that the house returns to the screen.
    4. Parameterize the role with x and y parameters – the header should then become def draw_house(10, y): , then that you lot tin can laissez passer in the location of the house on the canvas.
    5. Utilise draw_house to place v houses on the canvas in different locations.
  10. Exploration: Read over Appendix B and write a script named houses.py that produces the following when run:

    GASP illustration 3

    hint: Y'all will need to utilise a Polygon for the roof instead of ii Line southward to get filled=True to work with it.

doughertygreasse.blogspot.com

Source: https://www.openbookproject.net/thinkcs/python/english2e/ch04.html

Post a Comment for "That Is Not an Integer X Such That 0 X 100 Try Again Enter Score 2"