-3
import random
print ("welcome to my game")

guessestaken = 0
number = random.randint(1,10)

print ("what is your name")

myname = raw_input()

print ("Well,"+ myname + "," + "I'm thinking of a number between  1 and 10"

while guessesTaken < 6:
    print ("take a guess")
    guess = raw_input()
    guess = int(guess)
    guesstaken = guesstaken + 1

    if guess < number :
        print  ("your guess is low")
    if guess > number :
        print  ("your guess is high")
    if guess == number :
        break
if guess == number :
    print ("You are awesome ")
    guesstaken = str(guessestaken)
    print ("You guessed the number in " + guessestaken + " try" )

if guess != number:
    print "You lost"

每次我尝试执行它时,都会出现错误“而 guessesTaken < 6: ^ SyntaxError: invalid syntax”

4

2 回答 2

2

print语句前的while语句省略右括号:

print ("Well,"+ myname + "," + "I'm thinking of a number between  1 and 10"

删除左括号或附加右括号。

于 2013-07-27T18:40:50.857 回答
1

falsetru 已经回答了你的问题。您还可以在和guessesTaken之间自由切换。我只想补充一点,python 有一个很好的控制语句,用于确定循环是否由于被耗尽或破坏(by )而完成。在这些情况下,您可以使用.guesstakenguessestakenbreakwhile...else

在您的代码中,它看起来像这样:

#! /usr/bin/python3

import random

number = random.randint(1, 10)
print ('Welcome to my game.')

myName = input ('What is your name? ')
print ('Well, {}, I\'m thinking of a number between 1 and 10'.format (myName) )

guessesTaken = 0
while guessesTaken < 6:
    guess = int (input ('Take a guess: ') )
    guessesTaken += 1

    if guess < number: print  ('Your guess is low.')
    if guess > number: print  ('Your guess is high.')
    if guess == number:
        print ('You guessed the number in {} tr{}.'.format (guessesTaken, 'y' if guessesTaken == 1 else 'ies') )
        break
else: print ('You lost.')
于 2013-07-27T18:58:05.337 回答