【发布时间】:2015-07-18 22:13:11
【问题描述】:
代码如下:
# Critter Caretaker
# A virtual pet to care for
class Critter(object):
"""A virtual pet"""
def __init__(self, name, hunger = 0, boredom = 0):
self.name = name
self.hunger = hunger
self.boredom = boredom
def __pass_time(self):
self.hunger += 1
self.boredom += 1
@property
def mood(self):
unhappiness = self.hunger + self.boredom
if unhappiness < 5:
m = "happy"
elif 5 <= unhappiness <= 10:
m = "okay"
elif 11 <= unhappiness <= 15:
m = "frustrated"
else:
m = "mad"
return m
def talk(self):
print("I'm", self.name, "and I feel", self.mood, "now.\n")
self.__pass_time()
def eat(self, food = 4):
print("Brrupp. Thank you.")
self.hunger -= food
if self.hunger < 0:
self.hunger = 0
self.__pass_time()
def play(self, fun = 4):
print("Whee!")
self.boredom -= fun
if self.boredom < 0:
self.boredom = 0
self.__pass_time()
crit_name = input("What do you want to name your critter?: ")
crit = Critter(crit_name)
choice = None
while choice != "0":
print \
("""
Critter Caretaker
0 - Quit
1 - Listen
2 - Feed your critter
3 - Play with your critter
""")
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Good-bye.")
# listen to your critter
elif choice == "1":
crit.talk()
# feed your critter
elif choice == "2":
crit.eat()
# play with your critter
elif choice == "3":
crit.play()
# some unknown choice
else:
print("\nSorry, but", choice, "isn't a valid choice.")
input("\n\nPress the enter key to exit.")
当我在 IDLE 中运行它时,它工作得很好,但是当我保存文件并双击文件时,它不能正常运行。例如,当我从“0” - “3”中选择一个有效选项时,它会打印 - “不是一个有效的选择”。但即使它不是一个有效的选择,它也应该打印“对不起,但是 - 不是一个有效的选择”。
对不起我的英语。如果您对我的英语感到困惑,请告诉我。
顺便说一句,我目前正在从 Michael Dawson 的一本名为“Python Programming for Absolute Beginner”的书中学习 Python。我应该读完这本书还是应该找到另一种学习 Python 的方法?
【问题讨论】:
-
你是不是不小心把 Python 2 和 Python 3 搞混了?
-
把
print('choice type', type(choice)放在input("Choice: ")之后的行。如果choice是一个整数,它总是会比较不等于字符串,所以你所有的 if elif 表达式都是 False -
@msw 假设程序是为 python 3 设计的,
input()将默认为字符串 -
@user3636636 当然,但与其猜测他看到的是哪个解释器,不如直接询问更准确。从 IDE 迁移到命令行时,人们经常会遇到这种版本偏差。是的,sys.version 是获取信息的另一种方式,我只是认为询问数据本身更简单。
标签: python