Program to check the User Enter a String or Numerical Value in Python

Program to check the User Enter a String or Numerical Value in Python

Program to check the User Enter a String or Numerical Value in Python, in this Article i will show you , how to check whether the User enter  the correct types of input.String or Numerical

Checking String Input

Since the ” input()” takes in the String Value , i will use a while loop to check whether the User enter  a valid string Input

Checking Numerical Input

I will Use Exception Handling to Check whether the User enter a Valid Numerical Input

 

Sample Code:

  1. First I will create a Python List to list all types rating
  2. Then i create a function “movierate(age,type): “ to check whether the User  input Age suitable to view the kind of rated Movie that the User Inputed
  3. Then i use  a while loop with Exception Handling  “ValueError” to check whether the User Input an integer value
  4. Then i use the while loop to check whether the User Input category is available in the  rated  list
  5. If All String and Numerical Parameter are input correctly , the parameter is passed into the movierate(age,type): function

 

# types of Movie

rated = ["PG", "R","General","M18"]
# Create a Function to check the User Age able to view the rated Movie


def movierate(age,type):

    if age > 18 and type in rated:
        print("you can view all type of Movie")
    elif age < 18 and type == rated[0]:
        print("This Movie is For Adult")
    elif age < 18 and type == rated[1]:
        print("This Movie is For Adult")
    elif age < 18 and type == rated[3]:
        print("This Movie is For Adult")

    else:
        print("You Can Watch this Movie")

# Ask the User to enter the Age

while True:
    try:
        x = input("Please enter a number: ")
        userAge = int(x)

        break
    except ValueError:
        if len(x)==0:
            print( "you entered nothing")
        else:
            print ("Oops!  That was no valid number.  Try again...")

catMovie = input("Please enter  the Cateorgory: ")

while catMovie not in rated:
    catMovie = input("Please enter  the Cateorgory: ")

movierate(userAge, catMovie)

Check out Context Manager in Python Here

Leave a Reply

Your email address will not be published. Required fields are marked *

two + 10 =