Home > Software design >  A python question regarding guessing a random number, there's an error in my code
A python question regarding guessing a random number, there's an error in my code

Time:08-08

I have a question that is asking me to create a kind of guessing game, basically, I have to write a code that makes the computer generate a random number from 0-100 and the user has to guess this number. The code which I wrote is giving me an error, can anyone assist me when it comes to fixing my code? (I just started programming so my bad if it's a really basic mistake.)

import random
import math

x = random.randint(0, 100)
guess = int(input("Guess a number: "))
    if x == guess:
        print("You got the right number!!!")
 elif x > guess:`enter code here`
    print("The number you guessed was less than the actual number!")
 elif x < guess:
     print("The number you guessed was more than the actual number!")

CodePudding user response:

  1. enter code here is not supposed to be there
  2. if x == guess: is not supposed to have an indent
  3. The math import is unnecessary

So it should be:

import random

x = random.randint(0, 100)
guess = int(input("Guess a number: "))
if x == guess:
    print("You got the right number!!!")
elif x > guess:
    print("The number you guessed was less than the actual number!")
elif x < guess:
    print("The number you guessed was more than the actual number!")

CodePudding user response:

If my assumptions are correct, it should be an error with the indenting.

In line 6, if x == guess: and line 8 elif x > guess:, they are on different indent levels.

Adjusting the if statement should fix the error, something like this:

import random
import math

x = random.randint(0, 100)
guess = int(input("Guess a number: "))
if x == guess:
    print("You got the right number!!!")
elif x > guess:
    print("The number you guessed was less than the actual number!")
elif x < guess:
    print("The number you guessed was more than the actual number!")

You need to make sure all the ifs and elifs are on the same indent level for it to work.

  • Related