Today, we will discuss how to make decisions in Python using the If statement and how to get input using the Input() function.
An if statement is simply a statement that checks whether a logical True/False condition is met, and if so does something. If the condition is not met, it can simply ignore it or do something else.
For example, let us say we wish to check if a number is even or odd. To do so, we can check whether the number, when divided by two, gives a remainder of zero. If so, it is even, otherwise, it is odd.
To create an if statement we use the following syntax:
if <condition goes here>:
<do something if true>
Here, our condition is if number%2==0 The % operand means modulus, that is, it gives the remainder of an integer division. We then check if the remainder is equal to zero. We do so by using the == operand.
Warning: The = and == operands are both different. The = operand means assignment of a value to a variable, and the == operand means comparison for equality between two values.
Inside the if statement body, we print out that the number is even. However, if we wish to print out that the number is odd, instead of creating another if statement, we can simply use an else statement. An else statement, unlike an if, does not have a condition body. Instead, it runs the code in the body when all other if's fail. Here is an example:
As we can see, the number three is odd, so the if fails, and runs the else statement.
But what if we wish to check if a number is one, two, or three, and if it is neither of them, return False? Instead of several if statements, we can use an elif statement. In an elif statement, we have a body and a condition, but the whole piece of elif code should follow either another elif or an if statement. Here is an example that uses elif statements:
And that is how we program a conditional in Python. But you may have noticed that whenever we need to change the variable number, we always have to change it in the program. If a consumer was using this code, does that mean he/she should do the same as well?
To fix this problem, we have a function called the input() function. To use it, we just call it as is, or put it in a converter function, as below:
It will wait for an input to convert to an integer and use in a program. Because it will convert the input into an integer, it is necessary to make sure that a number is entered as input, and not anything else:
Those are the ways on how to implement conditionals in Python and how to use the input() function in Python.