0

I'm writing this script for an assignment so I'd appriciate being talked through it rather than simply being handed an answer. Basically I'm trying to convert feet to meters, meters to feet, and provide a sum of the total converted distance in both at the end. Without the [] indexes, It was working perfectly. The new part I've only just added and am struggling with is the [] indexes, and to be honest I'm having a hell of a time groking how they work. Anyways heres the code:

MAX = 256
switch = ""
feet = [0.0] * MAX
meters = [0.0] * MAX
feetpermeter = 3.28084
metersperfoot = 0.3048
sum_meters = 0
sum_feet = 0

def main():
    selector()


def selector():
    while True:
        print("Is your measurement in meters or feet?")
        switch = input("Or would you like to quit?")
        if (switch == "feet" or switch == "Feet"):
            ftm()
        elif (switch == "meters" or switch == "Meters"):
            mtf()
        elif (switch == "quit" or switch == "Quit"):
            end()
        else:
            print("Sorry, that wasn't one of the options.")
            print("Lets try that again")


def mtf():
    try:
        meters[sum_meters] = float(input("Enter the number of meters. "))
        feet[sum_feet] = meters * feetpermeter
        print("That is", feet, "feet.")
        main()
    except:
        print("Sorry, I didn't quite get that, lets try again.")
        mtf()


def ftm():
    try:
        feet[sum_feet] = float(input("Enter the number of feet. "))
        meters[sum_meters] = feet * metersperfoot
        print("That is", meters, "meters.")
        main()
    except:
        print("Sorry, I didn't quite get that, lets try again.")
        ftm()


def end():
    while True:
        switch2 = input("Are you sure you want to quit(y/n)?")
        if (switch2 == "y" or switch2 == "Y"):
            print("you converted a total of ", sum(feet), "feet")
            print("And", sum(meters), "meters.")
            print("Bye!")
            exit()
        elif (switch2 == "n" or switch2 == "N"):
            print("Ok, let's try that again.")
            main()
        else:
            print("Sorry, that wasn't one of the options.")
            print("Lets try that again")


main()

I did try having sum_feet + 1 and sum_meters + 1 after each result but that hadnt worked either.

2 Answers 2

0

You are not using the indexing in a proper way. For instance , look at the comments on your existing code:

def mtf():
    try:
        # Error 1. You stored all the inputs to index 0, as sum_meters is 0 always and its not incremented
        # So, all the inputs are not recorded, only last one gets in index 0
        meters[sum_meters] = float(input("Enter the number of meters. "))

        # Error 2: You multiplied the whole list against the conversion parameter.
        # Instead, you should multiply the value at current index
        feet[sum_feet] = meters * feetpermeter

        # This will print the whole list. Again use the current index here
        print("That is", feet, "feet.")
        main()
    except:
        print("Sorry, I didn't quite get that, lets try again.")
        mtf()

A fixed version of your function will be like:

def mtf():
    try:
        # For modifying global variables in a function scope
        global sum_meters
        global sum_feet
        meters[sum_meters] = float(input("Enter the number of meters. "))
        feet[sum_feet] = meters[sum_meters] * feetpermeter
        print(f"That is {feet[sum_feet]} feet.")
        sum_meters += 1
        sum_feet += 1
        main()
    except:
        print("Sorry, I didn't quite get that, lets try again.")
        mtf()

This fixes stands true for your other functions as well. I also thought to give you another piece of advice, that you can use a good object oriented approach for such problems, which makes it simpler to implement. You can learn a lot about that, then you will feel more confident.

As an example, see the below code - which does almost same, but in a more crisp way.

class Converter:
    FEET_PER_METER = 3.28084
    METERS_PER_FOOT = 0.3048

    def __init__(self):
        self.feet_store = []
        self.meter_store = []
        self.curr_index = 0

        self.menu_handlers = {
            "feet": self.feet_to_meter,
            "meters": self.meter_to_feet,
            "quit": self.summary
        }

    def run_selection(self, selected):
        #
        selected = str.lower(selected)
        if selected in self.menu_handlers:
            # call the relevant function
            return self.menu_handlers.get(selected)()
        return False

    def meter_to_feet(self):
        meters_in = float(input("Enter the number of meters."))
        to_feet = meters_in * self.FEET_PER_METER
        self.meter_store.append(meters_in)
        self.feet_store.append(to_feet)
        print(f"In Feet : {to_feet}")
        return to_feet

    def feet_to_meter(self):
        feet_in = float(input("Enter the number of feet."))
        to_meters = feet_in * self.METERS_PER_FOOT
        self.feet_store.append(feet_in)
        self.meter_store.append(to_meters)
        print(f"In Meters : {to_meters}")
        return to_meters

    def summary(self):
        confirm = input("Are you sure you want to quit(y/n)?")
        if confirm in ["y", "Y"]:
            print("you converted a total of ", sum(self.feet_store), "feet")
            print("And", sum(self.meter_store), "meters.")
            print("Bye!")
            exit()
        else:
            return False


