'int' object has no attribute 'strip' error message - python

This is my program and what means this error?
def menuAdiciona():
nome = input("Digite o nome de quem fez o cafe: ")
nota = int(input("Que nota recebeu: "))
if len(nome.strip()) == 0:
menuAdiciona()
if len(nota.strip()) == 0:
menuAdiciona()
if nota < 0:
nota = 0
AttributeError: 'int' object has no attribute 'strip'.

If you have a case for which you don't know whether the incoming value is a string or something else, you can deal with this using a try...except:
try:
r = myVariableOfUnknownType.strip())
except AttributeError:
# data is not a string, cannot strip
r = myVariableOfUnknownType

You are trying to call strip() on the nota value, which is an integer. Don't do that.

integer has no strip attribute... so you can make it like this...
if len(str(nome).strip()) == 0:
menuAdiciona()
if len(str(nota).strip()) == 0:
menuAdiciona()

strip is only available for strings
if you desperately need to strip numbers try this:
str(nome).strip()
str(nota).strip()
so it turns out to be:
def menuAdiciona():
nome = input("Digite o nome de quem fez o cafe: ")
nota = int(input("Que nota recebeu: "))
if len(str(nome).strip()) == 0:
menuAdiciona()
if len(str(nota).strip()) == 0:
menuAdiciona()
if nota < 0:
nota = 0

Related

I wanted to print this tuple in a single line

I was making a small program to exemplify the wordle game in python but the code below generates an output in tuple format (one element per line). Like this:
T
_
E
T
E
the code:
def check_palpite():
palavra_secreta = "Sorte"
tentativas = 6
while tentativas > 0:
palpite = str(input("Faça um palpite de palavra de 5 letras!"))
if palpite == palavra_secreta:
print("Resposta correta")
break
else:
tentativas = tentativas - 1
print(f"Você tem {tentativas} tentativa(s) \n ")
for char, palavra in zip(palavra_secreta, palpite):
if palavra in palavra_secreta and palavra in char:
print(palavra.upper())
elif palavra in palavra_secreta:
print(palavra.lower())
else:
print("_")
if tentativas == 0:
print(f"Fim de jogo a palavra era {palavra_secreta}")
check_palpite()
I need the elements to be generated in a single-line format and not a tuple. Like this:
T_ETE
I believe that to solve this problem the responsible part of the code is this
for char, palavra in zip(palavra_secreta, palpite):
if palavra in palavra_secreta and palavra in char:
You have two approaches, either:
pass a string to the end= parameter of print(), or
append each character to a string and print the string after the loop.
Approach 2 is faster because it makes fewer function calls, so I'll use that one. Just create an empty string before the loop, then print that string at the end of the loop. Like this:
def check_palpite():
palavra_secreta = "Sorte"
tentativas = 6
while tentativas > 0:
palpite = str(input("Faça um palpite de palavra de 5 letras! "))
if palpite == palavra_secreta:
print("Resposta correta")
break
tentativas = tentativas - 1
print(f"Você tem {tentativas} tentativa(s) \n ")
string = ""
for char, palavra in zip(palavra_secreta, palpite):
if palavra in palavra_secreta and palavra in char:
string += palavra.upper()
elif palavra in palavra_secreta:
string += palavra.lower()
else:
string += "_"
if tentativas == 0:
print(f"Fim de jogo a palavra era {palavra_secreta}")
print(string)
check_palpite()

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

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à:

Loophole of an if inside a while [closed]

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()

Calling the second function in a "while" loop

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

Categories

Resources