Python Forum
Return giving incorrect value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Return giving incorrect value
#1
Part of a recent assignment was to create a conversion program using functions. This week, we have been asked to modify it and create value-returning functions. As my program is written, if the conversions occur in each individual program, it works just fine. When I use the return value, however, it will return the first value entered even if it is considered an "invalid" entry (usually negative numbers) even after other values are entered afterward. For example, if I enter -1 for miles and it prompts for a valid number, and then I enter 1, it returns the value as -1 regardless. Everything else seems to be working fine. I've tried putting return (value) in different spots but none of that has seemed to help. I've also tried googling my issue, to no avail. Any guidance would be greatly appreciated.
#conversion factors
MILES_TO_KM = 1.6
GALLONS_TO_LITERS = 3.9
POUNDS_TO_KG = .45
INCHES_TO_CM = 2.54

#main conversion function
def main():
    miles = int(input('Enter the number of miles: '))
    miles_to_kms(miles)
    fahrenheit = int(input('Enter the degrees in Fahrenheit: '))
    fahrenheit_to_celsius(fahrenheit)
    gallons = int(input('Enter the number of gallons: '))
    gallons_to_liters(gallons)
    pounds = int(input('Enter the number of pounds: '))
    pounds_to_kgs(pounds)
    inches = int(input('Enter the number of inches: '))
    inches_to_cms(inches)

    kilometers = miles * MILES_TO_KM
    print(miles, 'mile(s) is equal to', kilometers, 'kilometers.')

    celsius = ((fahrenheit-32)*5/9)
    print(fahrenheit, 'degree(s) Fahrenheit is equal to', celsius, 'degree(s) Celsius.')

    kilograms = pounds * POUNDS_TO_KG
    print(pounds, 'pounds is equal to', kilograms, 'kilograms.')

    liters = gallons * GALLONS_TO_LITERS
    print(gallons, 'gallon(s) is equal to', liters, 'liter(s).')

    centimeters = inches * INCHES_TO_CM
    print(inches, 'inch(es) is equal to', centimeters, 'centimeter(s).')

#define conversion for miles
def miles_to_kms(miles):
    attempts = 0.0
    attempts += 1
    while miles < 0 and attempts <=3:
        miles = int(input('Enter a valid number of miles: '))
        attempts += 1

    if attempts >3 and miles <0:
        print ('Too many invalid entries submitted.')
        exit()
    return miles


#define conversion for fahrenheit
def fahrenheit_to_celsius(fahrenheit):
    attempts = 0.0
    attempts += 1
    while fahrenheit >1000:
        while attempts <= 3:
            fahrenheit = int(input('Enter a valid temperature: '))
            attempts += 1
            
    if attempts >3 and fahrenheit >1000:
        print ('Too many invalid entries submitted.')
        exit()
    return fahrenheit

#define conversion for gallons
def gallons_to_liters(gallons):
    attempts = 0.0
    attempts += 1
    while gallons < 0 and attempts <= 3:
        gallons = int(input('Enter a valid number of gallons: '))
        attempts += 1

    if attempts > 3 and gallons < 0:
        print ('Too many invalid entries submitted.')
        exit()
    return gallons

#define conversion for pounds
def pounds_to_kgs(pounds):
    attempts = 0.0
    attempts += 1
    while pounds < 0 and attempts <=3:
        pounds = int(input('Enter a valid number of pounds: '))
        attempts += 1
      
        if attempts > 3 and pounds < 0:
            print ('Too many invalid entries submitted.')
            exit()
    return pounds

#define conversion for inches
def inches_to_cms(inches):
    attempts = 0.0
    attempts += 1
    while inches <0 and attempts <=3:
        inches = int(input('Enter a valid number of inches: '))
        attempts += 1
      
        if attempts > 3 and inches < 0:
            print ('Too many invalid entries submitted.')
            exit()
    return inches
    
main()
Reply
#2
your logic is flawed.
here's an example of how 'miles_to_kms(miles)' should work:

in main, move:
miles = int(input('Enter the number of miles: '))
to the miles_to_kms function. change the name of this function to get_miles
call from main like:
# in main()
miles = get_miles()
new get_miles function (replaces miles to kms)
def get_miles():
    attempts = 0.0
    attempts += 1
    miles = -1 # initialize miles

    while True:
        if attempts >3:
            print ('Too many invalid entries submitted.')
            break
        miles = int(input('Enter the number of miles: '))
        if  miles < 0:
            print('Invalid number of miles, try again')
            attempts += 1
            continue
        break
    return miles
 
print(get_miles())  
results:
Output:
Enter the number of miles: -2 Invalid number of miles, try again Enter the number of miles: -1 Invalid number of miles, try again Enter the number of miles: 4 4
Reply
#3
Thank you so much! I knew my logic was wrong somewhere, I just could not catch it. I really appreciate it.
Reply
#4
(Oct-18-2018, 05:30 PM)Larz60+ Wrote: new get_miles function (replaces miles to kms)
def get_miles():
    attempts = 0.0
    attempts += 1
    miles = -1 # initialize miles

    while True:
        if attempts >3:
            print ('Too many invalid entries submitted.')
            break
        miles = int(input('Enter the number of miles: '))
        if  miles < 0:
            print('Invalid number of miles, try again')
            attempts += 1
            continue
        break
    return miles
 
print(get_miles())  

There are some issues in this code:

It's not necessary to initialize miles.
After 3 invalid entries the function returns the last invalid number.
int(input()) without exceptions is very dangerous.

Maybe a better solution:
def get_miles(attempts_allowed=3):
    attempts = 0
    
    while attempts < attempts_allowed:
        try:
            miles = int(input('Enter the number of miles: '))
            if miles >= 0:
                return miles
        except ValueError:
            pass
        print('Invalid number of miles, try again.')
        attempts += 1
        continue
    print('Too many invalid entries submitted.')
    return None
  
print(get_miles())  
Reply
#5
(Oct-24-2018, 09:16 PM)LeSchakal Wrote: int(input()) without exceptions is very dangerous.
We must have different opinions on the definition of very.
Reply
#6
(Oct-24-2018, 09:17 PM)nilamo Wrote: We must have different opinions on the definition of very.

I thought it was better to count a non-int as an invalid entry then to let the program crash.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I am getting an incorrect average, and not sure why? What's wrong with my code? shirleylam852 8 4,594 Nov-20-2020, 05:32 AM
Last Post: deanhystad
  Incorrect code janek30 11 8,324 May-09-2017, 10:06 AM
Last Post: janek30
  Writing incorrect passwords to a file till its correct garth 2 4,898 Feb-10-2017, 11:41 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