-1

I'm a python beginner in and got an assignment for school to make the simple number guessing "game" where you have to figure out a number by guessing and it either says higher or lower until you guess the correct number. It worked well until i added two player support and the ability to choose the interval that the random number will be in. Now the higher/lower result from the guess is the opposite if the amount of digits in the guess is different from the random unkown number. Lets say that the random number is 50, then guessing a number between 10-49 will give the result "guess higher", guessing a number between 99-51 will give the result "guess lower" like it's supposed to do. However if the guess is a different amount of digits like 0-9 it will say "guess lower" which is the opposite, same if i guess 100 or anything above it will say "guess higher".

The code:

import random


while True:
  select = input("En eller två spelare? ")
  if select == '1':
    y = input("0 - ")
    num = str(random.randint(1, int(y)))
    while True:
      guess = input('Gissa mellan 0 - ' + y+": ")
      if guess == num:
        print('Rätt nummer: ' + guess)
        break
      elif guess == "haks":
        print(num)
      elif guess < num:
        print('Högre än ' + guess)
      elif guess > num:
        print('Lägre än ' + guess)
  
  
  if select == '2':
    spelare1 = input("Spelare 1: ")
    spelare2 = input("Spelare 2: ")
    y = input("0 - ")
    num = str(random.randint(1, int(y)))
    spelare = 0
    
    while True:
      if spelare%2 == 0:
        print(spelare1 + 's tur')
      if spelare%2 == 1:
        print(spelare2 +'s tur')
      guess = input('Gissa mellan 0 - ' + y+": ")
      if guess == num:
        print('Rätt nummer: ' + guess)
        if spelare%2 == 0:
          print(spelare1, "vann!")
          break
        if spelare%2 == 1:
          print(spelare2, "vann!")
          break
      elif guess == "haks":
        print(num)
      elif guess < num:
        print('Högre än ' + guess)
        spelare = spelare+1
      elif guess > num:
        print('Lägre än ' + guess)
        spelare = spelare+1

I can't find any logic in this and already spent to much time on trying to fix it. Any help is much appreciated and if there are any questions about the code I'll happily answer them.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Korven13
  • 3
  • 1

1 Answers1

0

The number of digits doesn't matter

There's a difference between inequality comparisons on strings (like you're doing) and on actual numbers.

When used on strings, it's comparing alphabetically, not numerically

You should convert all inputs to numbers, not compare them as strings (the default return type of input function). Similarly, don't cast your random digits to strings

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245