我在从在线视频中学习的同时编写此代码。运行代码后的问题我得到了最后一个其他缩进和print("string",end = "")
的错误。我只是无法弄清楚不断弹出的结束错误。
import random
# Make a list of words
words = ['apple','banana','orange','coconut','strawberry','lime','grapefruit','lemon','kumquat', 'blueberry','melon']
while True:
start = input("Press enter/return to start, or enter Q to quit")
if start.lower() == 'q':
break
# Pick a Random Number
secret_word = random.choice(words)
bad_guesses = []
good_guesses = []
while len(bad_guesses) < 7 and len(good_guesses) != len(list(secret_words)):
# Draw guesses letters, spaces and strikes
for letter in secret_word:
if letter in good_guesses:
print(letter, end = "")
else:
print('_', end = "")
print('')
print('Strikes: {}/7'.format(len(bad_guesses)))
print('')
# Take guess
guess = input("Guess a letter: ").lower()
if len(guess) != 1:
print("You can only guess a single letter !")
continue
elif guess in bad_guesses or guess in good_guesses:
print("You've already guessed that letter !")
continue
elif not guess.isalpha():
print("You can only guess letters !")
continue
if guess in secret_word:
good_guesses.append(guess)
if len(good_guesses) == len(list(secret_word)):
print("YOU WIN !! The word was{}".format(secret_word))
break
else:
bad_guesses.append(guess)
else:
print("You didn't guess it! My secret word was {}".format(secret_word))
这是我得到的错误:
line 17 print(letter, end = "") ^ SyntaxError: invalid syntax Process finished with exit code 1
关于我在试用2.7和3.0的Python版本。
当我删除end = ""
程序时,但是在返回时打破了。
答案 0 :(得分:0)
您在python 2.7中使用python 3 print
语法。如果添加from __future__ import print_function
,则可以执行此操作。所以你的脚本会像这样开始
from __future__ import print_function
import random
# Make a list of words
words = ['apple','banana','orange','coconut','strawberry','lime','grapefruit','lemon','kumquat', 'blueberry','melon']
除此之外,您需要修正第13行中的拼写错误(secret_words
=&gt; secret_word
)
while len(bad_guesses) < 7 and len(good_guesses) != len(list(secret_word)):
然后你的程序在python 3中运行正常,这是一个工作示例:https://repl.it/CG46