Fundamentals » Selection Statements »

 

Selection Statements

Strings Table Of Contents Repetition Statements


Selections are made in Python as in Java using the if statement. Python has a boolean class to represent logical values and a complete set of logical operators.

Boolean Class

Python provides a boolean class which defines the two values True and False for use with logical expressions. Python will implicitly convert other types to a boolean when necessary. The basic rules are

  • Non-zero numeric values are converted to True while a value of zero, both integer and floating-point, is False.
  • For all other types, the values are converted to True if the object is nonempty and False when they are empty.

The built-in function bool( x ) can be used to convert value x to a boolean using these standard rules.

NoteNote:

An empty literal string ("") is considered empty and will evaluate to False.

Logical Expressions

Logical expressions are constructed using logical and boolean operators as they are in Java and most other langauges. The result of a logical expression is a boolean value of either True or False.

Relational Operators

The relational operators available in Python include

   <   >   <=   >=   ==   !=   <>

where <> and != are equivalent. As in Java, parentheses can be used to override the order of precedence.

Boolean Operators

The boolean operators in Python are represented as reserved words instead of symbols. They are used to create compound logical operators.

   or  and  not

The logical operators can be used with any of the built-in types. In general, the comparisons are performed as follows

  • Numeric values are compared by relative magnitude.
  • Strings are compared lexicographically, character by character from left to right.
  • Lists and tuples are compared component by component, left to right.
  • Dictionaries are compared by treating all of the items (key/value pairs) as though in a sorted list.

Evaluation and References

Logical operators in Python are applied to objects and not to the values within a variable.

Java Evaluation

In Java, the operators were applied to literal and variable values. This meant that the comparison of two reference variables determined whether they were aliases. For example, consider the following Java code segment

// Java code segment
String name1 = "Smith";
String name2 = "Jones";
if( name1 == name2 )
  System.out.println( "Name1 and Name2 are aliases." );
 

in which the two reference variables are compared for equality. In Java, the == operator compares the values stored in the two variables name1 and name2 and not the strings to which those variables refer.

Python Evaluation

If the == operator is applied to two string variables in Python, the strings themselves are compared and not the variable references. This is the case for all Python variables since all variables are object references.

When applied to a non-primitive object, Python performs the logical operation on each data field of the object. If the result from each of those comparisons is true, the final result is true, otherwise, it is false.

Reference Comparisons

To compare references themselves, that is the addresses stored in the variables, Python provides the is operator. For example, in the code segment

name1 = "Smith"
name2 = "Jones"

result = name1 is name2
 

result is set to False since the two variables point to two different objects. If we modify this segment

name1 = "Smith"
name2 = name1

result = name1 is name2
 

result is now set to True since the two variables refere to the same object and are thus aliases.

Null Reference

A null reference in Python is represented by the special object called None. It can be used in logical expressions to test references or assigned to variables to remove references.

# The is operator along with None can tests for null references.
result = name1 is None
result2 = name1 == None
 

The if Statement

Python provides the if statement as the sole selection statement. While it works the same as in Java, the Python sytnax is somewhat different.

Plain If-Structure

Consider the following example of a simple if statement in Python

if value < 0 :
   print "The value is negative."
 

Note that Python does not use parentheses to enclose the condition. The if statement is a compound statement, however, which means it requires a statement block following the condition even if there is only a single statement to be executed. The format of the simple if statement is shown below

if <condition>:
  <statement-block>  

The following program provides a complete example using a Python if statement

Program: sqroot.py
#sqroot.py
#Compute the square root of a postive value entered by the
#user. The extracted value is examined to make sure it is
#positive. If not, the absolute value is first computed.

import math

# Extract a value from the user.
value = int( raw_input( "Enter a value: " ) )

# Determine if it's negative. If so, make it positive.
if value < 0 :
   print "The value is negative. Converting to positive."
   value = abs( value )

# Compute the square root of the number.
sqroot = math.sqrt( value )

# Print the results.
print "The square root of ", value, " is ", sqroot
 

If-Else Structure

The if statement can contain an else part to be executed when the logical condition is false. It too is a compound statement which is indicated by the required colon following the else statement

if value < 0 :
   print "The value is negative."
   value = abs( value )
else:
   print "The value is positive."
 

The format of the if-else structure is shown below

if <condition> :
  <statement-block-1>
else:
  <statement-block-2>

The following program illustrates the use of nested if statements.

Program: minofthree.py
#minofthree.py
#Extracts three integer values from the user and then
#determines the smallest of the three.

#Extract the three values.
num1 = int( raw_input( "Enter value one: " ))
num2 = int( raw_input( "Enter value two: " ))
num3 = int( raw_input( "Enter value three: " ))

#Determine the smallest of the three with nested ifs.
if num1 < num2 :
   if num1 < num3 :
      smallest = num1
   else:
      smallest = num3
else:
   if num2 < num3 :
      smallest = num2
   else:
      smallest = num3
     
#Print the results.
print "The smallest value of the three is ", smallest
 


Multiway Branching

Python does not provide a switch type statement. Instead, all multiway branchings are encoded using a special if-elif-else structure.

if avgGrade >= 90.0 :
   letterGrade = "A"
elif avgGrade >= 80.0 :
   letterGrade = "B"
elif avgGrade >= 70.0 :
   letterGrade = "C"
elif avgGrade >= 60.0 :
   letterGrade = "D"
else:
   letterGrade = "F"
 

The else part can be omitted if there is no default part to the multiway branch. The if, elif and else words should be aligned to the same indentation level as shown in the format description below

if <condition-1> :
  <statement-block-1>
elif <condition-2> :
  <statement-block-2>
       :
       :
elif <condition-N> :
  <statement-block-N>
else:
  <statement-block-N+1>  

String Evaluations

Evaluating a single string or comparing two strings are common operations in many programs. In Java, these operations were performed using methods of the String class. In Python, they can be performed using ordinary operators.

Comparison

The normal equivalency operator is also used in Python to evaluate strings.

str1 = "Abc Def"
str2 = "Abc def"

if str1 == str2 :
   print "Equal!!"
else :
   print "Not Equal!!"
 

In Java, this was done using either the equal() or compareTo() method of the String class as illustrated below

// Java string comparison
String str1 = "Abc Def";
String str2 = "Abc def";

if( str1.equals( str2 ) )
  System.out.println( "Equal!!" );
else
  System.out.println( "Not Equal!!" );
 

Likewise, the lexicographical order of two strings is determined using the appropriate logical operator instead of the compareTo() operator as is done in Java

name1 = "Smith, John";
name2 = "Smith, Jane";

if name1 < name2 :
   print "Name1 comes first."
elif name1 > name2 :
   print "Name2 comes first."
else :
   print "The names are the same."
 

Contains

To determine if a string contains a substring of characters, Python provides the in operator. In the following example,

if "Smith" in name1 :
   print name1
 

a value of True is returned if the string name1 contains the given substring and False otherwise. In Java, this is done using the contains() method of the String class

if( name1.contains( "Smith" ) )
  System.out.println( name1 );
 

There is also a not version of the in operator that can be used to determine if a string dose not contain a substring

if "Jones" not in name1 :
   print "Name not found"
 



Strings Table Of Contents Repetition Statements

© 2006 - 2008: Rance Necaise - Page last modified on September 13, 2006, at 01:07 PM