5
\$\begingroup\$

I am pretty new to Python but I'm learning from classes.

I am working on a project for class and this is my code. Anyone got a better idea of a way to organize the code or put it differently so there aren't so many conditional statements?

def cm(centimeter):
    """Centimeter to Meters Converter!"""
    if centimeter == ("false"):
        print ("It looks like you input a value that wasn't a number! Try again!")
    else:
        result = round(centimeter / 100)
        print ("%d centimeters is the same as %d meters." % (centimeter, result))
def meter(meter):
    """Meter to Centimeters Converter!"""
    if meter == ("false"):
        print ("It looks like you input a value that wasn't a number! Try again!")
    else:
        result = round(meter * 100)
        print ("%d meters is the same as %d centimeters." % (meter, result))
def cent2(centin):
    """Centimeter to Inches Converter!"""
    if meter == ("false"):
        print ("It looks like you input a value that wasn't a number! Try again!")
    else:
        result = centin * 0.39
        print ("%d centimeters is the same as %d inches." % (centin, result))
def inchcm(inches):
    """Feet to Meters Converter!"""
    if inches == ("false"):
        print ("It looks like you input a value that wasn't a number! Try again!")
    else:
        result = inches / 0.39
        print ("%d inches is the same as %d centimeters." % (inches, result))
def kmmiles(km):
    """Meters to Inches Converter!"""
    if km == ("false"):
        print ("It looks like you input a value that wasn't a number! Try again!")
    else:
        result = km * 0.62137
        print ("%d km is the same as %d miles." % (km, result))
def mileskm(miles):
    """Miles to KM Converter!"""
    if miles == ("false"):
        print ("It looks like you input a value that wasn't a number! Try again!")
    else:
        result = miles / 0.62137
        print ("%d miles is the same as %d kilometers." % (miles, result))
def fer(fc):
    """Farenheight to Celcius Converter!"""
    if fc == ("false"):
        print ("It looks like you input a value that wasn't a number! Try again!")
    else:
        result = (fc - 32) * 5/9
        print ("%d farenheit is the same as %d celcius." % (fc, result))
def cel(cf):
    """Farenheight to Celcius Converter!"""
    if cf == ("false"):
        print ("It looks like you input a value that wasn't a number! Try again!")
    else:
        result = cf * 9/5 + 32
        print ("%d celcius is the same as %d farenheit." % (cf, result))
print ("Kevin's Sexy Converter!")
print("")
print("A. Length")
print("B. Temperature")
print("C. Mass")
print("")
type=input("Please choose an option: ")
if type == ("a") or type ==("A"):
    print("")
    print("1. CM to Meters")
    print("2. Meters to CM")
    print("3. CM to Inches")
    print("4. Inches to CM")
    print("5. KM to Miles")
    print("6. Miles to KM")
    print("")
    test=input("Please choose an option: ")
    if test == ("1"):
        cent=input("Centimeters: ")
        if cent.isdigit():
            cm(int(cent))
        else:
            cm("false")
    elif test == ("2"):
        meters=input("Meters: ")
        if meters.isdigit():
            meter(int(meters))
        else:
            meter("false")
    elif test == ("3"):
        centin=input("Centimeters: ")
        if centin.isdigit():
            cent2(int(centin))
        else:
            centin("false")
    elif test == ("4"):
        inches=input("Inches: ")
        if inches.isdigit():
            inchcm(int(inches))
        else:
            feeet("false")
    elif test == ("5"):
        km=input("KM: ")
        if km.isdigit():
            kmmiles(int(km))
        else:
            metersin("false")
    elif test == ("6"):
        miles=input("Miles: ")
        if miles.isdigit():
            mileskm(int(miles))
        else:
            metersin("false")
    else:
        print("You did not choose a valid option!")
elif type == ("b") or type == ("B"):
    print("")
    print("1. Farenheit to Celcius")
    print("2. Celcius to Farenheit")
    print("")
    temp=input("Please choose an option: ")
    if temp == ("1"):
        fc=input("Fahrenheit: ")
        if fc.isdigit():
            fer(int(fc))
        else:
            fc("false")
    if temp == ("2"):
        cf=input("Celsius: ")
        if cf.isdigit():
            cel(int(cf))
        else:
            cf("false")
else:
    print("You did not choose a valid option!")
\$\endgroup\$
0
5
\$\begingroup\$

To remove repetition

If you set up a list of the possible conversions:

conversions = [
    ('cm', 'meters'), 
    ('meters', 'cm'), 
    ('cm', 'inches'), 
    ('inches', 'cm'), 
    ('km', 'miles'), 
    ('miles', 'km')
]

And a dictionary of the factors required to convert each unit into metres:

meters = {
    'meters': 1.0,
    'cm': 0.01,
    'inches': 0.0254,
    'km': 1000
}

Then (e.g.) if the user asks for conversion type 3 - cm to inches - look up the conversion from the list of conversions:

convert_from, convert_to = conversions[int(user_choice) - 1]

Then to convert cm to inches, you multiply by 0.01 to get a number of metres then divide by 0.0254 to get a number of inches, which will look like this in your code:

result = original_amount * meters[convert_from] / meters[convert_to]

This will allow you to combine all of the length conversions into a single short function and remove all of the if...then... elif... repetition. You will still need a separate function for temperature.

Taking user input

In some places you tell the user to 'try again' but at this point the programme terminates. Usually you would want a while loop that repeats until the user enters a valid response:

while True:
    amount = input(convert_from + ': ')
    if amount.isdigit():
        result = float(amount) * meters[convert_from] / meters[convert_to]
        print('%s %s is the same as %d %s' % (amount, convert_from, result, convert_to))
        break
    else:
        print("It looks like you input a value that wasn't a number! Try again!")

Alternatively, it is often useful to use try...except: attempt to process the user's input, and if that causes an error, ask them to respond again:

while True:
    amount = input(convert_from + ': ')
    try:
        result = float(amount) * meters[convert_from] / meters[convert_to]
        print('%s %s is the same as %d %s' % (amount, convert_from, result, convert_to))
        break
    except ValueError:
        print("It looks like you input a value that wasn't a number! Try again!")
\$\endgroup\$
0
\$\begingroup\$

First of all i would return the data and print them and second i would create a new function for the testing

def check_if_is_digit(data_input):
    try:
        int(data_input) #or float(data_input) for int, long, float
    except ValueError:
        return False
    return True

def cm(centimeter):
    """Centimeter to Meters Converter!"""
    if check_if_is_digit(centimeter):
        result = round(centimeter / 100)
        return("%d centimeters is the same as %d meters." % (centimeter, result))

    return("It looks like you input a value that wasn't a number! Try again!")

# example
print(cm(100))
\$\endgroup\$
3
  • \$\begingroup\$ The check_if_is_digit function seems redundant - the isdigit method does more or less the same thing. \$\endgroup\$ – Stuart Jan 7 '14 at 0:54
  • \$\begingroup\$ >>> "-1".isdigit() False Thats the reason i didn't used the isdigit() \$\endgroup\$ – Giannis Papaioannou Jan 7 '14 at 7:58
  • \$\begingroup\$ Okay but it may not have been the OP's intention to allow negative values. It would make sense for temperatures but not for other units. Also, it might be easier just to build the try...except into the conversion function. \$\endgroup\$ – Stuart Jan 8 '14 at 0:29
-2
\$\begingroup\$

Instead of trying to determine if the input is a number and then looking for a special value ("false"), let Python determine if the input is a number:

def cm(centimeter):
    """Centimeter to Meters Converter!"""
    result = round(centimeter / 100)
    print ("%d centimeters is the same as %d meters." % (centimeter, result))
...
    try:
        if test == ("1"):
            cent=input("Centimeters: ")
            cm(int(cent))
        if ....
    except ValueError:
        print ("It looks like you input a value that wasn't a number! Try again!")
\$\endgroup\$
1
  • \$\begingroup\$ Thanks! I did that and it works but for some reason if I put a number that isn't defined under the try statement than it won't say what its supposed to say after the except statement. Any idea? \$\endgroup\$ – Kevin Harrison Oct 1 '13 at 23:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.