How to Check if User Input is Between Two Values in Python?

Estimated read time 2 min read

To check if user input is between two values in Python, you can use a combination of comparison operators (<, >, <=, >=) in an if statement. Here’s an example:

lower_limit = 10
upper_limit = 20

user_input = int(input("Enter a number: "))

if lower_limit <= user_input <= upper_limit:
    print("User input is between the lower and upper limits.")
else:
    print("User input is outside the lower and upper limits.")

In this example, the lower_limit and upper_limit variables represent the range within which the user input should be. The input() function is used to receive the user’s input, and int() is used to convert the input into an integer.

The if statement checks if lower_limit is less than or equal to user_input, and user_input is less than or equal to upper_limit. If this condition is true, the code inside the if block is executed, and the message “User input is between the lower and upper limits” is printed. If the condition is false, the code inside the else block is executed, and the message “User input is outside the lower and upper limits” is printed.

You can adjust the values of lower_limit and upper_limit to fit your specific requirements. Additionally, you can modify the data type conversion or validation based on the type of input you expect from the user.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply