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()
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
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"
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()
I'm on my early python self learning path and somehow I can't get the code to execute def cadastro() whenever 1 is imputed.
Can you please assist.
Valuable contributions have been shared with me on this forum which I'm greatly appreciative of, however I remain stuck with this code.
lista_de_usuarios = {}
print ('BEM VINDO AO BCI')
print("PARA CADASTRO PRESSIONE 1 E 2 PARA LOGIN")
while True:
opcao_1 = input()
if opcao_1 == '':
print ('NADA FOI SELECIONADO, ADEUS')
break
elif opcao_1 == 2:
acesso()
elif opcao_1 == 1:
cadastro()
def acesso():
print ('Insira o seu usuário')
user = input()
print ('insira a sua palávra chave')
password = input()
if user in lista_de_usuarios:
if lista_de_usuarios[user] == password:
print ('ACESSO LIVRE')
else:
print ('A senha digitada está incorrecta')
else:
print('Este usuário não consta em nossa base de dados')
acesso()
def cadastro():
print ('Insira o seu nome')
nome = input()
print ('insira a sua idade')
idade = input()
lista_de_usuarios[nome]=idade
cadastro()
You forgot to add " before your numbers. Because you asked for user input and added str(), they can only output a string.
elif opcao_1 == "1":
acesso()
elif opcao_1 == "2":
cadastro()
It is because the input type is a string and not a number, so your elif statement will never return true even if 1 or 2 is typed. Instead they should be:
elif opcao_1 == '1':
acesso()
elif opcao_1 == '2':
cadastro()
Blockquote
lista_de_usuarios = {}
print ('BEM VINDO AO BCI')
def opcoes():
print("PARA CADASTRO PRESSIONE 1 E 2 PARA LOGIN")
opcoes()
def acesso():
print ('Insira o seu usuário')
user = input()
print ('insira a sua palávra chave')
password = input()
if user in lista_de_usuarios:
if lista_de_usuarios[user] == password:
print ('ACESSO LIVRE')
else:
print ('A senha digitada está incorrecta')
else:
print('Este usuário não consta em nossa base de dados')
opcoes()
def cadastro():
print ('Insira o seu nome')
nome = input()
print ('insira a sua idade')
idade = input()
lista_de_usuarios[nome]=idade
print ('ESTA É A LISTA COMPLETA DE USUÁRIO: ',lista_de_usuarios)
while True:
opcao_1 = int(input())
if opcao_1 == '':
print ('NADA FOI SELECIONADO, ADEUS')
break
elif opcao_1 == 2:
acesso()
elif opcao_1 == 1:
cadastro()
Blockquote
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.