Week 5: If/Else Statements & Loop


Section 1: Assignment QA¶


Section 2: Built-in functions¶

A. File I/O:

  • Use open(path[,mode='r']) function.
    • Modes: read ('r') or write ('w') or both ('r+') or append ('a')
  • Input: .readlines() method will extract all content in the file as a list of strings. One paragraph, one string.
  • Output: .write(string) method write the given content to the file, from the beginning of file if mode 'w' is used or from the bottom of file if mode 'a' is used.
  • Save and Close File: .close() method
  • Tips:
    • Add line break \n
    • Remove line break or whitespaces at the beginning or the end of a string: method .strip()
    • Use slash / to denote directory
    • You need to the file to make the changes
In [82]:
# Create a new file named "text.txt" in the current folder
file = open('text.txt','w')
In [83]:
#add three new lines, separated by line break mark \n
file.write("Hello world!\n")
file.write("COMM 7780\n")
file.write("Bye bye!\n")
Out[83]:
9
In [84]:
#close it
file.close()
In [85]:
# Create a child folder test
# Create another file named "text2.txt" in the child folder
file2 = open("./test/text2.txt", "w")
file2.close()
In [2]:
# Create a file named "text3.txt" on Desktop
file3 = open("C:/Users/yuner/Desktop/text3.txt",'w')
file3.close()
In [94]:
#Read text.txt file
file = open('text.txt','r')
In [95]:
#read the existing lines into a list
lines=file.readlines()
In [96]:
#print out the first line
lines[0]
Out[96]:
'Hello world!\n'

B. If/Else Statement

  • If/Else Statement is used to test whether a condition is True. If statement is always followed by a question, a comparison condition, a logical operator, which will give you a boolen value of True or False. If True, do something. If False, do something else.
  • Format: if logical_condition1 :... (else: ...)
  • Example:

if a==1: print('yes') #Block A else: print('no') #Block B``` >

In [102]:
x = 1
if x==0:
    print('ZERO!')
    print('Yes!')
else:
    print('Not Zero!')
    print('No!')
print('Done!')
Not Zero!
No!
Done!
**Extra Knowledge** If/Else statement can be upgraded into a If/Elif/Else statement. Elif = Else + If
In [4]:
x = 2
if x==0:
    print('ZERO!')
    print('Yes!')
elif x==1:
    print('ONE!')
    print('No!')
else:
    print("Not ZERO nor ONE!")
print('Done!')
Not ZERO nor ONE!
Done!

Exercise¶

Write a program to determine if a number x is positive.
If x is positive, determine if it is odd or even.

In [ ]:

C. For Loop & While Loop

  • Two types of scripts: Sequential vs Iterative
  • Iterative scripts = Loop
    • For loop (based on counter/list) & While loop (based on condition)
    • Do repeated actions

While Loop¶

  • while loop is used to repeatedly execute a block of commands while a condition is True.
  • Characteristics: Indefinite iterations, where the number of iterations is not specified explicitly in advance
    • Format:

while condition: #loop condition statements #loop body

  • Syntax: In above format, statements refer to a block of commands subordinate to while loop. They are only functional within for loop. Python requires INDENT Tab or 4 spaces to group commands into block. For example:

n=5 while n>0: print(n) #Use indentation to denote a Block subordinate to while loop n-=1 #Decrease by 1 unit print('Blastoff!') #Out of the while loop

**Warning**: To create a loop, the most important thing is clearly defining an exit condition. Loops should not iteract forever. You should ensure the loop will only go on for finite steps.

Exercise¶

Write a GUESS NUMBER program using while loop:

  • Ask the user to guess the value of a number in your mind
  • If his/her answer is LARGER than your value, print "Your guess is TOO LARGE! Try Again!"
  • If his/her answer is SMALLER than your value, print "Your guess is TOO SMALL! Try Again!"
  • Stop the game when he/she gets the right value
In [ ]:
#Write your codes here
answer = 58

For Loop¶

  • for loop is used to step through items in a list and repeatedly execute a block of commands for each item.
    • Format:

for var in object_list: #Assign object items to target statements #Loop body


- `for` loop naturally includes a step for variable assignment: assign every value in the list to variable var
- Usually coupled with `range([start=0,] stop[, step=1])` function, which will automatically create a list of whole numbers ranging from the start number and stopping at but <font color="red">not including the stop number</font>.
        - range(5) = [0,1,2,3,4]
        - range(1,5) = [1,2,3,4]
        - range(0,5,2) = [0,2,4], Step = 2
- Syntax: Indentation within the for loop:
>```python
for a in range(5):
        print(a)       #Use indentation to denote loop body
        print(a+1)
        print(a+2)
In [ ]:
#Use for loop to print out the first 10 whole numbers
In [ ]:
#Use for loop to print out all EVEN numbers smaller than 25
In [ ]:
#Use for loop to print out the sum of the first 100 whole numbers
In [ ]:
#Read lines in text.txt and print out the number of CHARACTERS, including spaces, and the number of WORDS in each line
In [ ]:
#Repeat every line three times, i.e. copy each line and paste it three times to the file. 
#Save the outputs.
In [ ]:
#Cut lines in above created file by words. One word, one line. Save the outputs.
**Extra Knowledge: List Comprehension = For Loop in the List**
We can use a loop in the list to create a new list based on an old one.
In [ ]:
a=[0,1,2,3]
#two ways to increase every element in a by one unit
#---------------------------------
#1
b=[]
for i in a:
    b.extend([i+1])
print(b)
In [ ]:
#2
b=[i+1 for i in a]
print(b)
**Extra Knowledge**
1. We can use continue statement to skip following commands and directly jump to next iteration.
2. We can use break statement to quit the loop.
In [ ]:
#Try continue statement
for i in range(10):
    if 2<i<5:
        continue
    print(i)
In [ ]:
#Try break
for i in range(10):
    print(i)
    if i>5:
        break

Quiz¶

https://www.menti.com/algtsr8jam1i

Section 3: Build our own function¶

  • The function of customer function is to transform x into y. Like a magic trick turning a girl into a tiger.
  • Function is a block of reusable codes. Annotation: y=f(x), where x is a list of input variables and y is a list of output variables.
    • Terminology: inputs = parameters or arguments, outputs = returned values
    • Global vs Local: function can create its local variables that are only used inside its boundary. Local variables can use same names as global variables without overriding their values.
    • Format:

def function_name(input1[,input2,input3...]): command line return ```

In [ ]:
#Create a custom function series_sum() to report the sum of the first N whole numbers
#HINT: Input value: n, Output value: sum of the series
def series_sum()
In [ ]:
def minus_one(a):
    a=a-1
    print('local variable a:',a)
    return
In [ ]:
a=4
print('global variable a:',a)
test(a)
In [ ]:
 
Presidential inauguration speeches capture the sentiment of the time.

Practice: Inauguration Speech¶

Download the dataset from:https://juniorworld.github.io/python-workshop//doc/presidents.rar

Expected Objectives:

  1. Total number of sentences in the speech:
    • End of Sentence Marks: the period (.), the question mark (?), and the exclamation point (!).
  2. Total number of words in the speech
  3. Average length of sentences
  4. Coleman–Liau index of Readablity

Coleman–Liau index:¶

CLI = 0.0588 * L - 0.296 * S - 15.8


L is the average number of letters per 100 words and S is the average number of sentences per 100 words.
CLI is equivalent to the number of years of education completed by the speaker.

In [ ]:
presidents=['Washington','Jefferson','Lincoln','Roosevelt','Kennedy','Nixon','Reagan','Bush','Clinton','W Bush','Obama','Trump']
In [ ]:
for president in presidents:
In [ ]:
def readablity_test(paragraphs):
#Define a customer function readablity_test() to output sentence_count,word_count and letter_count
In [ ]:
#Save results to a csv file