(U)Unclassified

Control Flow

Control Flow Overview

  • Operators
    • Membership Operators
    • Identity Operators
    • Boolean Operators
    • Assignment Operators
  • I/O: Print
    • % Formatting
    • format()

Overview (Cont.)

  • I/O: Files
    • open() Operation Arguments
      • read
      • write
      • append
    • File Operator
  • If, Elif, Else

Overview (Cont.)

  • While Loops
    • While Else
  • For Loops
    • For Looping Dictionaries
  • Break and Continue

Objectives

Flow Control Objectives

By the end of this lesson you should know:

  • How to use comparison operators
  • When, why and how if, elif and else statements are used
  • When, why and how to use while and for loops
  • How to break and continue
  • How to use old and new style formatting
  • How to modify files

Operators

Comparison Operators

  • x == y
    • if x equals y, return True​
  • x != y
    • if x is not y, return True​
  • x > y
    • if x is greater than y, return True​
  • x < y
    • if x is less than y, return True​
  • x >= y
    • if x is greater or equal to y, return True​
  • x <= y
    • if x is less or equal to y, return True

Comparison Examples:

							
								a=7
								b=4
		
								print('a > b is',a>b)
		
								print('a < b is',a<b)
		
								print('a == b is',a==b)
		
								print('a != b is',a!=b)
		
								print('a >= b is',a>=b)
		
								print('a <= b is',a<=b)
		
		
								#Output
								a > b is True
								a < b is False
								a == b is False
								a != b is True
								a >= b is True
								a <= b is False
							
						

Membership Operators

  • in
    • Evaluates to True if it finds a variable in the checked sequence
  • not in
    • Evaluates to True if it does not find a variable in the checked sequence

Identity Operators

  • is
    • Evaluates to True if variables on either side of the operator point to the same object
  • is not
    • Evaluates to True if the variables on either side of the operator does not point to the same object

Boolean Operators

  • and
    • Evaluates True if expressions on both sides of the operator are True.
  • or
    • Evaluates True if expressions on either side of the operator are True.

Operator Examples

							
								# Example using bitwise operators
								a=7
								b=4

								# Result: a and b is 4
								print('a and b is',a and b)

								# Result: a or b is 7
								print('a or b is',a or b)

								# Result: not a is False
								print('not a is',not a)

								#Output
								a and b is 4
								a or b is 7
								not a is False



								# Example using 'in' operator
								list1=[1,2,3,4,5]
								list2=[6,7,8,9]
								for item in list1:
									if item in list2:
										print("overlapping")      
								else:
									print("not overlapping")

								# Output: not overlapping


								# Example of 'is' identity operator
								x = 5
								if (type(x) is int):
									print ("true")
								else:
									print ("false")

								# Output: true
							
						

Assignment Operators

Operator Example Similar
= x = 8 x = 8
+= x += 8 x = x + 8
-= x -= 8 x = x - 8
*= x *= 8 x = x * 8
/= x /= 8 x = x/8
%= x %= 8 x = x%8
**= x **= 8 x = x**8
&= x &= 8 x = x & 8
|= x |= 8 x = x|8
^= x ^= 8 x = x ^ 8
<<= x <<= 8 x = x << 8
>>= x >>= 8 x = x >> 8

I/O Print

Python 2 Basic

							
								print "hello" # print statement only valid in Py2
								print 1+1
								print 'Hello' + 'world'
								print('Hello' , 'World') # print function valid in both Py2 and Py3 (use this)

								# Printing without newline, still has space seperating though
								print "First statement ",
								print "%s" % ("Second statement"),
								print "Third statement"
								# Output: 'First statement Second statement Third statement'
							
						

Python 3 Basic

							
								print("hello")
								print(1+1)
								print('Hello' + 'World')
								print('Hello' , 'World')

								# Printing without newline
								print("First statement ", end=" ")
								print("{}".format("Second statement"), end="")
								print("Third statement")
								# Output: 'First statement  Second statementThird statement'
							
						

% Formatting

% formatting follows C style and is being phased out. It is highly recommend to use .format()… but have practice with both!

% Formatting Examples

							
								​# Basic Positional Formatting
								print "%s World!" % "Hello"
								'Hello World!'

								# Basic Positional Formatting
								print "%s %s!" % ("Hello", "World")
								'Hello World!'

								# Padding 10 left
								print '%10s' % ('test',)
								'      test'

								# Negative Padding (10 right)
								print '%-10s %s' % ('test', 'next word')
								'test       next word'

								# Truncating Long Strings
								print '%.5s' % ('what in the world',)
								'what '

								# Truncating and padding
								print '%10.5s' % ('what in the world',)
								'     what'

								# Numbers
								print '%d' % (50,)
								50

								# Floats
								print '%f' % (3.123513423532432)
								3.123513

								# Padding numbers
								print '%4d' % (50,)
								50

								# Padding Floating Points/precision
								print '%06.2f' % (3.141592653589793,)
								003.14

								# Name Placeholders
								things = {'car': 'BMW E30', 'motorcycle': 'Harley FXDX'}
								print 'My fav car %(car)s and motorcycle %(motorcycle)s' % things
								'My fav car BMW E30 and motorcycle Harley FXDX'
							
						

