TransWikia.com

Python3: How to check for a string within a while loop that expects integers

Stack Overflow Asked by Eskimo4 on November 10, 2021

in Python3: How do I check for a string within a while loop that expects integers…

Here’s my code currently: I want to replace sentinel value "0" with "quit" or "q" instead. How would I do that?

import random

highest = 10
lowest = 1
counter = 0

random_number = random.randint(lowest, highest)
# The randint function is in the random function within the random MODULE imported above.

guess = int(input(f"Guess a number between {lowest} and {highest}. Enter '0' at any time to quit: "))

while guess is not random_number:
    if guess == 0:
        print("Quitting game.")
        break
    elif guess < random_number:
        counter += 1
        guess = int(input("Guess higher: "))
    elif guess > random_number:
        counter += 1
        guess = int(input("Guess lower: "))
    if guess == random_number:
        print(f"Correct! Well done!! You got it right after {counter} guess(es)!")

I want to change the sentinel value "0" to "q / quit", but not sure how…

5 Answers

Thanks to all of you. Here is a copy of the code that completely works and is what I was looking for. The key was (like you all mentioned) to

  1. let input be a string initially
  2. check for 'q' or 'quit' immediately.
  3. Then converting guess to an int for the remaining code
  4. Let subsequent input in the if/elif statements be strings.
guess = input(f"Guess a number between {lowest} and {highest}. Enter 'quit' at any time to quit: ")

while guess is not random_number:
    if guess.casefold() == "quit" or guess.casefold() == 'q':
        print("Quitting game.")
        break
    guess = int(guess)
    if guess < random_number:
        counter += 1
        guess = input("Guess higher: ")
    elif guess > random_number:
        counter += 1
        guess = input("Guess lower: ")
    if guess == random_number:
        print(f"Correct! Well done!! You got it right after {counter} guess(es)!")

Thanks again!

Here's the same code with an "invalid input" checker that continues the loop:

guess = input(f"Guess a number between {lowest} and {highest}. Enter 'quit' at any time to quit: ")

while guess is not random_number:
    if guess.casefold() == "quit" or guess.casefold() == 'q':
        print("Quitting game.")
        break

    if guess.isnumeric():
        guess = int(guess)
        if guess < random_number:
            counter += 1
            guess = input("Guess higher: ")
        elif guess > random_number:
            counter += 1
            guess = input("Guess lower: ")
        if guess == random_number:
            print(f"Correct! Well done!! You got it right after {counter} guess(es)!")
    else:
        print("Invalid input. Try again...")
        guess = input(f"Guess a number between {lowest} and {highest}. Enter 'quit' at any time to quit: ")

Answered by Eskimo4 on November 10, 2021

Maybe try this:

import random

highest = 10
lowest = 1
counter = 0

random_number = random.randint(lowest, highest)

guess = input(f"Guess a number between {lowest} and {highest}. Enter 'quit' at any time to quit: ")

while guess is not random_number:
    if guess == "quit":
        print("Quitting game.")
        break
    guess = int(guess)

    if guess < random_number:
        counter += 1
        guess = int(input("Guess higher: "))
    elif guess > random_number:
        counter += 1
        guess = int(input("Guess lower: "))
    if guess == random_number:
        print(f"Correct! Well done!! You got it right after {counter} guess(es)!")

At first, store the input as a string, then check if it equals to 'quit'. If thats not true, convert the string into an integer and proceed normally.

I tried it out and it worked fine, but maybe there is a more elegant way of doing this.

Answered by Wanja on November 10, 2021

You can do one thing:- A way is you can take input inside the loop and check the input, with break when the user's guess matches the actual number:-

while 1:
 guess = input()
 if guess == 'q' or guess == 'quit':
  print("Quitting game")
  break
 elif int(guess) < random_numer:

and continue as the rest of your program.

Answered by Suryansu Dash on November 10, 2021

You would have to check whether the input is q / quit before converting it to an integer. With int(input(..)), you convert your input to an integer. This will fail if the user inputs a string.

...
while guess is not str(random_number):
    if guess == "q" or guess == "quit":
        print("Quitting game.")
        break
    guess = int(guess)
    # this might fail if the user did not enter a number
    if guess < random_number:
        counter += 1
        guess = input("Guess higher: ")
    elif guess > random_number:
        counter += 1
        guess = input("Guess lower: ")
    if guess == random_number:
        print(f"Correct! Well done!! You got it right after {counter} guess(es)!")

Answered by Jonas Drotleff on November 10, 2021

guess = int(in.... don't cast it in int, but string.

And then look if the string is "q" or "quit"

If not q or quit then you cast it in int : elif int(guess) < random_number:

Answered by urospet on November 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP