Warm tip: This article is reproduced from serverfault.com, please click

Guessing game with 5 chances in python

发布于 2020-11-28 21:01:05

This is my code:

import random

letters = ['a','g','s','s','c','v','e','g','d','g']

random_letter = random.choice(letters)

guesses_left = 5
while guesses_left > 0:
  guess = input("Your guess: ")
  if guess == random_letter:
    print ("You win!")
    break
  guesses_left -= 1 
else:
  print ("You lose.")

My question: Why am I able to type other types than strings? For example, if I run the code and answer with an integer I don't get error. If this problem is not fixable, is there a better way to create this type of game?

Questioner
Amx
Viewed
0
coderoftheday 2020-11-29 05:11:20

.isalpha checks to see if the string is all characters

import random

letters = ['a','g','s','s','c','v','e','g','d','g']

random_letter = random.choice(letters)

guesses_left = 5
while guesses_left > 0:
    guess = input("Your guess: ")
    if guess.isalpha():
        if guess == random_letter:
            print ("You win!")
            break
        else:
            print ("You lose.")
        guesses_left -= 1
    else:
        print('This is not a letter')