无法退出程序 - Python

时间:2015-08-13 10:10:43

标签: python

嘿,我是Python的新手,只使用它2天,而且编程相对较新。 我正在尝试创建一个Rock,Paper,Scissors游戏。我的问题是,当我运行程序并插入'quit'(应该退出程序)程序继续运行,我不知道为什么。有任何想法吗? 这是我的代码:

from random import randint

#the computer's hand
def ran_number():
  comp_choice = randint(1, 3)
  if comp_choice == 1:
    hand = "rock"
  elif comp_choice == 2:
    hand = "paper"
  else:
    hand = "scissors"
  return hand

#game starts
def play_game():
  print("Let's play a game of Rock, Paper, Scissors!")
  while True:
    choice = input("Type: 'rock', 'paper', or 'scissors' to play, or 'quit' to end the game.")
    choice.lower()
    comp = ran_number()

    if choice == 'quit':
      print("\nIt's been a pleasure to play against you! Hope to see you another time.")
      break
    elif ((choice == 'rock' and comp == 'paper') or (choice == 'paper' and comp == 'scissors') or (choice == 'scissors' and comp == 'rock')):
      print("\n{} beats  {}! You lose!".format(comp.capitalize(), choice.capitalize()))
      play_game()
      continue
    elif choice == comp:
      print("\nYou both played {}. It's a tie!".format(choice.capitalize()))
      play_game()
      continue
    else:
      print("\n{} beats{}! You win!".format(choice.capitalize(), comp.capitalize()))
      play_game()
      continue


play_game()

3 个答案:

答案 0 :(得分:1)

问题是您每次都会进入quit功能。因此,当您提供quit输入时,它会退出一个递归级别,您必须连续输入while输入游戏退出游戏的次数。

你根本不需要做递归,只需删除它就可以了,因为你也在使用choice.lower()循环。

此外,另一件事 - choice不在原地,您应该将其分配回continue

此外,您不需要elif部分内的from random import randint #the computer's hand def ran_number(): comp_choice = randint(1, 3) if comp_choice == 1: hand = "rock" elif comp_choice == 2: hand = "paper" else: hand = "scissors" return hand #game starts def play_game(): print("Let's play a game of Rock, Paper, Scissors!") while True: choice = input("Type: 'rock', 'paper', or 'scissors' to play, or 'quit' to end the game.") choice = choice.lower() comp = ran_number() if choice == 'quit': print("\nIt's been a pleasure to play against you! Hope to see you another time.") break elif ((choice == 'rock' and comp == 'paper') or (choice == 'paper' and comp == 'scissors') or (choice == 'scissors' and comp == 'rock')): print("\n{} beats {}! You lose!".format(comp.capitalize(), choice.capitalize())) elif choice == comp: print("\nYou both played {}. It's a tie!".format(choice.capitalize())) else: print("\n{} beats{}! You win!".format(choice.capitalize(), comp.capitalize())) play_game() ,因为您在继续之后没有任何语句,因此它会自动继续循环。

代码 -

__init__()

答案 1 :(得分:0)

我想你想说

choice = choice.lower()

也可能更安全

choice = choice.lower().strip()

删除任何不需要的空格。

答案 2 :(得分:0)

导入sys模块并调用exit()函数退出程序。

import sys

choice = raw_input("Type: 'rock', 'paper', or 'scissors' to play, or 'quit' to end the game: ")

if choice == 'quit':
    print("\nIt's been a pleasure to play against you!\n"
          "Hope to see you another time.")

sys.exit()