Python Small Things – II

We will discuss about:

  • Multi-line statements
  • Suite

Multi-line statements

Statements in Python usually are single line and there is no end character for the statement. 

When a statement needs to continue, or we desire to write it on many lines to make it more readable we can use “\” character 

Example:

polygon_perimeter = side1 + \

                                   side2 +\

                                   side3 +\

                                   side4 +\

                                   side5 


When statements are inside brackets i.e. (), [], {} need to spread multiple lines, there is no need for / character

Brackets are used in special for data structures, [] is used lists, () for tuple, and {} for dictionary


 Hence, we can have: 


 list example on multi- line:

list1 = ['elem1', 'elem2', 'elem3', 'elem4',

        'elem5', 'elem6', 'elem7', 'elem8']


 tuple example on multi-line:

tuple1 = ('tup1', 'tup2', 'tup3', 'tup4',

         'tup5', 'tup6', 'tup7', 'tup8')


 dictionary example on multi-line:

dict1 = {

    "category": "Computers",

    "type": "boolean",

    "difficulty": "medium",

    "question": "The HTML5 standard was published in 2014.",

    "correct_answer": "True",

    "incorrect_answers": "False"

}

 


Code block or suite


In below example: 

price=12

if  price >= 10:

discount=0.2

print("discount is higher")

else: 

discount=0.15

print("discount is smaller")

print(f"My discount is {discount}") 

Two statements that follow after if price>=10: represent a code block or sometime named suite. Here suite contains 2 statements, in general it can contain more lines, those lines are indented in the same way. 


For if referring to suite we have general syntax like below:

if condition1:

suite

elif condition2:

suite

else:

suite

In this syntax statements if condition1: , elif condition2: and else: are named header. A header line begins with a keyword, contain others like conditions, expressions and end with colon ":"

Structure with header lines and suite is encountered for other complex statements like while, def,  class etc

Python Small Things – I

Just title written in three words to be short and to get attention, but I think most proper title can be "Python Small Things But Important". We will discuss about:

  • Comments
  • Quotation

Comments