.format()

Format strings contain "replacement fields" surrounded by curly braces {}. Anything that is not contained in braces is considered literal text.

						
							"The sum of 4 + 5 is {}".format(4 + 5)
						
					

.format() examples

						
							​# Basic Positional Formatting
							print('{} {}!'.format('Hello', 'World'))
							'Hello World!'

							# Basic Positional Formatting
							print("{!s} {!s}".format("Hello", "World"))
							'Hello World!'

							# Actual Positional Formatting
							# EXCLUSIVE
							print('{1} {0}!'.format('World', 'Hello'))
							'Hello World!'

							# Padding 10 left
							print('{:>10}'.format('test'))
							'      test'

							# Negative Padding 10 right
							print('{:<10}'.format('test'))
							'test      '

							# Changing Padding Character
							# EXCLUSIVE
							print('{:_>10}'.format('test'))
							'______test'

							# Center Align
							# EXCLUSIVE
							print('{:_^10}'.format('test'))
							'___test___'

							# Truncating Long Strings
							print('{:.5}'.format('what in the world'))
							'what '

							# Truncating and padding
							print('{:10.5}'.format('what in the world'))
							'     what'

							# Numbers
							print('{:d}'.format(50))
							50

							# Floats
							print('{:f}'.format(3.123513423532432))
							3.123513

							# Padding numbers
							print('{:4d}'.format(50))
							50

							# Padding Floating Points/precision
							print('{:06.2f}'.format(3.141592653589793))
							003.14

							# Name Placeholders
							things = {'car': 'BMW E30', 'motorcycle': 'Harley FXDX'}
							print('My favorite car is a {car} and motorcycle {motorcycle}'.format(**things))
							'My fav car BMW E30 and motorcycle Harley FXDX'


							# Date and Time
							# EXCLUSIVE
							from datetime import datetime
							print('{:%Y-%m-%d %H:%M}'.format(datetime(2017, 10, 17, 10, 45)))
							2017-10-17 10:45


							#Variables
							nBalloons = 8
							print("Sammy has {} balloons today!".format(nBalloons))

							Output
							Sammy has 8 balloons today!


							sammy = "Sammy has {} balloons today!"
							nBalloons = 8
							print(sammy.format(nBalloons))

							Output
							Sammy has 8 balloons today!

						
					

Format Symbols

Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%e exponent notation
%f floating point real number

I/O Print Labs

Lab 3A

I/O Files

I/O Files

Python offers a robust and insanely easy to use toolset to interact with files.

First, a file must be opened before it can be modified... this includes creating new files. We use the open() function to achieve this. The first argument passed is the file name; rather it exists or not. The second argument is the operation in which we would like to perform. ex read, write, overwrite, etc.

							
								file = open("file.txt", 'r')
							
						

open() Operation Arguments

read

  • r -- Opens file for read only. File pointer is placed at start of file.
  • rb -- Opens a file for reading only in binary format. The file pointer is placed at the start of the file.
  • r+ -- Opens a file for both reading and writing. File pointer is placed at the start of the file.
  • rb+ -- Opens a file for both reading and writing in binary format. File pointer is placed at the start of the file.

write

  • w -- Opens a file for writing only. Overwrites the file if it exists. If the file does not exist, it creates a new one.
  • wb -- Opens a file for writing only in binary format. Overwrites the file if it exists. If it does not exist, it creates a new one.

write (cont.)

  • w+ -- Opens a file for writing and reading. Overwrites the existing file if it exists. If it does not exist, it creates a new one.
  • wb+ -- Opens a file for writing and reading in binary format. Overwrites the existing file if it exists. If not, it creates a new one.

append

  • a -- Opens a file for appending. File pointer is at end of file if it exists. If the file does not exist, it creates a new one
  • ab -- Opens a file for appending in binary format. File pointer is at end of file if it exists. If not, it creates a new one.

append (cont.)

  • a+ -- Opens a file for both appending and reading. If file exists, file pointer placed at end of file. If not, it creates a new one.
  • ab+ -- Opens a file for both appending and reading in binary format. Follows above file pointer and write rules.

Binary Formatting

  • binary formatting primarily apply to Windows
  • Windows treats binaries and files differently
  • reading binary in text mode in Windows will more than likely result in corrupted data.
  • Passing a 'b' variant will mitigate this issue

File Operations

Once the file is open, we can begin reading, adding or modifying the file's contents. Below are some of the methods to make that happen.

File Operations

  • f.write(str)
    • write str to file​
  • f.writelines(str)
    • write str to file​
  • f.read(sz)
    • read size amount​​
  • f.readline()
    • read next line​​
  • f.seek(offset)
    • move file pointer to offset​​

File Operations

  • f.tell()
    • current file position​
  • f.truncate(sz)
    • truncate the files z bytes​​
  • f.mode()
    • returns the access mode used to open a file​
  • f.name()
    • returns the name of a file​
  • f.close()
    • close file handle​...​
    • Just like other programming languages, we need to close the stream​
    • ALWAYS CLOSE THE FILE AS SOON AS YOU'RE FINISHED USING IT!!

