Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
repeating a user_input
#11
Don't do this
while user_input != RNumber:
    # To get here, user_input must be greater than or less than RNumber.  It cannot equal RNumber
    if user_input > RNumber:
        user_input = int(input("choose a lower number: \n"))   # <-- one of these will run
    elif user_input < RNumber:                                 #   |
        user_input = int(input("choose a higher number: \n"))  # <-
    elif user_input == RNumber:                                 
        print("the number you chose is correct (", RNumber, ")")  # <- This will never run
You could do this (but you shouldn't)
while user_input != RNumber:
    if user_input > RNumber:
        user_input = int(input("choose a lower number: \n"))
    elif user_input < RNumber:
        user_input = int(input("choose a higher number: \n"))
    # Make this if statement look at the new value of user_input.  Still doesn't
    # work if the first guess is correct,
    if user_input == RNumber:
        print("the number you chose is correct (", RNumber, ")")
You should do this:
while user_input != RNumber:
    if user_input > RNumber:
        user_input = int(input("choose a lower number: \n"))
    elif user_input < RNumber:
        user_input = int(input("choose a higher number: \n"))
# Only way to get here is to guess correctly.
print("the number you chose is correct (", RNumber, ")")
The only way to exit the loop is to guess the correct number. If the loop is done, the user guessed the number. No need for any check.

if statements are bad. They make code difficult to understand and they make programs run slow. But if statements are a necessary evil. Use them when needed. Avoid using when you don't.
Reply
#12
So, another way would be:
import random

RNumber = random.randint(1, 10)
user_input = 0
while user_input != RNumber:
    user_input = int(input("please guess a number between 1 and 10: "))
    if user_input > RNumber:
        print("choose a lower number: \n")
    elif user_input < RNumber:
        print("choose a higher number: \n")
print("the number you chose is correct (", RNumber, ")")
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#13
(Oct-25-2022, 04:25 PM)deanhystad Wrote: About the only while I use in Python is "while True".
import random

rnumber = random.randint(0, 10)
prompt = "Enter a number from 0 to 10: "
while True:
    unumber = int(input(prompt))
    if unumber > rnumber:
        prompt = "Guess a lower number: "
    elif unumber < rnumber:
        prompt = "Guess a higher number: "
    else:
        break
print("That's it!")
This does the same thing
import random

rnumber = random.randint(0, 10)
unumber = int(input("Enter a number from 0 to 10: ")
while unumber != rnumber:
    if unumber > rnumber:
        unumber = int(input("Guess a lower number: "))
    elif unumber < rnumber:
        unumber = int(input("Guess a higher number: "))
print("That's it!")

while what is true ? in this instance... (sorry for not understanding/knowing this basic stuff)
Reply
#14
rob101's example uses an expression in the while statement "while user_input != RNumber". The expression "input != RNumber" evaluates to the Python object True or False. If the result of the expression is True, the while loop continues to run. If the result is False, the loop stops.

My example uses "while True:". This skips evaluating an expression to get True or False, but otherwise works exactly like rob101's example. If the result is True, the while loop continues to run. If the result is False, the loop stops. True will always be True, so the loop runs forever.

Actually, that's not really true. My while loop loops forever because True is always truthful. Things can be "truthful" without being the object True. In Python, 1 is truthful and 0 is not. A list containing values is truthful, but an empty list is not. Python lets you use things other than True and False as the conditionals for "if" or "while" statements.

Most things in Python are truthful. It is easier to list the things that are not truthful.
1. False is obviously not truthful.
2. Comparisons and Boolean expressions that evaluate to False are not truthful.
3. None is not truthful.
4. The number zero is not truthful.
5. Empty collections are not truthful (lists, tuples, sets, dictionaries, bytearrays).
6. Zero length strings and bytes are not truthful.
7. Classes that override the __bool__() method to return False are not truthful.

So, back to the question about "while True:". Why make a loop that loops forever? Won't the program just hang?

"Forever" loops are actually very common in Python. Using a forever loop almost always indicates that the programmer wants to loop, but want's more control over how loop exits. Look at the body of a forever loop and you will find a "break" statement or a "return statement" (if the loop is inside a function). These exit the loop instead of testing the condition at the top.

My previous example:
import random
 
rnumber = random.randint(0, 10)
prompt = "Enter a number from 0 to 10: "
while True:  # I cannot check if it is time to exit the loop because no value is entered yet
    # I only want to do the str->int conversion in one place.  I might wrap an exception handler
    # around the conversion to prevent crashing the program if a non-numeric string is entered.
    unumber = int(input(prompt))
    if unumber > rnumber:
        prompt = "Guess a lower number: "
    elif unumber < rnumber:
        prompt = "Guess a higher number: "
    else:
        break   # This is where I exit the loop
print("That's it!")
Reply
#15
One use of this technique is to validate some user input.

As an example, I have a script that reads a CSV file and have an option to filter the results by month number:

months = ('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12')
filterMonth = "n/a"
while filterMonth == "n/a":
    filterMonth = input("Month (01 to 12): ")
    if filterMonth and filterMonth not in months:
        filterMonth = "n/a"
# at this point the filter is valid and the script can continue
So, if nothing is entered, no filter is applied, otherwise the filter is used.

if filterMonth:
    # do this
else:
    # do this
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#16
Just because it can be done: ask question until correct quess. For message use indexing and fact that booleans are subclass of integers (False 0, True 1).

import random

num = random.randint(0, 10)

prompt = "Guess number from 0 to 10: "

while (answer := int(input(prompt))) != num:
    print(f"Guess a {('lower', 'higher')[answer<num]} number")

print('Thats it!')
Of course this code (and any other in this thread) will fail spectacularly if user enters something which is not convertible to integer.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#17
Anyone can get it right if you use endless looping!

That must be curtailed!

def myApp():
    import random

    rNum = random.randint(1, 20)
    #rNum = 5
    hint = len(str(rNum))
    
    def tooBig(num):
        print('Number is too big!')
        anum = input('Guess again Dummkopf ... ')
        return int(anum)

    def tooSmall(num):
        print('Number is too small!')
        anum = input('Guess again Dummkopf ... ')
        return int(anum)

    print('Guess the random number!')
    print('The random number is', len(str(rNum)), 'long.')
    print('The number is', hint, 'digit(s) long.')

    # first guess
    anum = int(input('Guess what the random number is! Enter your guess here ... '))
    count = 1
    # could give them more guesses or better hints for longer numbers
    for i in range(5, 0, -1):
        print('You have', i, 'guesses left')    
        if anum == rNum:
            print(f'Well done, you got it in', count, 'guess(es)!')
            break
        if anum < rNum:
            anum = tooSmall(anum)
        elif anum > rNum:
            anum = tooBig(anum)
        count +=1

    # if loop ended unsuccessfully
    if anum != rNum:
        print('Loser!')  
Reply
#18
thank you guys for the explanations !
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why is 2/3 not just .666 repeating? DocFro 4 848 Dec-12-2023, 09:09 AM
Last Post: buran
  if else repeating Frankduc 12 2,819 Jul-14-2022, 12:40 PM
Last Post: Frankduc
  factorial, repeating Aldiyar 4 2,937 Sep-01-2020, 05:22 PM
Last Post: DPaul
  Repeating equations Tbot100 2 3,368 May-29-2019, 02:38 AM
Last Post: heiner55
  repeating for loop Kaldesyvon 5 3,985 Dec-06-2018, 08:00 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020