Python Method Practice

Asked 2 years ago, Updated 2 years ago, 19 views

It's a special method practice lecture.

I wonder why None comes out and the weight figure is walk -0.1 Eat+0.1, and I also want to know the decimal point after that.

I think I heard the last decimal point in the previous lecture, but I don't remember well, so I asked you one more time...

python

2022-09-22 21:37

2 Answers

"None" is the return value of the function you tried to print. If the return command statement is not used in the function, return None is implicitly added to the end of the function.

And the output of 68.7 - 0.1 as 68.6000000000000001 is a basic property of binary floating-point. It's not a Python bug, it's not a bug in your code. All languages that support floating-point operations will have the same results^

^


2022-09-22 21:37

class Human():

    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

    def __str__(self):
        return "{} (weight {})kg)".format(self.name, self.weight)

    def eat(self):
        self.weight += 0.1
        print("{} ate it, so {}You've reached kg."format(self.name, self.weight))

    def walk(self):
        self.weight -= 0.1
        print("{} on foot{}"You've reached kg."format(self.name, self.weight))

# Make person an instance of the Human class with a name and weight below.
person = Human ("Haha", 68.7)
print(person)
print(person.walk())
print(person.eat())
print(person.walk())

The return value is included in the function that makes it a string, so should I give a return value to walk and eat? I don't really understand this either.)


2022-09-22 21:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.