Python Forum
Imported function causes prompt repetition
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Imported function causes prompt repetition
#1
I have an assignment to prompt for three numbers, then print the largest, smallest, and average of the numbers. I'm to allow floating-point numbers, so I'm importing a module to accommodate that.

Here's the code I'm using to solicit the numbers:
from pcinput import getFloat
first_number = getFloat( "First number: " )
second_number = getFloat( "Second number: " )
third_number = getFloat( "Third number: " )
When I run the script, there's a prompt for the first number. When the number is provided, the prompt for the first number repeats, instead of the prompt for the second number. Typing a string of letters shows the error "That is not a number -- please try again", but typing a number shows the same prompt again. (I also can't escape from the repetition, and I have to restart PowerShell to get out of the program, but that's another problem.)

Here's the code for the getFloat function:
def getFloat( prompt ):
    while True:
        try:
            num = float( input( prompt ) )
        except ValueError:
            print( "That is not a number -- please try again" )
            continue
            return num

I've tried to use the getFloat function in other scripts as well, but the same problem occurs, so I suspect there's something wrong with the getFloat function.

I'm running Python 3.7. The script is in Windows PowerShell.
Reply
#2
Looks to me like the last line of getFloat should be dedented / moved to the try-block.
Reply
#3
Thanks for your quick response, micseydel. Detenting the last line repaired the problem, and all is running properly now.

The corrected function is

def getFloat( prompt ):
    while True:
        try:
            num = float( input( prompt ) )
        except ValueError:
            print( "That is not a number -- please try again" )
            continue
        return num
Reply
#4
I believe that more traditional way is micseydel other suggestion (more concise):

def getFloat(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print('That is not a number -- please try again')
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


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to make the function to prompt the user repeatedly till he enters a no sbabu 3 2,411 Mar-26-2020, 10:04 PM
Last Post: Blackdog31
  Finding repetition in string student8 4 5,046 Oct-15-2017, 07:26 PM
Last Post: student8

Forum Jump:

User Panel Messages

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