簡體   English   中英

為什么這個 python 腳本中的索引不起作用?

[英]Why isnt the indexing in this python script working?

我正在為一項任務編寫此腳本,因此我希望通過它進行交談,而不是簡單地得到答案。 基本上我試圖將英尺轉換為米,米轉換為英尺,並在最后提供兩者的總轉換距離之和。 沒有 [] 索引,它工作得很好。 我剛剛添加並正在努力解決的新部分是 [] 索引,老實說,我正在研究它們是如何工作的。 無論如何繼承代碼:

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()

我確實嘗試在每個結果之后使用 sum_feet + 1 和 sum_meters + 1 ,但這也沒有奏效。

您沒有以正確的方式使用索引。 例如,查看現有代碼的注釋:

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()

function 的固定版本如下:

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()

此修復程序也適用於您的其他功能。 我還想給您另一條建議,您可以使用面向此類問題的良好 object 方法,這樣可以更輕松地實現。 你可以從中學到很多東西,然后你會更有信心。

作為示例,請參見下面的代碼 - 幾乎相同,但方式更清晰。

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)

我希望這能給你更好的見解。

因此,您在這里嘗試執行的操作存在兩個問題:

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

米 * 英尺每米是一個數組乘以一個數字,你需要做米[sum_meters] 來得到你想要的數字。 其次,正如您所說,您需要每次增加 sum_meters ,但是因為您在 function 中,您需要在更改之前將變量聲明為全局變量。 此外,由於 sum_meters 和 sum_feet 總是相等的,您可以只使用一個變量來跟蹤這一點:

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()

我還想進一步說 go 並說對於這個問題不需要使用列表,你可以簡單地有兩個數字,total_meters 和 total_feet,然后像 go 一樣添加值。 這將花費更少的 memory 並消除已施加的 256 次任意限制。 所以我會這樣做:

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM