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.
Related
Hello So i created a function to see if every character of a string is valid to be changed from base 10 to base 2(binary for example) but i dont know why everytime i call the function it return None. Here is my function (I tried 2 Method)
Version 1 ( created a value initialized with False and if in the loop one of the char is no into the base it should return false and if it loop through all the character change the value to True and return it):
def valide_nbr_base(p_base,p_nombre):
base_bin = [0,1]
base_oct = [0,1,2,3,4,5,6,7]
base_hex = [0,1,2,3,4,5,6,7,8,9,"a","b","c","d","e","f"]
p_rep = False
if p_base == 2:
for i in range(len(p_nombre)):
if p_nombre[i] not in base_bin:
return r_rep
else:
p_rep = True
return p_rep
#if p_base == 8:
#if p_base == 16:
Version 2(Same as version 1 but with no variable simply return True or False):
def valide_nbr_base(p_base,p_nombre):
base_bin = [0,1]
base_oct = [0,1,2,3,4,5,6,7]
base_hex = [0,1,2,3,4,5,6,7,8,9,"a","b","c","d","e","f"]
if p_base == 2:
for i in range(len(p_nombre)):
if p_nombre[i] not in base_bin:
return False
else:
return True
#if p_base == 8:
#if p_base == 16:
Here is the full code so you can have a idea of how it work:
#def base_to_decimal():
def valide_nbr_base(p_base,p_nombre):
base_bin = [0,1]
base_oct = [0,1,2,3,4,5,6,7]
base_hex = [0,1,2,3,4,5,6,7,8,9,"a","b","c","d","e","f"]
p_rep = False
if p_base == 2:
for i in range(len(p_nombre)):
if p_nombre[i] not in base_bin:
return r_rep
else:
p_rep = True
return p_rep
#if p_base == 8:
#if p_base == 16:
from validerSaisieH22_Partie import *
#Comparaison Pour Valider Bonne Valeur
base = [2,8,16]
#Demander un choix de base si != int Value Error sinon boucle jusqu'a trouver la bonne base
choix =saisirEntier("Choix de la base 2 [binaire], 8 [octal] 16[Hexadécimal] :")
while choix not in base:
print("Erreur ==> Choix de la base doit être 2 ou 8 ou 16")
choix =saisirEntier("Choix de la base 2 [binaire], 8 [octal] 16[Hexadécimal] :")
#Demander le nombre a convertir et voir si il respecte le choix de la base si oui continuer sinon quitter le programme
nombre = input("Donner un nombre valide dans le système binaire pour le convertir en décimal:")
validiter = valide_nbr_base(base,nombre)
print(validiter)
the imported module is simply a try and except so people dont try to enter a letter at the base selection.
Thanks for the help i dont see why it would return None! :)
On Line 11 in your full code you have a undefined variable,
"r_rep" is not defined
In this code:
k = (input("Pizza vegetariana? (s/n):\n"))
print("Ingredientes:")
if k == 's':
print("1. Pimiento\n2. Tofu")
print("Elija el número de la opción")
elif k == 'n':
print("1. Peperoni\n2. Jamón\n3. Salmón\n")
for x in range(3):
l = int(input("Elija un número de las opciones:\n")
if l == 1:
n ="Peperoni "
elif l == 2:
n ="Jamón "
elif l == 3:
n ="Salmón "
print("Ingredientes elegidos: \n"
+n+"\nMozzarella"+"\nTomate")
else:
print("Tiene que introducir una \"s\" ó \"n\"")
Why does it give me a syntax error?
File "", line 10
if l == 1:
^
SyntaxError: invalid syntax
Because in the previous line you forgot to close the brackets for the int()
l = int(input("Elija un número de las opciones:\n"))
There was an ")" missing in line 9
You're missing a closing bracket on line 9. Also, consistent indentation is very important in python. Make sure you maintain it throughout your code. The corrected code is as follows:
k = (input("Pizza vegetariana? (s/n):\n"))
print("Ingredientes:")
if k == 's':
print("1. Pimiento\n2. Tofu")
print("Elija el número de la opción")
elif k == 'n':
print("1. Peperoni\n2. Jamón\n3. Salmón\n")
for x in range(3):
l = int(input("Elija un número de las opciones:\n"))
if l == 1:
n ="Peperoni "
elif l == 2:
n ="Jamón "
elif l == 3:
n ="Salmón "
print("Ingredientes elegidos: \n"+n+"\nMozzarella"+"\nTomate")
else:
print("Tiene que introducir una \"s\" ó \"n\"")
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.
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()
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()