我有两组代码,我刚刚开始学习Python以满足我的需求: 有两个不同的IDE(PyCharm Comm Edn)和PyDev,已经尝试过两者,
第二组成功运行,但是第一组没有成功,比较了两组代码,除了字符串引号和缩进之外,它们没有多大区别。
class Car:
def __init__(self):
self.speed = 0
self.odometer = 0
self.time = 0
def say_state(self):
print("I'm going {} kph".format(self.speed))
def accelerate(self):
self.speed += 5
def brake(self):
self.speed -= 5
def step(self):
self.odometer += self.speed
self.time += 1
def average_speed(self):
return self.odometer / self.time
if __name__ == '__main__':
my_car = Car()
print("I am a Car")
while True:
action = input("What Should I Do"
"[A]ccelerate, [B]rake show [O]dometer"
"Or Show average [S]peed").upper()
if action not in "ABOS" or len(action) != 1:
print("I DOnt Know how to do that")
continue
if action == 'A':
my_car.accelerate()
elif action == 'B':
my_car.brake()
elif action == 'O':
print("My Car has driven {} Kilometers".format(my_car.odometer))
elif action == 'S':
print("The Car average speed was {} Kilometers".format(my_car.average_speed()))
my_car.step()
my_car.say_state()
class Car:
def __init__(self):
self.speed = 0
self.odometer = 0
self.time = 0
def say_state(self):
print("I'm going {} kph!".format(self.speed))
def accelerate(self):
self.speed += 5
def brake(self):
self.speed -= 5
def step(self):
self.odometer += self.speed
self.time += 1
def average_speed(self):
return self.odometer / self.time
if __name__ == '__main__':
my_car = Car()
print("I'm a car!")
while True:
action = input("What should I do? [A]ccelerate, [B]rake, "
"show [O]dometer, or show average [S]peed?").upper()
if action not in "ABOS" or len(action) != 1:
print("I don't know how to do that")
continue
if action == 'A':
my_car.accelerate()
elif action == 'B':
my_car.brake()
elif action == 'O':
print("The car has driven {} kilometers".format(my_car.odometer))
elif action == 'S':
print("The car's average speed was {} kph".format(my_car.average_speed()))
my_car.step()
my_car.say_state()
尝试了所有可能的缩进工作。 对问题中的任何错误道歉!这里stackoverflow中的代码缩进也是不同的。
还通过选择整个代码尝试了IDE的自动缩进和缩进现在我可以忽略集合1并且使用集合2离开,但是我想知道的是,为什么在地球上,当集合在词法上是正确的时,第1集给出了错误。
错误集1:
E:\Learn_Python\venv\Scripts\python.exe E:/Python_Learning_Projects/Car.py Traceback (most recent call last): File "E:/Python_Learning_Projects/Car.py", line 1, in class Car: File "E:/Python_Learning_Projects/Car.py", line 24, in Car my_car = Car() NameError: name 'Car' is not defined Process finished with exit code 1