Loophole of an if inside a while [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I've made this program that requires the user to input 6 different numbers and i made it so if it's not happy with the numbers he can change them. The thing is that i put this condition so it would reedit the numbers but it seems to be loopholeing in the var of the input "cambio" that checks if it's happy with the numbers.
import random
def ingreso_numeros():
while len(nums_usuario) < 6:
num = int(input("Ingrese un número del 0 al 15: "))
if num in range(0,15) and num not in nums_usuario:
nums_usuario.append(num)
elif num not in range(0,15) and num not in nums_usuario:
print("El número ingresado no está entre 0 y 15")
elif num in range(0,15) and num in nums_usuario:
print("El número ya fue ingresado")
else:
("Machine Broke, contact supervisor")
print("Sus números ingresados son:",nums_usuario)
def quini_numeros():
while len(nums_quini) < 6:
x = randint(0,15)
if x not in nums_quini:
nums_quini.append(x)
conteo+=1
else:
pass
#testeo#
print(nums_quini)
#testeo#
## ------------ main -----------------------------------------
nums_quini = []
nums_usuario = []
opcion = True
ingreso_numeros()
while opcion == True:
cambio = input("¿Desea cambiar sus números? Sí(S)/No(N): ").upper
if cambio == "S":
nums_usuario.clear()
ingreso_numeros()
elif cambio == "N":
opcion = False
quini_numeros()

It seems you are not calling the method upper, then the value of cambio is <function str.upper>, and none of the conditions is executed which keeps you in an infinite loop.
cambio = input("¿Desea cambiar sus números? Sí(S)/No(N): ").upper() # use ()

I think looking at your code, I imagine you are going the route of checking if random ints are the same as what the user has entered.
I tried your code in python3 and found a couple of issues which I fixed. Hope this helps you progress.
import random
from random import randint
def ingreso_numeros():
while len(nums_usuario) < 6:
num = int(input("Ingrese un numero del 0 al 15: "))
if num in range(0,15) and num not in nums_usuario:
nums_usuario.append(num)
elif num not in range(0,15) and num not in nums_usuario:
print("El numero ingresado no esta entre 0 y 15")
elif num in range(0,15) and num in nums_usuario:
print("El numero ya fue ingresado")
else:
("Machine Broke, contact supervisor")
print("Sus numeros ingresados son:",nums_usuario)
def quini_numeros():
# you should declare before using a var
conteo = 0
while len(nums_quini) < 6:
x = randint(0,15)
if x not in nums_quini:
nums_quini.append(x)
conteo+=1
else:
pass
#testeo#
print(nums_quini)
#testeo#
## ------------ main -----------------------------------------
nums_quini = []
nums_usuario = []
opcion = True
ingreso_numeros()
while opcion == True:
cambio = input("enter your numbers? Yes(S)/No(N): ").upper()
print (cambio)
if cambio == "S":
print(nums_usuario)
nums_usuario.clear()
ingreso_numeros()
elif cambio == "N":
opcion = False
quini_numeros()

Related

need to end the players turn but instead my code keeps repeating itself infinitely (python)

So it basically should stop when tiros get to 3, but instead, when it gets to 3 the code just keeps runnining with no chance to input anything, it just keep writing the output of the results and incrementing infinitely.
here it is the full code
import random
import sys
import time
from os import system, name
num_jogadores = 0
min_jogadores = 2
dados = {"d_verde": {0: "cérebro", 1: "cérebro", 2: "cérebro", 3: "espingarda", 4: "pegada", 5: "pegada"}, "d_amarelo": {0: "cérebro", 1: "cérebro", 2: "espingarda", 3: "espingarda", 4: "pegada", 5: "pegada"}, "d_vermelho": {0: "cérebro", 1: "espingarda", 2: "espingarda", 3: "espingarda", 4: "pegada", 5: "pegada"}}
tiros = 0
cerebros = 0
#função para limpar o console
def limpar_tela():
if name == 'nt':
_ = system('cls')
#função para sortear a cor do dado
def cor_seletor():
cor = random.randrange(13)
if cor < 6:
return "verde"
elif cor >= 6 and cor < 10:
return "amarelo"
elif cor >= 10 and cor < 13:
return "vermelho"
#definir qual lado será escolhido aleatoriamente
def dado_lado():
lado = random.randrange(6)
return lado
def jogar_dados():
dado = cor_seletor()
lado = dado_lado()
if dado == "verde":
return (dado, dados["d_verde"][lado])
elif dado == "amarelo":
return (dado, dados["d_amarelo"][lado])
elif dado == "vermelho":
return (dado, dados["d_vermelho"][lado])
def rodada():
global cerebros
global tiros
j = 0
while j < 3:
cor_dado, resultado = jogar_dados()
if resultado == "cérebro":
cerebros += 1
elif resultado == "espingarda":
tiros += 1
print("A cor do seu dado foi:", cor_dado, ", e a face foi:", resultado,"!")
j += 1
print("Cérebros: ", cerebros, " e Tiros:", tiros)
#menu inicial.
print("Bem-vindos ao ZOMBIE DICE!")
inicio = input("Para começar o jogo digite qualquer coisa para começar ou para sair do jogo digite 'sair'\n")
if inicio.casefold() == "sair":
limpar_tela()
sys.stdout.write("Saindo...")
sys.stdout.flush()
time.sleep(1)
sys.exit()
else:
print("Vamos começar!")
jogar = input("Caso esteja pronto para o jogo, digite s, caso não esteja, digite n: ")
here is the part of the code that keeps repeating after the counter of tiros get past 3
while jogar not in "sn":
print("Sinto muito, sua resposta precisa ser 's' ou 'n' ")
jogar = input("Caso esteja pronto para o jogo, digite 's', caso não esteja, digite 'n': ")
else:
if jogar == "n":
print("Obrigado por jogar!")
while jogar == "s":
rodada()
if tiros < 3:
jogar = input("Você gostaria de rolar novamente? Caso sim, digite 's' caso não 'n': ")
while jogar not in "sn":
print("Sinto muito, sua resposta precisa ser 's' ou 'n'")
jogar = input("Você gostaria de rolar novamente?\n Digite 's' para sim e 'n' para não")
else:
if jogar == "s":
print("Jogando novamente...")
else:
print("Sua vez acabou.")
else:
print("Você tem três espingardas, seu turno acabou.")
play = "n"
As a better practice if you want your loop to iterate three times, it is better to do :
for _ in range(3):
do something
than:
j = 0
while j < 3:
j += 1
you will be less likely to change your variables and have endless loops. Anyway, here your main while loop should end when jogar != "s".
However I don't see any possible way to modify it if tiros > 3 in your code as the last line should probably be:
jogar = "n"
instead of
play = "n"

My while doesn't break when it should also with the condition difficoltà <= difficoltà*2

Here is my code. Please help me to correct it. Thanks!
I made a game where you have to memorize if you have seen a number or not. And when you finish you win.
import random
randomlist = []
for i in range(0,50):
n = random.randint(1,50)
if n in randomlist:
continue
else:
randomlist.append(n)
life=3
punti=0
numeri_visti=[]
difficoltà= int(input("Quanti numeri vuoi indovinare? "))
while life > 0 and difficoltà <= difficoltà*2:
numero = str(random.choice(randomlist))
check = len(numeri_visti)
print(numero)
risposta=input("Hai già visto questo numero: ")
if risposta == "SI" and numero in numeri_visti:
punti= punti+1
difficoltà= difficoltà+1
print(difficoltà)
elif risposta == "NO" and numero not in randomlist:
numeri_visti.append(numero)
punti= punti+1
difficoltà= difficoltà+1
print(difficoltà)
else:
life= life-1
if check==difficoltà:
print("Hai completato il gioco, sei un asso della memoria!!!")
else:
print("Mi dispiace hai perso, ma non arrenderti hai comunque fatto: ",punti," punti !!!")
If the difficulty limit should be twice the original difficulty, you need to save that at the beginning. Because you keep increasing difficoltà, so difficoltà*2 also increases when compare them.
difficoltà= int(input("Quanti numeri vuoi indovinare? "))
max_difficoltà = difficoltà*2
while life > 0 and difficoltà <= max_difficoltà:

Extra Output None

I'm creating a program that asks the user to guess a random number, here's the code:
import random
# Declaração de Variáveis
num = random.randint(0, 10)
presora = int(input(print("Por favor adivinhe um número de 0 a 10: ")))
# Corpo
while presora != num:
presora = int(input(print("Desculpe você errou, tente de novo: ")))
vida = -1
print(vida)
else:
print("Parabéns, você acertou!")
quit()
but whenever I run it appears none at the end:
Por favor adivinhe um número de 0 a 10:
None
Can someone help me?`
The problem is here:
presora = int(input(print("Por favor adivinhe um número de 0 a 10: ")))
instead, write just
presora = int(input("Por favor adivinhe um número de 0 a 10: "))
input prints the text, there is no need for print as well.

Why i cant use this python application?

Well, i made this as my first application. But now, i want to use it, and when i select an option, i does not work
def empezar():
print ("Desea hacer bhaskara, forma polinomica a canonica, forma canonica a polinomica?")
print ("(0=bhaskara, 1=canonica1, 2=canonica2, 3= canonica a polinomica)")
print ("Recordar, que 1 es igual a una x")
empezar = (input("Eleccion: "))
if empezar == 3:
poaca()
elif empezar == 2:
canonica2()
elif empezar == 1:
canonica1()
elif empezar == 0:
inputs()
#Correr codigo
empezar()
Every function is defined and when i send a number, the code just get closed. But it does not have any errors and i was running before.
Here is fixed code:
def empezar():
print ("Desea hacer bhaskara, forma polinomica a canonica, forma canonica a polinomica?")
print ("(0=bhaskara, 1=canonica1, 2=canonica2, 3= canonica a polinomica)")
print ("Recordar, que 1 es igual a una x")
empezar = (int(input("Eleccion: ")))
if empezar == 3:
poaca()
elif empezar == 2:
canonica2()
elif empezar == 1:
canonica1()
elif empezar == 0:
inputs()
#Correr codigo
empezar()
I simply cast the value input() to an integer value and it is working just fine for me.
Note: don't forget to implement the functions you are calling after checking the input
I suggest you use different name for variable from the function name.
Also, please check all your functions and make sure they have a return or print inside.
You could include those functions in your post.
def empezar():
print ("Desea hacer bhaskara, forma polinomica a canonica, forma canonica a polinomica?")
print ("(0=bhaskara, 1=canonica1, 2=canonica2, 3= canonica a polinomica)")
print ("Recordar, que 1 es igual a una x")
empezar_input = (input("Eleccion: "))
if empezar_input == 3:
poaca()
elif empezar_input == 2:
canonica2()
elif empezar_input == 1:
canonica1()
elif empezar_input == 0:
inputs()
#Correr codigo
empezar()

else not being activated in my code

I am a beginner and I have written the following code. My problem is that I am not being able to stop the while loop by setting "continuar" to False. My idea is that when the input is not 1 nor 2, the last else should do that, but it does not. What am I doing wrong?
Thanks.
import random
print("Vamos a usar la estrategia de la martingala")
print("La apuesta mínima es 1€")
dinero_inicial=int(input("Con cuanto dinero empiezas? "))
dinero=dinero_inicial
dinero_apostado=1
continuar=True
while dinero>=dinero_apostado and continuar==True:
print()
apuesta=int(input("Introduce 1 para el negro, 2 para el rojo o otro número para retirarte: "))
if apuesta==1 or apuesta==2:
casilla=random.choices([0,1,2],[1,18,18])
casilla=casilla.pop()
if casilla==0:
print("Ha salido el 0")
elif casilla==1:
print("Ha salido el negro")
elif casilla==2:
print("Ha salido el rojo")
if casilla==apuesta:
print("Felicidades, has ganado la apuesta")
dinero=dinero+dinero_apostado
dinero_apostado=1
elif casilla != apuesta:
print("Has perdido la apuesta")
dinero=dinero-dinero_apostado
dinero_apostado=dinero_apostado*2
print("Te quedan {}€ y ahora apostarás {}€ ".format(dinero,dinero_apostado))
else:
continuar==False
print()
print("Has dejado de jugar")
if dinero>dinero_inicial:
print("Has acabado con {}€ y has ganado {}€".format(dinero,dinero-dinero-dinero_inicial))
else:
print("Has acabado con {}€ y has perdido {}€".format(dinero,dinero_inicial-dinero))
Well, you aren't actually setting it to False in your else. You are doing an equality check of the variable continuar against False:
== Checks equality:
continuar==False
= Sets the value:
continuar=False
You have to write continuar = False which assigns the variable continuar the value False, but continuar == False checks if the variable continuar is False which results in False because it is True.

Categories

Resources