这个代码在python中猜猜游戏有什么问题

时间:2013-07-27 18:39:42

标签: python

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&lt; 6:             ^     SyntaxError:语法无效“出现

2 个答案:

答案 0 :(得分:2)

print语句之前的

while语句省略右括号:

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

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

答案 1 :(得分:1)

falsetru已经回答了你的问题。您还可以在guessesTakenguesstakenguessestaken之间自由切换。我只想补充一点,python有一个很好的控制语句,用于确定循环是否因为被删除或被破坏而被完成(break)。在这些情况下,您可以使用while...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.')