Record#
Today I continued learning the while function, reviewing the break from yesterday, and learning about continue and exit.
- break is used to exit a loop in while.
- continue is used to restart execution from the first line in the while loop.
- exit() is also used to exit a loop. exit() is a function, note that it has parentheses.
- ChatGPT told me that break and exit() are different:
break
is used to interrupt the current loop and continue executing the code after the loop.exit()
is used to immediately terminate the execution of the program, without executing any code afterwards.
- I learned a new trick. In replit, in the left side table of contents, click the + sign in the upper right corner, and the code will automatically be pasted into the editing area on the right side.
- In the final stage of code writing, I made modifications to the rock-paper-scissors game from item 14. I added a scoring feature and the ability to re-enter input if there is an error. Apart from the code being a bit longer, I am satisfied.
CODE#
from getpass import getpass as input
print("Rock Paper Scissors Game! Best of three rounds!")
print()
print("Your choices: 🪨 = R, ✂️ = S, 📄 = P")
p1 = ""
p2 = ""
n = 1
score1 = 0
score2 = 0
while True:
print()
print("Round", n)
while True:
p1 = input("Player 1: What's your choice? ")
if p1 == "R" or p1 == "S" or p1 == "P":
break
while True:
p2 = input("Player 2: What's your choice? ")
if p2 == "R" or p2 == "S" or p2 == "P":
break
if p1 == p2:
print("It's a tie!")
elif p1 == "R" and p2 == "S":
print("Player 1 wins!")
score1 += 1
elif p1 == "R" and p2 == "P":
print("Player 2 wins!")
score2 += 1
elif p1 == "S" and p2 == "P":
print("Player 1 wins!")
score1 += 1
elif p1 == "S" and p2 == "R":
print("Player 2 wins!")
score2 += 1
elif p1 == "P" and p2 == "R":
print("Player 1 wins!")
score1 += 1
elif p1 == "P" and p2 == "S":
print("Player 2 wins!")
score2 += 1
if score1 == 2:
print("Player 1 wins the final victory")
break
elif score2 == 2:
print("Player 2 wins the final victory")
break
else:
n += 1
continue