Conditional statements are the statements used for the evaluation of a code as either true or false. These are also called decision-making statements. In other words, decision-making or processing of a condition in a Programming language is automated using Conditional Statements. Python has 6 conditional statements as follows:
- If the statement
- If else Statement
- Nested if statement
- If…Elif ladder
- Short Hand if Statement
- Short Hand if-else statement
A piece of code used to specify a task in which multiple inputs may or may not be needed is called a function. Depending on the input and type of task associated with a function, it can return one or more values. There are 3 types of functions in Python as follows:
- help() to ask for help,
- min() to get minimum value
- print() to print an object to the terminal
User Defined Functions:
- def hello() :
- double = lambda x: x*2
Johnny’s mom told him that by the end of the week if he has saved at least one hundred dollars, she would give him an extra ten dollars. If he did not manage to save at least one hundred dollars though, she would prefer not to give him the extra cash.
So now let’s define a function called add_10 which takes as a parameter the unknown m.
Here m represents the money johnny saved by the end of the week.
Now, what should we tell the computer to do is
If m is greater than or equal to 100 then add 10 to the saved amount. If it is not return a statement that lets us know johnny should save more.
That means if m is greater than or equal to a hundred let m assume the value of m+10.
if m >= 100: m = m + 10
Yes, it is what you saw. We have m on both sides of the equation and that is perfectly fine. As a matter of fact, it is not an equation. Remember that the equality sign stands for assigning the expression on the right side to what is written on the left side.
Let’s complete the if the part with return m. To sum up, logically we mention m as a parameter. Then we substitute its value with a greater value than m with 10. In the end, we say from now on return a value equal to the new m. finally in all other cases, for instance, save more. Johnny should learn it is a good habit to have some cash on the side right.
if m >= 100: m = m + 10 return m else: return "Save more!"
def add_10(m): if m >= 100: m = m + 10 return m else: return "Save more!"
When you think of it from a logical perspective it makes sense doesn’t it. What would you use a computer for to solve problems for you and it can do that through functions? You’ll most probably need to ask the machine to execute something if a given parameter is within certain limits and ask it to execute another thing if the parameter is beyond these limits. Therefore combining your knowledge about conditionals and functions in python comes right on the money. You can also check our Projects for more such beginner or advanced Python Projects.