Py学习  »  Python

如何使用Python类并请求用户输入?

MrN1ce9uy • 5 年前 • 1396 次点击  

这是我第一次尝试创建和使用类。当我请求用户输入时,错误就发生了。我得到以下错误:

n1 = Arithmetic.float_input("Enter your First number: ")
TypeError: float_input() missing 1 required positional argument: 'msg'

这是我的密码。

# Define class
class Arithmetic:
    def float_input(self, msg): # Use this function for exception handling during user input
        while True:
            try:
                return float(input(msg))
            except ValueError:
                print("You must enter a number!")
            else:
            break
    def add(self, n1, n2):
        sum1 = n1 + n2
        print(n1,"+" ,n2,"=", sum1)
    def sub(self, n1, n2):
        diff = n1 - n2
        print(n1,"-",n2,"-", diff)
    def mult(self, n1, n2):
        product = n1 * n2
        print(n1,"*",n2, "=", product)
    def div(self, n1, n2):
        if n2 == 0:
            print(n1, "/",n2,"= You cannot divide by Zero")
        else:
            quotient = n1 / n2
            print(n1, "/",n2,"=", quotient)
    def allInOne(self, n1, n2):
        #Store values in dictionary (not required, just excercising dictionary skill)
        res = {"add": add(n1, n2), "sub": sub(n1, n2), "mult": mult(n1, n2), "div": div(n1, n2)}

# Declare variables. Ask user for input and use the exception handling function       
n1 = Arithmetic.float_input("Enter your First number: ")
n2 = Arithmetic.float_input("Enter your Second number: ")

我错过了什么?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51665
 
1396 次点击  
文章 [ 4 ]  |  最新文章 5 年前