Control Structure and Text files

Conditionals

Similar to other programming languages, python also uses “if” statements for conditions. But python uses “elif” instead of “else if” for following conditions. Besides, python neither use parenthesis (“()”) to cover the conditions nor use curly brackets (“{}”) to cover the blocks. Instead, it’s necessary to indent our codes to make sure they are covered by either conditions or loops.

The if/elif/else blocks in python:

if <condition>:
    <this will execute if the condition is true>
elif <new condition>:
    <this will execute if the previous condition is not true but this new condition is true>
elif <newer condition>:
    <this will execute if the previous condition is not true but this newer condition is true>
else:
    <this will execute if all previous conditions are false>

Small note: while we have to start with “if”, we can have however many “elif”s we want (include none), and the “else” is optional.

>>> x = 15
>>> if x > 20:  # this statement is false
...     print("x is greater than 20.")
... else:       # this statement is true
...     print("x is less than 20.")
... 
x is less than 20.

# more complicated if-elif-else block
>>> A = 17
>>> B = 23.4
>>> if A > 10:
...     print("apple")
... elif B >= A:
...     print("orange")
... elif A == 17:
...     print("banana")
... else:
...     print("eggplant")
... 
apple
# in the previous codes, A = 17 > 10, the first "if" block will be executed
# the rest of the codes will not be executed, even though some of them are true

Loops

In python, loops are “for” loops and “while” loops. Loops are used in some repeated procedures. For example, if we want to add all the number between 1 and 100, instead of doing “1+2+3+4+…+100” manually, it’s better use a loop to add them together. Both “for” and “while” loop will keep repeated the codes inside the block until the condition is no longer true. The conditions in “for” loops are somehow different from those in “while” loops. The variable used in “while” loop condition has to be predefined, while it’s not necessarily in “for” loop.

# the "while" loop will be like:
<dummy var> = <initial value>
while <dummy var> < <some value>:
    <repeated codes>
    <increment the dummy var>

# the "for" loop will be like:
for <dummy var> in <iterable container>:
    <repeated codes>

# add all the numbers between 1 and 100:
# while loop:
>>> i = 1
>>> sum = 0
>>> while i <= 100:
...     sum += i
...     i += 1
... 
>>> print(sum)
5050
# for loop:
>>> sum = 0
>>> for i in range(1, 101):
...     sum += i
... 
>>> print(sum)
5050

# we can create a infinite loop in while loop using True in condition:
>>> i = 1
>>> while True:
...    print(i)
...    i += 1

# Python has a special command called "break" to end a while loop prematurely
>>> i = 1
>>> while True:
...     print(i)
...     i += 1
...     if i > 20:
...             break
... 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# we can also use nested "for" loops or "while" loops
>>> for i in range(1, 10):
...     print("i = ", i)
...     for j in range(1, 10):
...             print(i * j)
# note: the dummy vars in nested loop need to be different

# SPECIAL NOTE:
# we can even add a "else" statement after the loops
>>> for i in range(10):
...     print(i)
... else:
...     print("end!")
... 
0
1
2
3
4
5
6
7
8
9
end!
# the "else" block will be executed right after the loop ends
# if there is a "break" command that forces the loop end early, the "else" block won't be executed 

Functions:

In python, there are built-in functions like “print”, “type”, “range”, and etc. We can also define our own function for our convenience. It’s easier to define our own functions in python than other languages, like C, or Java. In C, C++, or Java, a function or method needs to have a return type even though it doesn’t return anything. But in Python, it’s not necessary to include the return type. And the types of input arguments are not needed.

The functions are defined as below:
def <fun_name>(var_1, var_2):
<this codes will be executed when this function is called>
Small notes: the “def” keyword is a must, but var_1, var_2, and return statement are not, depending on the need.

# define a function that multiples two number
>>> def mul(a, b):
...     return a * b
... 
# call the function
>>> print(mul(10, 20))
200

Text file

Reading and writing files in other languages might be complicated. We need to interact with file streams, and close the file stream to avoid memory leak. But here in Python, a simple “with open” statement can easily open the file and close the file stream automatically.

# define text file in a function
def read_txt():
    with open("my_text.txt", "r") as f:
        my_str = f.read()
    print(my_str)
    
def write_txt(new_str):
    with open("my_text.txt", "w") as f:
        f.write(new_str)

# small note:
# inside open(), we need to declare the "mode" that we intend to use:
# common mode: "r"-read, "w"-write, "a"-append, "b"-binary file
# common functions for "f":
# read():read the whole file and store every line in to a string
# readlines(): read the whole file and store every line in to a list
# readline(): read only one line
# write(): write a string to the file
# writelines(iterable container): write the strings in the containers to file

More on files input/output: if we open a file in “r” mode but the file does not exist, python will raise a “FileNotFoundError”. But if we open a file in “w” mode but the file does not exist, a new file will be created. If the file exists, the content of the file will be override in “w” mode. To append the content, we need to use “a” for appending.For the files that aren’t in the same folder of the .py file, use the absolute path for the file name.

Leave a Reply

Your email address will not be published. Required fields are marked *