Return Value from Function is None - python

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

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"

Python nonsense syntax error, indented blocks

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\"")

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