Input and Loops
Speaking of choices, you’ll want to specify just what the choices are. Line 4 declares
CHOICES, a list containing the strings
"scissors". Line 6 prints a challenge to the player, and then line 8 requests their response.
You shouldn’t just accept any random thing from the user. You want to make sure it’s a valid choice. Line 10 verifies that what the user typed in is one of the items in the
CHOICES list. If it is, then line 11 randomly selects the computer’s response.
choice() function takes a list and randomly chooses one of the items in the list. The selection is returned and, in this case, is stored in
computer_choice. Lines 12 through 14 contain a print statement showing the result to the user.
If you haven’t seen an f-string before, it is a way of creating a template that Python will fill in. An f-string is prefixed with the letter
f, hence the name, and then it looks for brace brackets—those are the curly ones—inside the string. Values in the brace brackets are replaced with their corresponding variables. In this case, the
computer_choice values are inserted into the string.
The whole thing is then put to the screen by the
print() function. Since line 10 checked for valid values, you want to tell the user if they didn’t choose something valid. Line 16, inside this
else clause, tells the user what they typed and tells them it wasn’t a good choice.
03:07 What about asking the user if they want to throw down again? To do this, you’ll need to wrap all the game logic in a loop, and after the result is shown, prompt the user if they want to play again. Let’s see the code.
The next chunk of work is just the code from
simple.py but embedded inside of the loop. Then, after that, at line 17 is a new edition. Once a round has been played, this prompts the user if they want to play again.
This method returns the lowercase version of the string it is being called upon. That way, if the user inputs capital
"N", it will be turned into a lowercase
"n" before it is compared. If the user indicates no, then the
break statement is called. The
break statement breaks you out of the surrounding loop. In this case, the code would continue to line 23.
If the user typed anything but
"n", it is assumed they meant yes. In this case, the code inside the loop continues. Line 21 is an empty
print(), which will display a blank line. After that, the execution continues back to the top of the
while loop, asking the user to make their next throw.
Become a Member to join the conversation.