Karolina Lęcznar
Karolina Lęcznar

Reputation: 19

Python guessing game -if/elif/else

I've just started learning Python and have constructed a little guessing game. It works but I would like to add a statement that if inputted number is out of range 1-10 there will be an error... Could you help or give me a hint? I suppose I should use nested if/else statement but not sure where:

import random as r

rand_num = r.randrange(1, 10)
odp = 0
i = 0
print("Guess the number from range 1-10")

while True:
    i += 1
    odp = int(input("Input number: "))

    if (rand_num < odp):
        print("Selected number is lower than you had inputted...")
    elif (rand_num > odp):
        print("Selected number is higher than you had inputted...")
    elif (rand_num == odp):
        break

print("Congrats! You have guessed the number after ", i, " tries")

Upvotes: 1

Views: 1053

Answers (3)

frost-nzcr4
frost-nzcr4

Reputation: 1620

You should definitely read how the control flow works and maybe try another good option like continue to skip the current iteration and run next one (without the use of large branching statements):

def game(minimum=1, maximum=10):
    rand_num = r.randrange(minimum, maximum)
    odp = 0
    i = 0
    print(f"Guess the number from range {minimum}-{maximum}")

    while True:
        i += 1
        odp = int(input("Input number: "))
    
        # Validate the input value.
        if odp < minimum or odp > maximum:
            print("Invalid input")
            # To skip the following lines and start next cycle of while-loop
            continue

        if rand_num < odp:
            print("Selected number is lower than you had inputted...")
            continue

        if rand_num > odp:
            print("Selected number is higher than you had inputted...")
            continue

        if rand_num == odp:
            if i == 1:
                print("Cheater!")
            else:
                print("You win!")
            break

game(2, 25)

Upvotes: 1

Blue Robin
Blue Robin

Reputation: 1106

import random as r

rand_num = r.randrange(1, 10)
odp = 0
i = 0
print("Guess the number from range 1-10")

while True:
    r.seed(r.random())
    i += 1
    input_user = int(input("Input number: "))
    if abs(input_user) <= 10:
        print(abs(input_user) <= 10)
        if rand_num < input_user:
            print("Selected number is lower than you had inputted...")
        elif rand_num > input_user:
            print("Selected number is higher than you had inputted...")
        elif rand_num == input_user:
            print("Selected number is correct!")
            break
    else:
        print("Invalid number")

Put the else statement after all of the if/elif statements. Also, use a different seed each time to randomize the variable each time you run it.

Upvotes: 2

kanuos
kanuos

Reputation: 1203

You are on the right track there. You can use a nested if-elif block to check whether the number is in the range (1-10) and on error you could prompt a message saying that.

However, whenever you are using user inputs, you must use try except blocks. You are assuming that the user would enter a stringified integer. What if the user enters an invalid character? What if the user enters a fraction? You could keep on using if-elifs to check all the probable inputs. You probably can see how inefficient and verbose your code becomes. If you are new to Python's error handling and haven't learnt try except finally use the nested if elifs.

However, this is how I would do the same problem

 import random as r

rand_num = r.randrange(1, 10)
odp = 0
i = 0
print("Guess the number from range 1-10")

try:
  while True:
      i += 1
      odp = int(input("Input number: "))

      if odp > 10 or odp < 1:
        raise ValueError("Out of bound error")
    
      if (rand_num < odp):
          print("Selected number is lower than you had inputted...")
      elif (rand_num > odp):
          print("Selected number is higher than you had inputted...")
      elif (rand_num == odp):
          break

except ValueError as e:
  print(e)

You should also check for invalid types. Here's the official doc error handling

Upvotes: 2

Related Questions