![](/img/trans.png)
[英]Why does my code work in IDLE but not when I save the file and double click the file
[英]why does my code works in IDLE but not when I save the file and double click the file?
这是代码:
# 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编程入门》中学习Python。 我应该读完本书还是应该找到另一种学习Python的方法?
与您在其他地方访问的IDLE安装相比,您的IDLE安装看上去好像具有不同的Python版本。
您可以做的一件事是在脚本顶部添加对版本的检查,以查看您正在运行的版本:
import sys
print(sys.version)
您可以做的另一件事是尝试使用字符串语法输入一个选项,例如"3"
,然后查看它是否有效。 如果是这样,则当您尝试从IDLE外部运行时,您正在运行的是Python 2版本。
如果要从Python 3转到Python 2,最主要的问题是input()
函数的行为。 Python 3的input
函数与Python 2中的raw_input
函数相同。
在Python 2中, input
只要是有效的Python代码,就尝试执行您输入的任何内容。 在Python 3中, input
仅将您输入的内容存储为字符串。
因此在Python 2中:
choice = input("Choice: ")
Choice: 3
print(choice)
3
将choice
作为整数3。这将在您进行的检查中比较false,因为3 == "3"
将始终为false。 (因为与整数和字符串的任何比较均为False)
但是,Python 3中的相同代码略有不同:
choice = input("Choice: ")
Choice: 3
print(choice)
"3"
在这里,代码可以实现您所期望的。 希望这解释了在IDLE中使用Python 3.x的代码将如何工作,而在Python 2.x运行时的代码却无法工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.