Necesito hacer un seguimiento de la cantidad de conjeturas que ingresa un usuario en un simple juego de adivinanzas.
He intentado usar los intentos = 0 y luego establecer los intentos a = intentos + 1. Incluso cuando hago esto, el código imprimirá "Has adivinado en 1 intentos" incluso cuando el usuario haya adivinado en más intentos que uno.
Código:
attempts = 0;
print("Hello, welcome to the game. You will be choosing a number
between 1 and 100. You can only guess up to 10 times.")
for tries in range(tries_allowed):
print("You only get 10 tries.")
break
while attempts < 10:
guess = int(input("Please guess a number"));
attempts_used= attempts + 1;
if guess > random_number:
print("Guess is too high, try a smaller number");
elif guess < random_number:
print("Guess is too low, try a higher number");
elif guess == random_number:
attempts_used=str(attempts_used)
print("Correct- you win in", attempts_used, "guesses");
exit();
else:
if tries_allowed == 10:
print("You failed to guess in time")
my_list= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list.append(attempts_used)
print(my_list)
4 respuestas
Limpié un poco su código, muestra el método de conteo +=
que funciona para su secuencia de comandos. Como otros han dicho, el código original está creando una variable completamente nueva attempts_used
que es simplemente attempts + 1
, y attempts
sigue siendo 0.
También podría ser attempts = attempts + 1
, +=
significa lo mismo.
Para hacer un int
a str
en Python para fines de impresión, no es necesario que se almacene en una variable separada, solo llame str()
a su alrededor, a menos que planee usar la cadena por separado .
import random
random_number = random.randint(1,100)
attempts = 0
tries_allowed = 10
print("Hello, welcome to the game. You will be choosing a number between 1 and 100")
print("You only get " + str(tries_allowed) + " tries.")
my_list = []
while attempts < tries_allowed:
guess = int(input("Please guess a number: "))
if guess in my_list:
print("You have already guessed " + str(guess))
continue
attempts += 1
my_list.append(guess)
if guess > random_number:
print("Guess is too high, try a smaller number")
elif guess < random_number:
print("Guess is too low, try a higher number")
elif guess == random_number:
print("Correct- you win in", str(attempts), "guesses")
break
else:
if attempts == 10:
print("You failed to guess in time")
for item in my_list:
print(item)
Nunca actualiza la variable attempts
, ha creado una nueva llamada attempts_used
, no necesita hacer esto.
Simplemente use attempts
donde quiera que esté usando attempts_used
Nota: Mientras lo hace, debe deshacerse de lo que se conoce como un "número mágico" o un límite codificado en su ciclo while
while attempts < tries_allowed:
Código que también verifica la entrada anterior e imprime un mensaje.
import random
# Hello World program in Python
attempts = 0
print("Hello, welcome to the game. You will be choosing a number between 1 and 100. You can only guess up to 10 times.")
random_number = random.randint(1, 101)
#print(random_number)
my_list= []
for tries in range(10):
print("You only get 10 tries.")
guess = int(input("Please guess a number: "))
if guess in my_list:
print("You already guessed this number!!")
my_list.append(guess)
attempts += 1
if guess > random_number:
print("Guess is too high, try a smaller number")
elif guess < random_number:
print("Guess is too low, try a higher number")
else:
print("Correct- you win in", tries + 1, "guesses")
attempts = -1
break
if attempts is 10 and attempts is not -1:
print("You failed to guess in time")
print("Attempts : ", my_list)
Su variable "intentos" permanece en 0, por lo que los intentos utilizados (intentos + 1) siempre serán 1. Debe fusionar ambas variables en una sola para controlarla (intentos = intentos + 1)
Preguntas relacionadas
Nuevas preguntas
python
Python es un lenguaje de programación multipropósito, de tipificación dinámica y de múltiples paradigmas. Está diseñado para ser rápido de aprender, comprender y usar, y hacer cumplir una sintaxis limpia y uniforme. Tenga en cuenta que Python 2 está oficialmente fuera de soporte a partir del 01-01-2020. Aún así, para preguntas de Python específicas de la versión, agregue la etiqueta [python-2.7] o [python-3.x]. Cuando utilice una variante de Python (por ejemplo, Jython, PyPy) o una biblioteca (por ejemplo, Pandas y NumPy), inclúyala en las etiquetas.