1

I have a problem with my code.

My code is a beginner number guesser. The code is supposed to write an error when the user types a letter when.

I first thought to convert usrin_guess to an integer and then say "is it a string or integer" but I realized that couldn't work. Then I wrote this... In my head should it work but it makes a failure at if int(usrin_guess) > uo_rand_num: when I write a letter.

def rand_num(num):
    return random.randint(1, num) # Making a random number between the amount of number input and 1

uo_rand_num = rand_num(amount_of_numbers)

while int(usrin_guess) != uo_rand_num:
    
    usrin_guess = input("Enter a number between " + "1" + " and " + usrin_amount_of_numbers + " ") 
    
    try:
        val = int(usrin_guess)  
    except ValueError:
        val_input == False


    if val_input == True:
        if int(usrin_guess) > uo_rand_num:
            print("The number is lower than " + usrin_guess)
        elif int(usrin_guess) < uo_rand_num: 
            print("The number is higer than " + usrin_guess)
        elif int(usrin_guess) == uo_rand_num:
            answer = True

        usr_guesses += 1
    else:
        print("Please don't enter a character")
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 3
    There is many errors in that code , `amount_of_numbers, usrin_amount_of_numbers, val_input, usr_guesses` are not defined – azro Nov 20 '20 at 22:08
  • Maybe you could take a look at this answer and see if any of the solutions there would work for you: https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – Random Davis Nov 20 '20 at 22:10
  • Show the full traceback of the error as properly formatted text in the question. – Michael Butscher Nov 20 '20 at 22:11
  • "make a failure" is not a very clear description of whatever it is that you are observing. – khelwood Nov 20 '20 at 22:13
  • I would recommend reading https://ericlippert.com/2014/03/05/how-to-debug-small-programs/. – AMC Nov 20 '20 at 22:20

3 Answers3

1

Great attempt, it might help if you created a helper function like get_int_input to handle all the validation and utilized f-strings for string interpolation:

import random


def get_int_input(prompt: str, min_num: int, max_num: int) -> int:
    num = -1
    while True:
        try:
            num = int(input(prompt=prompt))
            if min_num <= num <= max_num:
                break
            print(f'''Error: Integer outside of the allowed range, \
[{min_num}, {max_num}], try again...''')
        except ValueError:
            print('Error: Enter an integer, try again...')
    return num


def rand_num(min_num: int, max_num: int) -> int:
    return random.randint(a=min_num, b=max_num)


def guessing_game() -> None:
    min_num, max_num = 1, 10
    num_to_guess = rand_num(min_num=min_num, max_num=max_num)
    attempts = 0
    user_guess = -1
    while user_guess != num_to_guess:
        attempts += 1
        user_guess = get_int_input(
            prompt=
            f'Enter a number between {min_num} and {max_num} inclusive: ',
            min_num=min_num,
            max_num=max_num)
        if user_guess < num_to_guess:
            print(f'The number is higher than {user_guess}')
        elif user_guess > num_to_guess:
            print(f'The number is less than {user_guess}')
    attempt_or_attempts = 'attempt' if attempts == 1 else 'attempts'
    print(
        f'Congrats! You guessed the number in {attempts} {attempt_or_attempts}!'
    )


def main() -> None:
    guessing_game()


if __name__ == '__main__':
    main()

Example Usage:

Enter a number between 1 and 10 inclusive: 5
The number is higher than 5
Enter a number between 1 and 10 inclusive: 11
Error: Integer outside of the allowed range, [1, 10], try again...
Enter a number between 1 and 10 inclusive: 7
The number is higher than 7
Enter a number between 1 and 10 inclusive: 9
The number is higher than 9
Enter a number between 1 and 10 inclusive: 10
Congrats! You guessed the number in 4 attempts!

Try it out here.

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
0

It is better to use a while True loop, and break out of the loop when the condition is met. That way, you won't have to write the input statement twice.

You can use a formatted string instead of concatenations on your strings.

Instead of defining a variable to detect whether an error occured, you can directly put the block of code into the try and except blocks:

def rand_num(num):
    return random.randint(1, num) # Making a random number between the amount of number input and 1

uo_rand_num = rand_num(amount_of_numbers)
usrin_guess = 0

while True:
    usrin_guess = input(f"Enter a number between 1 and {usrin_amount_of_numbers} ")
    if int(usrin_guess) == uo_rand_num:
        break
    try:
        val = int(usrin_guess)
        if int(usrin_guess) > uo_rand_num:
            print("The number is lower than " + usrin_guess)
        elif int(usrin_guess) < uo_rand_num: 
            print("The number is higer than " + usrin_guess)
        elif int(usrin_guess) == uo_rand_num:
            answer = True
        usr_guesses += 1
    except ValueError:
        print("Please don't enter a character")
Red
  • 26,798
  • 7
  • 36
  • 58
0

Try converting it into its ASCII Value.

You can use the ord() function to do get the ASCII value. Each letter has its own ASCII value, for A it's 065 and that of Z is 090.

So in order to check if the input is a character or not just check if the ASCII value lies in between that range.ASCII TABLE: http://sticksandstones.kstrom.com/appen.html

Red
  • 26,798
  • 7
  • 36
  • 58
Sreeram M
  • 140
  • 10