因此,我需要編寫一個模擬電視作爲Python教程書(Python for the Absolute Beginner,第8章)中挑戰對象的程序。我認爲大部分代碼與該章節的Critter Caretaker程序相似。一旦我解決了即將出現的問題,我還不知道這個程序是否能正常工作,因爲我無法運行它。Python中的面向對象編程:神祕的語法錯誤 - 電視對象
下面是代碼:
#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
一旦我達到這個「如果範圍變化(1-100):」行代碼中,pyshell告訴我,我犯了一個語法錯誤有權在結腸。它沒有給我任何關於那個錯誤是什麼的更多信息。
已經發生的另一個奇怪現象是,在編寫程序時,我從一個冒號移動到下一行後的自動間距似乎是關閉的;就像它將光標移動到太多空格上一樣,就好像它認爲代碼是用於在前面的冒號後面出現的不可見的SUBcolon一樣。起初我想也許我沒有完成前面的一行代碼,但我似乎無法弄清楚它是什麼。
什麼導致我的語法錯誤? P:如果其他人注意到代碼會出現其他問題,一旦語法錯誤得到修復,就會出現問題,我希望能夠告訴他們這些問題。我是新來的對象編程,我可以使用我可以獲得的所有幫助。
你錯過了這一行的右括號:'change = int(input(「你想要什麼音量級別(1-100)?:」)' –
另外,範圍(1-100)不會 –
正如前面的評論所述,你的'範圍(1-100)'是不正確的,你想'範圍(1,100)'。但是,如果你真的打印 - >'print(list範圍(1,100)))',你會發現它實際上只是到了'99',所以你實際上需要'range(1,101)'。 – idjaw