def main():
    converter = Converter()
    while True:
        choice = input("Is your measurement in meters or feet (meters/feet/quit)?")
        converter.run_selection(choice)

I hope this gives you better insights.

3
  • This was VERY helpful! I appreciate the time you took to help me out! Commented Nov 24, 2021 at 20:34
  • You can accept and upvote an answer, if you found it helpful
    – Kris
    Commented Nov 25, 2021 at 5:44
  • hey kris, I upvoted both answers but it said something about me not having the reputation neccesary. Commented Nov 26, 2021 at 21:07
0

So theres two problems with what you've tried to do here, in the lines:

meters[sum_meters] = float(input("Enter the number of meters. "))
feet[sum_feet] = meters * feetpermeter

meters * feetpermeter is multiplying an array by a number, you need to do meters[sum_meters] to get the number you want. Secondly as you said, you need to increment sum_meters each time, but because you're inside a function you will need to declare the variable as a global before you change it. Also since sum_meters and sum_feet are always going to be equal, you can just use a single variable to keep track of this:

def mtf():
    try:
        global index
        meters[index] = float(input("Enter the number of meters. "))
        feet[index] = meters[index] * feetpermeter
        index += 1
        print("That is", feet, "feet.")
        main()
    except:
        print("Sorry, I didn't quite get that, lets try again.")
        mtf()


def ftm():
    try:
        global index
        feet[index] = float(input("Enter the number of feet. "))
        meters[index] = feet * metersperfoot
        index += 1
        print("That is", meters, "meters.")
        main()
    except:
        print("Sorry, I didn't quite get that, lets try again.")
        ftm()

I would also go a little further and say that the use of lists is unnecessary for this problem, you could simply have two numbers, total_meters and total_feet and add the values as you go. This would take less memory and also remove the arbitrary limit of 256 goes that has been imposed. So I would do:

import sys

MAX = 256
switch = ""
total_feet = 0
total_meters = 0
feetpermeter = 3.28084
metersperfoot = 0.3048
sum_meters = 0
sum_feet = 0
index = 0


def main():
    selector()


def selector():
    while True:
        print("Is your measurement in meters or feet?")
        switch = input("Or would you like to quit?")
        if switch == "feet" or switch == "Feet":
            ftm()
        elif switch == "meters" or switch == "Meters":
            mtf()
        elif switch == "quit" or switch == "Quit":
            end()
            sys.exit(0)
        else:
            print("Sorry, that wasn't one of the options.")
            print("Lets try that again")


def mtf():
    try:
        global total_feet
        global total_meters
        meters = float(input("Enter the number of meters. "))
        feet = meters * feetpermeter
        total_meters += meters
        total_feet += feet
        print("That is", feet, "feet.")
        main()
    except Exception as e:
        print(e)
        print("Sorry, I didn't quite get that, lets try again.")
        mtf()


def ftm():
    try:
        global total_feet
        global total_meters
        feet = float(input("Enter the number of feet. "))
        meters = feet * metersperfoot
        total_meters += meters
        total_feet += feet
        print("That is", meters, "meters.")
        main()
    except Exception as e:
        print(e)
        print("Sorry, I didn't quite get that, lets try again.")
        ftm()


def end():
    while True:
        switch2 = input("Are you sure you want to quit(y/n)?")
        if switch2 == "y" or switch2 == "Y":
            print("you converted a total of ", total_feet, "feet")
            print("And", total_meters, "meters.")
            print("Bye!")
            exit()
        elif switch2 == "n" or switch2 == "N":
            print("Ok, let's try that again.")
            main()
        else:
            print("Sorry, that wasn't one of the options.")
            print("Lets try that again")


main()

1
  • I'm sure there's a lot that's unnecessary. This code has been slowly added to each week during the course with specific goal and requirements. This week is the lists. That said this post was incredibly helpful and I now understand part of how these function that I was not getting before. Thank you so much. Commented Nov 24, 2021 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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