We use a conditional statement to run a single line of code or a set of codes if it satisfies certain conditions. If a condition is true, the code executes, otherwise, control passes to the next control statement.
There are three types of conditional statements as illustrated in the above example:
- If statement: If <expr> is true, execute <statement_1>. Then, execute <statement_2> … <statement_n> unconditionally, irrespective of whether <expr> is true or not. If <expr> is true, execute all of <statement_1> … <statement_n>. Otherwise, don’t execute any of them.
- Elif statement: If the previous condition is false, either it could be “if” condition or “elif” after “if”, then the control is passed on to the “elif” statements. If it is true then the statements after the “elif” condition will execute. There can be more than one “elif” statement.
- Else statement: When “if” and “elif” conditions are false, then the control is passed on to the “else” statement and it will execute.
If we have a block of code then statements in it will be executed sequentially. But, when we want a statement or a set of statements to be executed multiple times then we use loops.
Types of loops:
1.While loop: We use this loop when we want a statement or a set of statement to execute as long as the Boolean condition associated with it satisfies.
In the while loop, the number of iterations depends on the condition which is applied to the while loop.
2.for loop: Here, we know the number of iterations unlike while loop. This for loop is also used for iterations of statements or a set of statements multiple times.
3.nested loop: This type of loop consists of a loop inside a loop. It can be for loop or can be a combination of for and while loop.
Now, we will learn about user-defined functions in this python tutorial.