【发布时间】:2017-07-11 02:12:11
【问题描述】:
因此,我需要编写一个程序,将电视模拟为 Python 教程书中的挑战对象(Python for the Absolute Beginner,第 8 章)。我认为大部分代码都类似于那一章中的 Critter Caretaker 程序。我还不知道一旦我解决了我将要提出的问题,这个程序是否会工作,因为我无法让它运行。
代码如下:
#TV Object
class TV(object):
def __init__(self, volume = 50, channel = 1):
self.volume = 50
self.channel = 1
print("You have turned on your TV")
def change_channel(self, channel):
print("This TV has three channels: News, Weather, and Soap Operas.")
print("""
Which would you like to watch?
1 - News
2 - Weather
3 - Soap Operas
""")
change = int(input(""))
if change in range(1-3):
channel = change
return channel
def set_volume(self, volume):
print("The current volume is ", volume, ".")
change = int(input("What volume level would you like (1-100)?:")
if change in range(1-100):
volume = change
return volume
def watch(self, volume, channel):
news = "Breaking News: U.S Senate to vote today on bill to use politicians for lab experiments."
weather = "We're looking at a mostly sunny day with a slight chance of atomic anhiliation."
soap = "John, I think I'm pregnant! And the father is your evil twin!"
if channel == 1:
program = news
if channel == 2:
program = weather
if channel == 3:
program = soap
if volume == 70>:
print(upper(program))
elif volume == 30<:
print(lower(program))
else:
print(program)
def main():
tv = TV()
choice = None
while choice != "0":
print \
("""
0 - Turn it off
1 - Change the channel
2 - Set the volume
3 - Watch TV
""")
choice = input("Choice: ")
print()
#exit
if choice == "0":
print("Good-bye.")
#change the channel
elif choice == "1":
tv.change_channel(channel)
#set volue
elif choice == "2":
tv.set_volume(volume)
#watch TV
elif choice == "3":
tv.watch(volume, channel)
#some unknown choice
else:
print("\nSorry but", choice, "isn't a valid choice.")
main()
input("\n\nPress the enter key to exit
set_volume方法出现错误。
def set_volume(self, volume):
print("The current volume is ", volume, ".")
change = int(input("What volume level would you like (1-100)?:")
if change in range(1-100):
volume = change
return volume
一旦我到达“if change in range(1-100):”这行代码,pyshell 就会告诉我,我在冒号上做了一个语法错误。它没有给我更多关于那个错误是什么的信息。
另一个奇怪的现象是,在编写程序时,我从冒号移到下一行后的自动间距似乎关闭了;就像它将光标移动到太多空格上一样,好像它认为代码是针对前一个冒号之后的不可见子冒号的。起初我以为我可能没有完成前一行代码,但我似乎无法弄清楚它是什么。
是什么导致我的语法错误?
P.S:如果其他人注意到语法错误修复后会出现的其他代码问题,我将不胜感激。我是对象编程的新手,我可以使用我能获得的所有帮助。
【问题讨论】:
-
您在这一行缺少右括号:
change = int(input("What volume level would you like (1-100)?:") -
另外,range(1-100) 不会像你想象的那样做。
-
如前文所述,您的
range(1-100)不正确。你想要range(1, 100)。但是,如果您实际打印 ->print(list(range(1, 100))),您会看到它实际上只转到99。所以,你实际上想要range(1, 101)。
标签: python object methods syntax-error