Python - Taking Conditional User Inputs



Generally, Input makes the program interactive, allowing the users to provide the data to the program that can use to make decisions. However, in many situations, we don’t want raw input but we want to react differently depending on what the user enters. This is where the conditional user inputs comes in.

Conditional user inputs indicates that after collecting input from the user, the program decides what to do next based on certain conditions. Python provides the simple structures such as if, elif and else to handle these decisions. For example,

  • Checking the eligibility to vote, if the user enters the age.
  • Displaying the grades of the students, if the student enters the marks.

Different Conditional User Inputs in Python

Let's dive into the tutorial to learn more about the different conditional user inputs in the python.

Using if and else Conditions

It is basic form of the conditional input. After receiving the input from the user, it uses the if statement to check a condition and retrieves the different responses based on whether the condition is true or false.

Example

In the following example, we are going to check whether the entered number is positive or not using the if-else condition.

x = int(input("Enter a number: "))
if x > 0:
    print("It Is A Positive Number")
else:
    print("It Is Not A Positive Number")

Following is the output of the above program -

Enter a number: 8
It Is A Positive Number

Using if-elif-else Conditions

It is used when there are multiple possibilities. It evaluates the conditions one by one until it finds one that is true. If none match, the else block is executed.

Example

Consider the following example, where we are going to check whether the number is positive, negative or zero.

x = int(input("Enter a number: "))
if x > 0:
    print("Entered Number Is Positive")
elif x < 0:
    print("Entered Number Is Negative")
else:
    print("Entered Number Is Zero")

The output of the above program is -

Enter a number:0
Entered Number Is Zero

Using Nested if Conditions

The nested if indicates that the one if statement inside the another. It is used when one decision depends on another.

Example

In the following example, we are going to check if the person is eligible to vote. Here, we will check the age first, if the age is valid, then we will check the citizenship.

x = int(input("Enter your age: "))
y = input("Are you a citizen (yes/no)? ")
if x >= 18:
    if y.lower() == "yes":
        print("Eligible to vote.")
    else:
        print("Must be a Citizen to vote.")
else:
    print("Must be at least 18 years old to vote.")

Following is the output of the above program -

Enter your age: 24
Are you a citizen (yes/no)? yes
Eligible to vote.
Advertisements