Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Basic Data Types, Control Structures and Functions - Python

Chapter: Internet & World Wide Web HOW TO PROGRAM - Python

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Basic Data Types, Control Structures and Functions - Python

This section introduces basic data types, control structures and functions, using a simple program. In this program, we define two functions that use control structures to perform the operations of those functions.

Basic Data Types, Control Structures and Functions

 

This section introduces basic data types, control structures and functions, using a simple program (Fig. 28.5). In this program, we define two functions that use control structures to perform the operations of those functions.

 

 

Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information.

   import keyword

   print keyword.kwlist

 

['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is','lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while']

>>> 

 

Fig. 28.4       Printing Python keywords in interactive mode.

 

Line 6 calls Python function min on parameters x and y. This function returns the smaller of the two values. We assign the value returned by min to local variable gcd.

 

Notice that line 6 is indented. Unlike many other languages, Python determines the beginning and end of a statement based on whitespace. Each new line begins a new state-ment. The indentation in line 6 marks the beginning of the code block that belongs to func-tion greatestCommonDivisor. Groups of statements that belong to the same block of code are indented by the same amount. The language does not specify how many spaces to indent, only that the indentation must be consistent.

 

Line 8 describes the beginning of a Python while loop. The code in the while block executes as long as gcd is greater than or equal to 1.

 

    # Fig. 28.5: fig28_05.py

    # Program to illustrate basic data types, control structures and

    # functions.

 

    def greatestCommonDivisor( x, y ):

    gcd = min( x, y )

 

         while gcd >= 1:

 

 

              if ( x % gcd ) == ( y % gcd ) == 0:

return gcd

          else:

          gcd -= 1

 

          def determineColor( color ):

      if color == "green":

      print "You entered green!"

      elif color == "purple":

      print "You entered purple!"

      else:

 

      print "You did not enter green or purple."

      number1 = int( raw_input( "Enter a positive integer: " ) )

      number2 = int( raw_input( "Enter a positive integer: " ) )

 

      print "The greatest common divisor is", \

      greatestCommonDivisor( number1, number2 )

 

      for entry in range( 5 ):

      colorChoice = raw_input( "\nEnter your favorite color: " )

determineColor( colorChoice )

 

 

 

Enter a positive integer: 2

Enter a positive integer: 30

The greatest common divisor is 2

 

Enter your favorite color: yellow

You did not enter green or purple.

 

Enter your favorite color: green

You entered green!

 

Enter your favorite color: black

You did not enter green or purple.

 

Enter your favorite color: purple

You entered purple!

Enter your favorite color: red

You did not enter green or purple.

 

 

Fig. 28.5 Program illustrating data types, control structures and functions

 

Line 10 is a Python if statement. If the specified condition is true (i.e., the condition evaluates to any nonzero value), the code in the if block (i.e., the indented code that fol-lows the if statement) is executed. The statement in line 10 uses the modulo operator (%) to determine if parameters x and y can be divided evenly by variable gcd. The statement illustrates the fact that Python comparison expressions can be “chained.” This code is iden-tical to

 

if ( x % gcd ) == 0 == ( y % gcd ):

 

and to

 

if x % gcd == 0 and y % gcd == 0:

 

Chaining occurs left to right; therefore, the former expression is more efficient than the expression presented in the code, because the former expression may save a division op-eration.

 

If the expression in line 10 is true, we have found the greatest common divisor. The return keyword (line 11) exits the function and returns the specified value.

If the expression in line 10 is false (i.e., the condition evaluates to zero), the code in the else block (lines 12–13) executes. This code decrements variable gcd by 1, using the -= statement and has the same effect as the statement

 

gcd = gcd - 1

 

Python defines several such statements, including +=, -=, *=, /=, %= (modulo division) and **= (exponentiation). [Note: These statements are new in Python 2.0; using these statements in Python 1.5.2 or less causes a syntax error.]

 

Function determineColor (lines 15–22) takes parameter color, which contains a string. Lines 17–22 use the if/elif/else control structure to evaluate expressions based on the value of the parameter. If the value of parameter color is equal to the string "green" (line 17), the function prints "You entered green!" If the value of color is equal to the string "purple" (line 19), the function prints "You entered purple!" If the value of name does not match either of these strings (line 21), the function prints

 

"You did not enter green or purple." Function determineColor illustrates simple Python string comparisons. We discuss string comparison/manipulation in further detail in Section 28.4.

 

Line 24 calls Python function raw_input to get input from the user. This function takes an optional string argument that is displayed as a prompt to the user. The raw_input function returns a string. The Python function int takes as an argument a noninteger type and returns an integer representation of the argument. We store the integer returned from function int in local variable number1. Line 25 retrieves a value for number2 in a similar fashion.

 

Lines 27–28 print the greatest common divisor of the two numbers to the screen. The backslash character (\) at the end of line 27 is a line-continuation character that allows us to continue a statement on the next line. The comma (,) that follows the string informs Python that we want to print additional items after the string. In this case, the additional item is the integer value returned by the call to function greatestCommonDivisor. Notice from the output that Python automatically inserts a space between the last character in the string and the integer value.

Line 30 begins a Python for loop. The call to Python function range with an argu-ment of 5 returns the values 0, 1, 2, 3 and 4. [Note: The function actually returns a list that contains these values. We discuss lists in Section 28.3.] The for loop iterates through these values and, on each iteration, assigns a value to variable entry and then executes the statements in the for block (lines 31–32). Thus, the statements in the for block are executed five times. These statements retrieve a string from the user and pass that string to function determineColor. Notice the “\nescape sequence at the beginning of the string in line 31. This is a special Python character that prints a newline to the screen. A newline causes the cursor (i.e., the current screen position indicator) to move to the begin-ning of the next line on the screen. Figure 28.6 lists some common Python escape sequences. After the program calls function determineColor on five user-defined strings, the program exits.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.