簡體   English   中英

平均值程序不起作用(Python 3.4)

[英]Averages Program doesn't work (Python 3.4)

我正在嘗試制作一個平均程序,該程序在用戶要求程序計算它之前采用數字。 我正在使用一個類來提高類,我希望有人解釋為什么我編寫的代碼在您運行它並嘗試計算平均值時不起作用。

from statistics import mean

class User():
    def __init__(self):
        self.name = input("Name: ")
        self.numbers = []
        self.check_name()

    def check_name(self):
        self.ask_user()
        #adding in later

    def ask_user(self):
        asking = True
        while asking:
            try:
                self.number = int(input())
                self.numbers.append(self.number)
            except ValueError:
                if str(self.number) == "calc":
                    self.calc()
                    asking = False
                    break
                else:
                    print("Only enter numbers. ")


    def calc(self):
        avg = mean(self.numbers)
        print("Average =",str(avg))

User()

您代碼中的問題是您總是試圖將輸入字符串轉換為整數。 如果失敗,就像有人鍵入“calc”一樣,變量self.number將不會被重新定義。

如果您將調用int()移動到下一行,並刪除對str()的調用,則此代碼可以正常工作,這變得不必要:

def ask_user(self):
    asking = True
    while asking:
        try:
            self.number = input()
            self.numbers.append(int(self.number))
        except ValueError:
            if self.number == "calc":
                self.calc()
                asking = False
                break
            else:
                print("Only enter numbers. ")

每次輸入一個數字時, self.number包含一個數字。 self.number = int(input())input()返回"calc" ,語句失敗,因此self.number仍然是一個數字。 畢竟,它不能是int("calc")

暫無
暫無

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

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