Reputation:
Just need this for a game program. At the end of the Rock-Paper-Scissors program it asks if the user wants to play again or not, and uses sys.exit()
to terminate the program. However, instead of terminating the program if the user enters something that isn't 'Y' or 'y' in the replayFunc()
function, it goes into the code under the except:
block in main()
. Any help is appreciated.
import random
import os
import sys
userOS = str(sys.platform)
def clearFunc():
if "win32" not in userOS:
os.system('clear')
else:
os.system('cls')
def replayFunc():
exitPrompt = input("Do you want to play again? (Y/N): ")
if exitPrompt == 'Y' or exitPrompt == 'y':
main()
else:
sys.exit(0)
def main():
oppChoice = random.randint(1,3)
playerChoice = int
print("Welcome to Rock-Paper-Scissors!")
input("\nPress Enter to continue: ")
clearFunc()
try:
playerChoice = int(input("Please use 1-3 to select from the list below:\n\n1. Rock\n2. Paper\n3. Scissors\n"))
if playerChoice == 1 and oppChoice == 1:
print("You tied!")
replayFunc()
elif playerChoice == 1 and oppChoice == 2:
print("Computer Wins!")
replayFunc()
elif playerChoice == 1 and oppChoice == 3:
print("You win!")
replayFunc()
elif playerChoice == 2 and oppChoice == 1:
print("You win!")
replayFunc()
elif playerChoice == 2 and oppChoice == 2:
print("You tied!")
replayFunc()
elif playerChoice == 2 and oppChoice == 3:
print("Computer Wins!")
replayFunc()
elif playerChoice == 3 and oppChoice == 1:
print("Computer wins!")
replayFunc()
elif playerChoice == 3 and oppChoice == 2:
print("You win!")
replayFunc()
elif playerChoice == 3 and oppChoice == 3:
print("You tied!")
replayFunc()
else:
print("Didn't get that")
main()
except:
print("TypeError")
main()
main()
Upvotes: 0
Views: 438
Reputation: 155363
sys.exit(0)
is basically implemented as raise SystemExit(0)
. It's an exception, because you need to bubble up so context managers (with
statements) and finally
blocks can clean up properly.
The reason bare except:
is frowned upon is because it catches even exceptions that shouldn't be caught, e.g. SystemExit
. So stop using it, and catch only exceptions you know how to handle, or at least change it to except Exception:
which won't catch the special, shouldn't be caught exceptions (like SystemExit
and KeyboardInterrupt
).
Upvotes: 2