Ad

Try And Except Problems In Python 2.7

- 1 answer

I am trying to write a piece of code that asks the user if they want to restart and if so, it does so and if not, it says thanks for playing.

import os
import time
while True:
 try:
  print "He walks past you but then doubles back, he crouches down, you scream and try to grab the brick but your too slow,5 bullets penetrate your chest and go through your heart. Blood is coming out of your mouth, gagging on your own blood the last thing you see is him turning around and walking away. You died."
  death1 = raw_input ("Do you want to restart:")
  time.sleep(1)
  os.system('clear')
 except:
  if death1 == str("yes"):
      continue
  elif death1 == str("no"):
   print "Thanx for playing"
   break

Currently, as long as the user types in anything it will re-ask the question. Is there a way to make it so if they say no, it says thanks for playing?

Ad

Answer

while True:

    # game logic here

    want_restart = raw_input("Do you want to restart?")
    want_restart = want_restart.lower() == "yes"

    if not want_restart:
        break

print("Game ended. Thanks for playing")
Ad
source: stackoverflow.com
Ad