1

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")
Banana
  • 1,149
  • 7
  • 24
  • if 1 > rand_num > 10. Make this the first if then use elif after – Matthew Apr 05 '22 at 22:32
  • See e.g. here https://stackoverflow.com/questions/13628791/determine-whether-integer-is-between-two-other-integers Hint: "not (condition)" negates a condition – Banana Apr 05 '22 at 22:35
  • Start by identifying the line of code you need to change. Then describe the steps that you want to put in place instead. Use English (or whatever written language you use the most) and don't worry too much about python syntax. – Code-Apprentice Apr 05 '22 at 22:35

3 Answers3

2

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

kanuos
  • 985
  • 9
  • 16
  • 1
    (...) while True: i += 1 odp = int(input("Input number: ")) if odp > 10 or odp < 1: print("Podana liczba jest spoza przedziału 1-10") else: if (rand_num < odp): (...)Thanks that is what I did on my own before even checking the comments and it works! Thank you for your time - I am Polish btw hence why there is some gibberish in the code lol – Karolina Lęcznar Apr 06 '22 at 11:16
2
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.

Blue Robin
  • 847
  • 2
  • 11
  • 31
1

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)
frost-nzcr4
  • 1,540
  • 11
  • 16