File Operations Examples

							
								f = open('file_name', 'a')
								data = f.read()
								print data

								file.close()
							
						

I/O Files Lab

Lab 3B

If, Elif, Else

  • Python includes the standard if, else-if, and else statements
  • Python's else-if statement is shortened to elif

If, Elif, Else

  • Python has a standard if, else statement
    • The if statement checks for truth within a given condition
    • If the condition is false, the code within the if statement will not run
    • To counter this, you can use elif statements to check for further conditions
    • The else statement which is a catch all if none of the previous statements evaluate to True

If, Elif, Else example

							
								a = 100
								if a > 100:
									print('a is greater than 100')
								elif a < 100:
									print('a is less than 100')
								else:
								print('a is equal to 100')
							
						

Output

							
								a is equal to 100
							
						

Another Example

What is the output?

							
								for a in range(51):
								if a == 0:
									print("{} you can't divide by zero!".format(a))
								elif a % 10 == 0:
									print ('{} can be divided by 10!!!'.format(a))
								elif a % 2 == 0:
									print('{} is even!'.format(a))
								else:
									print('{} is odd!'.format(a))

							
						

If, Elif, Else Labs

Lab 3C

While Loops

While loops, just like C and C++, loop through each iteration until either the condition is met or a break statement is called.

While Loops Example

							
								count = 0
								while count < 5:
									print('count: ' + str(count))
									count += 1
							
                        

Output

							
								count: 0
								count: 1
								count: 2
								count: 3
								count: 4
							
						

While Else

The while-else runs like a regular while loop except for the one iteration when the while loop becomes false. This results in the else statement being executed once!

While Else

							
								count = 0
								while count <= 4:
									print('count: {}'.format(count))
									count += 1
								else:
									print('while loop executed... count is: {}'.format(count))
							
						

Output

							
								count: 0
								count: 1
								count: 2
								count: 3
								count: 4
								while loop executed... count is: 5
							
						
This gives us a clearer look at how Python increments variables.

When using the while loop, a few factors will make a difference in the output... that could break your program if you don't pay attention. The value of the incrementing var, where the count increment is placed and the comparison operator are the three most common factors. Here are a few things to keep in mind:

While Loops Lab

Lab 3D

For Loops

For Loop in C

							
								char *my_string = "Python";
								for (int i = 0; i < strlen(my_string); i++) {
									printf(%c\n", my_string[i]);
								}

							
						

Python in C Style:

							
								my_string = "Python"
								for i in range(len(my_string)):
									print(my_string[i])
							
						

Python For loop

							
								my_string = "Python"
								for letter in my_string:
									print(letter)
							
                        
  • Strings are iterable
  • The "in" operator simply calculates the count of my_string and iterates through it as var letter
  • The value of letter is my_string[i]

For Looping Dictionaries

One way to set up looping for a dictionary

                            
                                #In python 2 use the method iteritems()
                                for key, value in dict.iteritems():
                                    pass
                            
                        
                            
                                #In python 3 the method is now just items()
                                for key, value in dict.items():
                                    pass
    
                            
                        

Here is an example of how to do this

                            
                                x = {'stu1':'James', 'stu2':'Bob', 'stu3':'Rengar'}
    
                                for stu_id, name in x.items():
                                    print("{}'s name is {}".format(stu_id, name))
                            
                        

Loops: Iterative vs Recursive

  • Iteration and recursion each involve a termination test:
    • Iteration terminates when the loop-continuation condition fails
    • recursion terminates when a base case is recognized
  • Iteration
    • When a loop repeatedly executes until the controlling condition becomes false.
  • Recursion
    • When a statement in a function calls itself repeatedly.

For Loops Lab

Lab 3e

Break and Continue

Break

The break statement simply breaks out of the innermost enclosing loop.

							
								for i in range(1, 101):
									if i == 10:
										print("WE BROKE IT!")
										break
									print(i)
							
						

Output:

							
								1
								2
								3
								4
								5
								6
								7
								8
								9
								WE BROKE IT!
							
                        

Continue

The continue statement continues with the next iteration of the loop.

							
								for i in range(1, 100):​
									if i % 2 == 0:​
										print("{} is an even number!".format(i)​)
										continue #prevents second print from running​
									print("{} is an odd number!".format(i))

							
						

Output:

							
								1 is an odd number!
								2 is an even number!
								3 is an odd number!
								4 is an even number!
								5 is an odd number!
								6 is an even number!
								7 is an odd number!
								8 is an even number!
								9 is an odd number!
								10 is an even number!
								11 is an odd number!
								12 is an even number!
								13 is an odd number!
								14 is an even number!
								15 is an odd number!
								16 is an even number!
								17 is an odd number!
								18 is an even number!
								19 is an odd number!
								20 is an even number!
								....								
							
						

Break and Continue Lab

Lab 3f

Questions?

Summary

  • Operators
  • I/O Print
  • I/O Files
  • If, Elif, Else
  • While Loops
  • For Loops
  • Break and Continue