Constructs
del
del
can be used to delete any variable, it de-allocates a variable. After you run del a
, the variable a
was deleted, so we can't access it.
Exercise:
Given that a = [1,2,3,4,[5,6,7]]
Delete the first value.
Delete the second value of the list present at index 4.
Delete the variable a.
Take an input value from the user and delete it (if it is present), print "value not present" if the value is not present in the list.
Given that a = {"IN":"India", "ES":"Espanol"}
Delete the key "IN".
Delete the key "ES"
Delete the variable a.
if-else statment
Read the docs | Watch video 1| Watch video 2
Let's say we work for a school and we are asked to write a program to print out if a student has passed or failed for a particular exam. a
is the score that the student scored in a subject, b
is the maximum marks for the subject. Passing percentage is 35.
Output:
Indentation
Python uses spaces for indentation. Either spaces or tabs can be used for indentation, but not both. Usage of four spaces is recommended.
Scoping
Each statement belongs to one or more "scopes", one direct scope and multiple indirect scopes.
For visualization, let's draw []
around the spaces, so the code now looks like this:
Note: This is not valid Python code,
[]
is used just to show the indentation.
How to find scope?
After a construct which ends with a colon (if/for/while/try/except), calculate the number of spaces in the immediate next line. In this example, it is
four spaces
. The first[]
block.Every line below this line which has
four spaces
at the start until we get a line which doesn't have four spaces is in the if block.
Note: Having indentation without an if/for/while/elif block is a syntax error, for instance, you can't do the following:
The error is because the interpreter isn't able to find out what block the statement belongs to.
elif
The elif
block is special, it gets evaluated if the parent if
block has been evaluated to False.
In our school, we now want to print the grades of students.
Note:
elif
andelse
can't exist without a correspondingif
block. Only theif
block can exist independently.
Output:
Nesting
We can have multiple if blocks inside an if block (same is true with for/while statements). This is called nesting. When we write nested if statements, then the same logic applies to indentation.
This is an example of two level nesting:
Let's add []
to the code to understand scoping for nested blocks.
Each [ ]
can be considered as an indentation block, we can see that if b < 1
has only one block, but this statement, print(" b is less than 1")
has two blocks of spaces, the first one is to if b < 1
which is the primary scope, the secondary scope is to if a > 1
.
Note: This is not valid Python code,
[]
is used just to show the indentation.
Scoping for nested blocks
Here, the statements which lie in the inner if statement lie in two blocks, the inner if statement's block and the outer if statement's block.
Exercise
Take the name, age and score of the user as input. Print their percentage. If the percentage is less than 60, print F, if percentage is between 60 and 70 print B and if percentage is greater than 70 print A. Marks are out of 100.
Take a number from the user and print if it is even or odd.
Take two numbers from the user and print which number is largest.
Take two numbers from the user and print which number is smallest.
Take three numbers from the user and print largest and smallest number.
Take four numbers from the user and create a list.
Take four numbers from the user and create a set.
for loop.
Read the docs
for
statement is used to cycle over a list/set/tuple.
Output:
Explanation:
The program goes through five iterations
Iteration 1: Value of i is 1; loop prints 1;
Iteration 2: Value of i is 2; loop prints 2;
Iteration 3: Value of i is 3; loop prints 3;
Iteration 4: Value of i is 4; loop prints 4;
Iteration 5: Value of i is 5; loop prints 5;
In a for
loop, we can perform other operations too, for the sake of simplicity, we just printed the value of the variable i.
Another approach.
Output:
Explanation: range(5)
returns a list [0,1,2,3,4].
The Else Block
for
has an else block. It is strange at first glance, but it is quite helpful in certain cases, like finding if a number if prime or not.
We will take a simple example where we want to find out if an element is present in a list or not.
Output:
Explanation: The loop is killed by using a break
, if the loop does not get killed, then the value is not present in the list.
Exercise:
Print all numbers till 100.
Print all numbers from 20 to 100.
Print all even numbers less than 100.
Print all odd numbers less than 100.
break, continue, pass
break
Read the docs
The break statement kills the current loop. If we have nested loops, then we have to position the break
properly to kill the correct loop.
The above block will print all the numbers until it hits 4. The moment it hits 4, the for loop will stop executing.
continue
Read the docs
The continue statement takes the execution to the next iteration.
The above block will print all numbers except 4. It continues to the next iteration.
Note: break and continue work with loops only, either
for
orwhile
.
Exercise:
Print all numbers from 0 till 10 except 4 and 5.
Print all numbers from 0 till 20 except those divisible by 3.
a = [1,2,3,4,5], take an integer as input from the user. Print all numbers which are less than the input number using break.
pass
Pass can be used as an empty placeholder in places where you don't have anything to add.
For instance, in the above if-else block, you really don't know what logic you are going to put, so you can either use print("TODO")
, or use the pass statement. pass doesn't print anything. You can use pass in any loop.
while loop.
Read the docs
while
is used when you have to loop for a specific condition. If you don't have a condition, you can use True
and that would result in an infinite loop.
Output:
Explanation: The while
statement will loop on the condition, until the condition evaluates to False
. The loop exits when the condition becomes False.
Note: The
while
statement also has an else block, we encourage you to play with it to understand it better.
Exercise:
Print all numbers till 100 using while.
Print all numbers from 100 to 1 using while.
Print all even numbers less than 100 using while.
Print all odd numbers less than 100 using while.
For a list [1,2,3,4,5], write a program which checks if 6 is present in the list, using while.
Print all numbers from 0 to 10 except 4 and 5.
try - except - finally
Read the docs
try-except is used for exception handling, we'll take a look at it in a later chapter.
with
Note: requires the knowledge of file handling, you can come back to this chapter after reading the file handling chapter.
Read the docs
The with block was added in PEP 343. support of the Resource Acquisition Is Initialization idiom commonly used in C++. It is intended to allow safe acquisition and release of operating system resources.
Resources are created within a scope/block, resources are cleanly released whether the block exists normally or because of an exception.
Output:
Because of scoping, the input_file
and output_file
variables are only available within the with clause. This can result in some clean code, but it is upto you totally. I like to use try-except-finally.
We encourage you to read more about the range
function. Please do not use the Internet, use the help
function. The faster you get familiar to using the documentation, the better programmer you become. In a world full of people Googling "how to create a string in Python", we really need to be self sufficient as to using the documentation that a language provides to differentiate from others. The mark of a great programmer isn't in how much things she can store in her memory, it is in the mastery of the tools she uses, documentation and the help command are among the tools.
Links
Last updated