python代码没错但运行不出来,python写完代码怎么运行

首页 > 教育培训 > 作者:YD1662023-06-04 22:41:24

#父与子的编程之旅

#与小卡特一起学Python

#第十四课一

#终于到了对象这一章节,集前面学习的大成,尝试着一点一点的理解每行代码的意义,在大脑中模拟运算整个代码可能出现的结果。

#然后打开电脑,按照教材的代码清单,逐个字母的敲击进去。

#不积跬步无以至千里,你要默默努力,悄悄生长,然后惊艳所有人。

#加油,你是最棒的。

#代码1—创建一个对象

class Ball:

def bounce(self):

if self.direction == "down":

self.direction = "up"

myBall = Ball()

myBall.direction = "down"

myBall.color = "red"

myBall.size = "small"

print ("I just created a ball.")

print ("My ball is ",myBall.size)

print ("My ball is ",myBall.color)

print ("My ball`s direction is ", myBall.direction)

print ("Now i`m going to bounce the ball.")

print()

myBall.bounce()

print ("Now the ball`s direction is ",myBall.direction)

print()

#代码2—初始化一个对象,让对象在使用之前处于预设的状态

class Ball:

def __init__(self,color,size,direction):

self.color=color

self.size=size

self.direction=direction

def bounce(self):

if self.direction=="down":

self.direction="up"

myBall=Ball("red","small","down")

print("I just created a ball.")

print ("My ball is ",myBall.size)

print("My ball is", myBall.color)

print("My ball`s direction is ", myBall.direction)

print("Now I`m going to bounce the ball")

print()

myBall.bounce()

print ("Now the ball`s direction is", myBall.direction)

print(myBall)

print()

#代码3,—使用str()方法来改变打印对象的方式

class Ball:

def __init__(self, color, size, direction):

self.color = color

self.size = size

self.direction = direction

def __str__(self):

msg = "Hi, I`m a " self.size " " self.color " " " ball!"

return msg

myBall = Ball("red","small","down")

print (myBall)

#代码4—加热热狗,并添加配料

#学习了这么久之后,第一次编写一个有头有尾的程序,从定义类别开始,到完成配料添加

#对于变成的理解,和程序员的思想,也有了进一步的体会

#看着教材的内容,自己演练演练

#好记性不如烂笔头,看的再仔细,不如自己在键盘上多敲敲

class HotDog:

def __init__(self):

self.cooked_level = 0

self.cooked_srting = "Raw"

self.condiments = []

def __str__(self):

msg= "hot dog"

if len(self.condiments) >0:

msg= msg " with"

for i in self.condiments:

msg= msg i ", "

msg = msg.strip(", ")

msg = self.cooked_string " " msg "."

return msg

def cook(self, time):

self.cooked_level = self.cooked_level time

if self.cooked_level > 8:

self.cooked_string = "Charcoal"

elif self.cooked_level > 5:

self.cooked_string = "Well-done"

elif self.cooked_level > 3:

self.cooked_string = "Medium"

else:

self.cooked_string = "Raw"

def addCondiment (self, condiment):

self.condiments.append (condiment)

myDog = HotDog()

print(myDog)

print ("Cooking hot dog for 4 minutes...")

myDog.cook(4)

print (myDog)

print ("Cookding hot dog for 3 more minutes...")

myDog.cook(3)

print (myDog)

print ("What happens if I cook it for 10 more minutes?")

myDog.cook(10)

print (myDog)

print ("Now, I`m going to add some stuff on my hot dog.")

myDog.addCondiment ("ketchup")

myDog.addCondiment ("mustard")

print (myDog)

print ()

最后的这个代码,无法运行,提示错误,但是我和标准答案比较之后没有错误,谁能发现错在什么地方了吗?

栏目热文

文档排行

本站推荐

Copyright © 2018 - 2021 www.yd166.com., All Rights Reserved.