Search code examples
pythonrandomnumbers

python random numbers and comparison


I'm a new programmer and just starting off with Python. I have the following 2 questions, however, I decided to put them in one post.

  1. When asking to input age, how do I force the program to only accept numbers?
  2. The concept is that after the user has entered their age, the program would pick a random number between 1 and 100 and compare it to the user input, returning either "I'm older than you", "I'm younger than you" or "we are the same age".

    # Print Welcome Message
    print("Hello World")
    # Ask for Name
    name = input("What is your name? ")
    print("Hello " + str(name))
    # Ask for Age
    age = input("How old are you? ")
    print("Hello " + str(name) + ", you are " + str(age) + " years old.")
    random.randint(1, 100)
    

Solution

  • Hi you can try this simply.

    import random
    name = input("What is your name? ")
    print("Hello " + str(name))
    while True :
        try :
            age = int(input("How old are you? "))
            break
        except :
            print("Your entered age is not integer. Please try again.")
    print("Hello " + str(name) + ", you are " + str(age) + " years old.")
    randNumber=random.randint(1, 100)
    if randNumber > age :
        print("I am older than you")
    if randNumber < age :
        print("I am younger than you")
    else :
        print("we are the same age")
    

    Only made few changes to existing code with modifications asked.