Any line that begins with a hash (i.e. # ) is a comment. 

Example, first line from below is a comment:


# Follow import packages section 

import sys

import random

import pandas


Python interpreter ignores comment lines. The role of the comment is to document the code.

There is no sign to comment multiple lines in Python, thus when many lines need to be commented we need to comment each one. 

Sometime we use comments to make unusable a code line, we think that the line will not be needed as for example we replaced it with something else, but we still need to keep it for a while, thus we comment it, and interpreter will skip it.

Example of multi-line comment and lines commented to become inactive: 


#file1 = open("file1.txt", "r")

#print(file1.readlines())

with open("file1.txt") as file1:

    file_1_data = file1.readlines()

print(file_1_data)


Quotation

All, single quotes → ' , double quotes → "" and triple quotes → """ or ''' are used for assigning values to string variables.


Example: 

var1 = 'sky'

var2 = 'The sky is blue'


but we can use also:

var1 = "sky"

var2 = "The sky is blue"


The idea is that at the beginning and the end of string to use the same quote type.


Triple quotes are used when strings occupy many lines.

Example:

var3a = """Today is a sunny day, no clouds at all 

and the sky is blue"""


#or 


var3b = '''Today is a sunny day, no clouds at all 

and the sky is blue'''


A particular use case for single ' and double "" is when we need to print or have a variable that contain a  word that is quoted. For example we need to have a variable that have like value  Today is a 'sunny' day


If use: 

var4 = "Today is a "sunny" day"

print(var4)

this will give error: 

File "C:\Users\Stefan\app-start\test.py", line 1

var4 = "Today is a "sunny" day"

^^^^^

SyntaxError: invalid syntax


Solution is to use:

var4 = 'Today is a "sunny" day'

print(var4)


that will print indeed:

Today is a "sunny" day


Or something a little bit similar:

var4 = "Today is a 'sunny' day"

print(var4)

which will print:

Today is a 'sunny' day


The rule to quote string inside other string is to do it with different quotes. Means for example if the big string is between single ‘ we can quote inside it using double quote. 

Nested IF In Python

There are situations when we need to check inside an if body other condition, means we will have other if on that body, or a nested if as often we see in programming terminology.

What if for our previous example about discount:

price=12

if  price >= 10:

discount=0.2

print("discount is higher")

else: 

discount=0.15

print("discount is smaller")

print(f"My discount is {discount}")

We need to give supplementary discount depending of the quantity, if price is greater than 10 and quantity is greater than 15 discount is higher with other 0.05 


Then sample code is: 

price=12

quantity=17

if  price >= 10:

discount=0.2

if quantity>15:

discount=discount+0.05

print("discount is higher")

else:

discount=0.15

print("discount is smaller")

print(f"My discount is {discount}")

Here commands executed in first if body are: 

discount=0.2

if quantity>15:

discount=discount+0.05

print("discount is higher")

here, inside it nested if is:

if quantity>15:

discount=discount+0.05

This is indented at the same level as the other commands, and the body of the nested if, I.e. discount=discount+0.05 is indented with one tab more.


In our example there is an if nested in if body, but it can also be inside else body, or inside of both if and else.

Below is an example:

price=7

quantity=17

if  price >= 10:

discount=0.2

if quantity>15:

discount=discount+0.05

print("discount is higher")

else:

discount=0.15

if quantity>15:

discount=discount+0.03

print("discount is corrected based on quantity")

print("discount is smaller")

print(f"My discount is {discount}")

and output of this is:

discount is corrected based on quantity

discount is smaller

My discount is 0.18


Process finished with exit code 0


A general syntax for nested if, with two levels nested is:

if conditionLevel1a: 

statements 

if conditionLevel2a: 

statements

elif conditionLevel2b: 

statements

else: 

statements 

elif conditionLevel1b: 

statements

else: 

statements


Or there can be:

if conditionLevel1a: 

statements 

elif conditionLevel1b: 

statements

if conditionLevel2a: 

statements

elif conditionLevel2b: 

statements

else:

statements 

else: 

statements

Obviously, there can be something similar having if inside else body. Also, in whatever cases from above we can have statements then nested if, or first to have nested if and then other statements.


We can have multiple nested levels, one general example for three level nested is: 

if conditionLevel1a: 

statements 

if conditionLevel2a: 

statements

if conditionLevel3a: 

statements

elif conditionLevel3b: 

statements

else:

statements 

elif conditionLevel2b: 

statements

else:

statements 

elif conditionLevel1b: 

statements

else: 

statements

If Else In Python

Very often in life something is happening depending by a condition and as programs solve something from life, in programs we need to use conditional statement. 

Basic python conditional statement is if/else and general syntax is:

if condition:

do something i.e. execute it when condition is true

else: 

do something else i.e. execut when condition is false


 Let’s see a simple example:  

price=12

if  price >= 10:

discount=0.2

else: 

discount=0.15

print(f"My discount is {discount}") 


 To understand more any if/else can be represented in a diagram or a logic flow chart, for our case: 

 

if-else-flowchart


 Important to underline:

  • after "condition" there is colon i.e. ":" character 
  • "do something..." which follow after condition is right indented
  • what is after else, means "do something else..." is right intended
  • indentation is a must and it means all instructions with the same indentation will be executed as part of the condition accomplished or as part of else block


Further about our example:

price=12

if  price >= 10:

discount=0.2

print("discount is higher")

else: 

discount=0.15

print("discount is smaller")

print(f"My discount is {discount}")

After if condition we can have one or many instructions, also after else we can have one or many instructions, and in both cases those need to be identical indented, which means for python that those will be executed together  


 And the code executed is:

  

if-else-example

F String In Python

Let's presume we have a simple problem like to calculate a surface area code is:

slength = 10

swidth = 9

area = len * wid

print ("Surface area is " + area)

Obviously this will give error:

TypeError: can only concatenate str (not "int") to str

Hence, we will change to have: 

slength = 10

swidth = 9

area = slength * swidth

print ("Surface area is " + str(area))

The idea with f string is that it helps to write in better way expression from print function from above example. Means it help in writing that concatenated string more concise.

Referring to "Surface area is " + str(area) we can write it easier with f string. There are two elements important for f string:

  •  first in front of the string we put f means we will have f"Surface area is "

  • second between " " we can write directly variables but those should be between curly braces i.e. "Surface area is " + str(area)  will be f"Surface area is {area}" 

So, our example is: 

slength = 10

swidth = 9

area = slength * swidth

print (f"Surface area is {area}")

Some observations:

  • There is no space between f and "Surface area is {area}" means it is f"Surface area is {area}"    and not   f "Surface area is {area}".

  • There is no need for str conversion function for area variable, conversion is performed basically by curly braces and/or "f". Means f string does all.
  • We can add further other text and/or use many curly braces. We can write for example:
    print (f"Surface area is {area}", the length is {slength} and the width is {swidth}" )

Code is now: 

slength = 10

swidth = 9

area = slength * swidth

print (f"Surface area is {area}, the length is {slength} and the width is {swidth}” )

Attention: once adding other text and variabiles, don’t forget to move the right " at the end means it need to be 

print (f"Surface area is {area}, the length is {slength} and the width is {swidth}" )

and not 

print (f"Surface area is {area}", the length is {slength} and the width is {swidth} )

Running the example: 

F string run example