"I want to use the statement break, and also in case the condition is not True, to give some values to a new variable. The thing is, Python uses only one line, and still runs after i've inserted a number.
prompt = '\nDime tu edad y te dire el precio de tu entrada .'
prompt += '\n¿Cual es tu edad?'
while True:
edad = input(prompt)
edad = int(edad)
if edad < 3:
break
elif edad > 3: ## Here I'm trying to set the conditions as to give a new value to precio.
precio = '5€'
elif edad > 12:
precio = '10€'
elif edad > 18:
precio = '15€'
print(f" El precio es {precio}")
Related
I was coding this simple 'Bank' program for my first exercise with classes in Python but when I run it, says:
tabError: inconsistent use of tabs and spaces in indentation
line 45
if self.datos[x]['nombre'] == nombre and self.datos[x]['idnum'] == idnum and self.datos[x]['email'] == email:^
I understand what it means, and I took a look on my code and tried to find if there was some problem with the methods, nevertheless I couldn't understand what is causing it, I believe something about the dictionaries has something to do with it. So this is my code:
class Cliente:
def __init__(self):
self.datos = []
def opciones(self):
menu = ['1: Mostrar saldo',
'2: Ingresar monto',
'3: Retirar monto',
'4: Cerrar']
for option in range(len(menu)):
print(option)
opc_escoger = int(input('Escriba el número de la opción que desee: '))
if opc_escoger == 1:
self.mostrar()
elif opc_escoger == 2:
self.Ingresar()
elif opc_escoger == 3:
self.retirar()
elif opc_escoger == 4:
print('Saliendo...')
exit()
elif opc_escoger == 5:
self.registrarse
self.opciones()
def registrarse(self):
print('REGISTRO')
nombre = input('Ingrese su nombre de usuario: ')
idnum = input('Ingrese su número de documento de identificación: ')
email = input('Ingrese su dirección de correo electrónico: ')
self.datos.append({'nombre':nombre, 'idnum':idnum, 'email':email, 'monto': 0})
def ingresar(self):
print('INGRESAR')
nombre = input('Ingrese su nombre de usuario: ')
idnum = input('Ingrese su número de documento de identificación: ')
email = input('Ingrese su dirección de correo electrónico: ')
for x in range(len(self.datos)):
if self.datos[x]['nombre'] == nombre and self.datos[x]['idnum'] == idnum and self.datos[x]['email'] == email:
print('Dinero actual: ', self.datos[x]['monto'])
monto = input('¿Cuál es el monto a ingresar?: ')
self.datos[x]['monto':monto]
else:
print('Los datos ingresados no coinciden con los de un usuario registrado')
self.registrarse()
#Here's some more code for the other methods, but are pretty similar to the 'ingresar' method
I've been struglying to convert my .py file in to a working .exe file. This is my first time doing it and I can't seem to find my mistake.
I've tryed two methods, pyinstaller and cx_Freeze, and both times the conversion would occur without any error, but when I try to open the .exe file, it blinks a CMD window and nothing happens.
Can any one, please, help me?
my program:
import numpy as np
import pandas as pd
verde='\033[1;32m'
vermelho='\033[1;31m'
preto='\033[0;30m'
'DATA FRAME FROTA'
Empilhadeiras={'Paletrans':['PR20','PR16'],'STILL':['FMX','EGU'], 'Ameise':['EJC','X']}
Modelos= pd.DataFrame(Empilhadeiras, columns=['Paletrans','STILL','Ameise'])
print(Modelos)
Custos={'Impostos':[]}
print()
print()
'VALOR DO MAQUINÁRIO'
num_maquinário = float(input("Digite o valor do maquinário: "))
str(float(num_maquinário))
print('R$'+str(float(num_maquinário)))
print()
'VALOR DOS IMPOSTOS'
num_txs = float(input("Digite a alíquota (sem %): "))
print(str(float(num_txs)) + '%')
txs=num_maquinário*(num_txs/100)
str(txs)
print('R$'+ str(txs))
print()
'DEPRECIAÇÃO DO MAQUINÁRIO'
num_depre = float(input("Digite o percentual de depreciação por ano (sem %): "))
print(str(float(num_depre)) + '%')
depre=num_maquinário*(num_depre/100)
str(depre)
print('R$'+ str(depre))
print()
'VALOR DO FRETE'
num_frete = float(input("Digite o valor do frete: "))
str(float(num_frete))
print('Frete trajeto único: R$'+ str(float(num_frete)))
num_frete*2
str(num_frete*2)
print('Frete ida e volta: R$' + str(num_frete*2))
print()
'DURAÇÃO DO CONTRATO'
num_dur = float(input("Digite o tempo de duração do contrato em meses( de 12 a 60): "))
str(float(num_dur))
print(str(float(num_dur))+' meses')
print()
'CUSTO COM SUBSTITUIÇÃO DE PEÇAS'
num_pec = float(input("Digite o custo médio para substituição de peças por mês: "))
str(float(num_pec))
print('R$'+str(float(num_pec)))
num_peças= num_pec*num_dur
print('Custo total com peças ao longo do contrato:R$'+str(num_peças))
print()
'NÚMERO DE VISITAS TÉCNICAS'
num_vis= float(input("Digite o número de visitas técnicas mensais planejadas: "))
str(float(num_vis))
print('R$'+str(float(num_vis)))
num_visit = num_vis*num_dur
print('Custo total com visitas ao longo do contrato: R$'+str(num_visit))
print()
'NÚMERO DE HORAS TÉCNICAS'
num_htec = float(input("Número médio de horas técnicas por atendimento: "))
if num_htec < 4:
if num_htec < 4:
print("R$100,00")
elif 8> num_htec >4:
print("R$200,00")
elif 12> num_htec >8:
print("R$300,00")
else:
print("R$500,00")
else:
print("R$100,00")
m = num_htec*num_vis
def totTec(m):
m = num_htec*num_vis
if m < 4:
if m < 4:
htec = 100
elif 8> m>4:
htec = 200
elif 12> m>8:
htec = 300
elif 16> m>=12:
htec = 500
elif 20> m>16:
htec = 750
elif 24> m>20:
htec = 1200
else:
htec = 1500
else:
htec = 250
return htec
print('Valor Tempo total: R$'+str(totTec(m)))
print()
'CUSTO DAS HORAS DE DESLOCAMENTO'
num_dtemp = float(input("Tempo de deslocamento em horas até o cliente: "))
if num_dtemp < 4:
if num_dtemp < 4:
print("R$100,00")
elif 8> num_dtemp >4:
print("R$200,00")
elif 12> num_dtemp >8:
print("R$300,00")
else:
print("R$400,00")
else:
print("R$100,00")
str(num_dtemp*num_vis)
print('Total de horas:'+str(num_dtemp*num_vis))
a=num_dtemp*num_vis
def totTemp(a):
a=num_dtemp*num_vis
if a < 4:
if a < 4:
temp= 100
elif 8> a>4:
temp= 200
elif 12> a>8:
temp= 300
elif 16> a>12:
temp= 400
elif 20> a>16:
temp= 500
elif 24> a>20:
temp= 600
else:
temp= 400
else:
temp= 100
return temp
print('Valor Tempo total: R$'+str(totTemp(a))+',00')
print()
'CUSTO DA DISTÂNCIA DE DESLOCAMENTO ATÉ O CLIENTE'
num_distância = float(input("Digite a distância até o cliente em KM: "))
if num_distância*2 < 100:
if num_distância*2 < 100:
print("R$40,00")
elif 250> num_distância*2 >100:
print("R$100,00")
elif 400> num_distância*2 >250:
print("R$160,00")
elif 550> num_distância*2 >400:
print("R$220,00")
elif 700> num_distância*2 >550:
print("R$500,00")
else:
print("R$750,00")
else:
print("R$50,00")
k = (num_distância*2)*num_vis
def distTot(k):
k = (num_distância*2)*num_vis
if k < 100:
if k < 100:
dist = 40
elif 250> k>100:
dist = 160
elif 400> k>250:
dist = 220
elif 550> k>400:
dist = 280
elif 700> k>550:
dist = 340
elif 1000>= k>850:
dist = 400
else:
dist = 500
else:
dist = 40
return dist
print('Valor Distância total: R$'+str(distTot(k))+',00')
print()
'CUSTO COM PEDÁGIO'
num_pedágio = float(input("Digite o gasto com pedágio: "))
str(float(num_pedágio))
print('Pedágios por visita: R$'+str(float(num_pedágio)))
num_tped = num_pedágio*num_vis
print('Gasto total com pedágio: R$'+str(num_tped))
print()
'CUSTO COM HOSPEDAGEM'
num_hospedagem = float(input("Digite o gasto com hospedagem: "))
str(float(num_hospedagem))
print('Hospedagem por visita: R$'+str(float(num_hospedagem)))
num_thost = num_hospedagem*num_vis
print('Gasto total com hospedagem: R$'+str(num_thost))
print()
'CUSTO COM ALIMENTAÇÃO'
num_alimentação = float(input("Digite o gasto com alimentação: "))
str(float(num_alimentação))
print('Gasto com alimentação por vista: R$'+str(float(num_alimentação)))
num_tal= num_alimentação*num_vis
print('Gasto total com alimentação: R$'+str(num_tal))
print()
'CUSTO TOTAL INICIAL'
cti= num_maquinário + txs + num_frete
print('Custo inicial: R$'+str(cti))
print()
'CUSTO TOTAL ANUAL'
cta= totTec(m) + num_pec + distTot(k) + totTemp(a) + num_tped + num_thost + num_tal
print('Custo anual: R$'+str(cta))
print()
'CUSTO TOTAL'
CustoTotal= num_maquinário + txs + depre + + (num_frete*2) + totTec(m) + num_pec + distTot(k) + totTemp(a) + num_tped + num_thost + num_tal
print('Custo total: R$'+str(CustoTotal))
'VALOR DO ALUGUEL'
num_alg = float(input("Digite o valor da Parcela Aluguel: "))
str(float(num_alg))
print('R$'+str(float(num_alg)))
rend_anual= num_alg*12
print('Receita Anual:R$'+ str(rend_anual))
print()
'TAXA MÍNIMA DE ATRATIVIDADE'
num_tma = float(input("Digite a Taxa Mínima de Atratividade: "))
str(float(num_tma))
print(str(float(num_tma))+'%')
num_TMA=num_tma/100
print()
dep1= num_maquinário - depre
dep2=dep1 - (dep1*num_depre)
dep3=dep2 - (dep2*num_depre)
dep4=dep3 - (dep3*num_depre)
dep5=dep4 - (dep4*num_depre)
ano_X=(rend_anual- cta)
ano_1=(rend_anual- cta + dep1 + num_frete)
ano_2=(rend_anual- cta + dep2 + num_frete)
ano_3=(rend_anual- cta + dep3 + num_frete)
ano_4=(rend_anual- cta + dep4 + num_frete)
ano_5=(rend_anual- cta + dep5 + num_frete)
n_1=12
n_2=24
n_3=36
n_4=48
n_5=60
Hipotese_1 = np.array([-cti,ano_1])
Hipotese_2 = np.array([-cti,ano_X,ano_2])
Hipotese_3 = np.array([-cti,ano_X,ano_X,ano_3])
Hipotese_4 = np.array([-cti,ano_X,ano_X,ano_X,ano_4])
Hipotese_5 = np.array([-cti,ano_X,ano_X,ano_X,ano_X,ano_5])
VPL_1=np.npv(rate=num_TMA, values=Hipotese_1)
VPL_2=np.npv(rate=num_TMA, values=Hipotese_2)
VPL_3=np.npv(rate=num_TMA, values=Hipotese_3)
VPL_4=np.npv(rate=num_TMA, values=Hipotese_4)
VPL_5=np.npv(rate=num_TMA, values=Hipotese_5)
print(VPL_1)
print(VPL_2)
print(VPL_3)
print(VPL_4)
print(VPL_5)
vpla_1=(VPL_1)*((num_TMA*(1+num_TMA)**n_1)/((1+num_TMA)**(n_1-1)))
vpla_2=(VPL_2)*((num_TMA*(1+num_TMA)**n_2)/((1+num_TMA)**(n_2-1)))
vpla_3=(VPL_3)*((num_TMA*(1+num_TMA)**n_3)/((1+num_TMA)**(n_3-1)))
vpla_4=(VPL_4)*((num_TMA*(1+num_TMA)**n_4)/((1+num_TMA)**(n_4-1)))
vpla_5=(VPL_5)*((num_TMA*(1+num_TMA)**n_5)/((1+num_TMA)**(n_5-1)))
print()
print('vpla_1 (12 meses)')
print(vpla_1)
if vpla_1>0:
print(verde+'Viável')
else:
print(vermelho+'Inviável')
print(preto+'vpla_2 (24 meses)')
print(vpla_2)
if vpla_2>0:
print(verde+'Viável')
else:
print(vermelho+'Inviável')
print(preto+'vpla_3 (36 meses)')
print(vpla_3)
if vpla_3>0:
print(verde+'Viável')
else:
print(vermelho+'Inviável')
print(preto+'vpla_4 (48 meses)')
print(vpla_4)
if vpla_4>0:
print(verde+'Viável')
else:
print(vermelho+'Inviável')
print(preto+'vpla_5 (60 meses)')
print(vpla_5)
if vpla_5>0:
print(verde+'Viável')
else:
print(vermelho+'Inviável')
How I tried to convert it from cx:
from cx_Freeze import setup, Executable
setup(name='VPLA',
version='0.1',
description='Análise de viabilidade para aluguel de empilhadeiras
elétricas',
executables= [Executable("VPLA.py")])
Then went to the Anaconda CMD and typed:
python setup.py build
I currently doing this tic tac toe project, but I am stuck because it does not work, so I need help identifying what errors I made. In addition, I need to allow the user to choose one letter ("X" o "O") and the "X" goes first. I don't know how can I code this. I hope that someone help me, please.
This is the code that I have developed:
# Variables globales
# Tablero vacio
board = ["_", "_", "_",
"_", "_", "_",
"_", "_", "_",]
# Si juego continua
juego_continua = True # El juego continua desde el inicio.
# Quien gana o empata
ganador = None
# Turno asignado
actual_jugador = "X"
# Funcion que defin juego tic tac toe.
def jugar_juego (): #
display_board() # Se va a representar el tablero inicial en pantalla.
# Mientras el juego continua.
while juego_continua: # Booleano
# Definir un solo turno para un jugador arbitrario
handle_turn (actual_jugador)
# Verificar si se acabo el juego
verificar_si_termino_juego()
# Cambiar al otro jugador
cambio_jugador()
# El juego ha terminado
if ganador == "Jugador - X" or ganador == "Jugador - O":
print(ganador + "Ganaste.")
elif ganador == None:
print ("Hay empate.")
def display_board():
print ("\n")
print (board[0] + " | " + board[1] + " | " + board[2] + " 1 | 2 | 3")
print (board[3] + " | " + board[4] + " | " + board[5] + " 4 | 5 | 6")
print (board[6] + " | " + board[7] + " | " + board[8] + " 7 | 8 | 9")
print ("\n")
# Define un turno para el jugador arbitrariamente.
def handle_turn(jugador):
print(jugador + "turno.")
posicion = input("Elegir una posicion desde 1 hasta 9 para comenzar: ")
valid = False
while not valid:
while posicion not in ["1", "2", "3", "4", "5", "6", "7", "8" ]:
posicion = input("Por favor elegir una posicion desde 1 hasta 9 para jugar: ")
posicion = int(posicion) - 1
if board (posicion) == "_":
valid = True
else:
print ("Esta posición ya esta ocupada, elegir otra: ")
board[posicion] = jugador
display_board()
def verificar_si_termino_juego():
verificar_si_gano()
verificar_si_empate()
def verificar_si_gano():
# Establecer variable global
global ganador
# verificar filas
ganador_filas = check_filas()
# verificar columnas
ganador_columnas = check_columnas()
# verificar diagonales
ganador_diagonales = check_diagonales()
if ganador_filas:
ganador = ganador_filas
elif ganador_columnas:
ganador = ganador_columnas
elif ganador_diagonales:
ganador = ganador_diagonales
else:
#No hay ganador
ganador = None
def check_filas():
# Establecer variable global
global juego_continua
# Revisa si las filas son iguales, exceptuando "_"
fila_1 = board[0] == board[1] == board[2] != "_"
fila_2 = board[3] == board[4] == board[5] != "_"
fila_3 = board[6] == board[7] == board[8] != "_"
# Si alguna fila es igual, indica que hay un ganador
if fila_1 or fila_2 or fila_3:
juego_continua = False
# Devuelve el ganador (X o O)
if fila_1:
return board[0]
elif fila_2:
return board[3]
elif fila_3:
return board[6]
# Retorna ninguna si no hay ganador
else:
return None
def check_columnas():
# Establecer variable global
global juego_continua
# Revisa si las columnas son iguales, exceptuando "_"
columnas_1 = board[0] == board[3] == board[6] != "_"
columnas_2 = board[1] == board[4] == board[7] != "_"
columnas_3 = board[2] == board[5] == board[8] != "_"
# Si alguna columna es igual, indica que hay un ganador
if columnas_1 or columnas_2 or columnas_3:
juego_continua = False
# Devuelve el ganador (X o O)
if columnas_1:
return board[0]
elif columnas_2:
return board[1]
elif columnas_3:
return board[2]
else:
return None
def check_diagonales():
# Establecer variable global
global juego_continua
# Revisa si las diagonales son iguales, exceptuando "_"
diagonal_1 = board[0] == board[4] == board[8] != "_"
diagonal_2 = board[2] == board[4] == board[6] != "_"
# Si alguna diagonal es igual, indica que hay un ganador
if diagonal_1 or diagonal_2:
juego_continua = False
# Devuelve el ganador (X o O)
if diagonal_1:
return board[0]
elif diagonal_2:
return board[2]
else:
return None
def verificar_si_empate():
global juego_continua
if "_" not in board:
juego_continua = False
return True
else:
return False
def cambio_jugador():
global actual_jugador
# Si actual jugador fue X, luego cambia a O
if actual_jugador == "X":
actual_jugador = "O"
# Si actual jugador fue O, luego cambia a X
elif actual_jugador == "O":
actual_jugador = "X"
jugar_juego()
The indentation is incorrect.
Here is the updated code:
def handle_turn(jugador):
print(jugador + "turno.")
posicion = input("Elegir una posicion desde 1 hasta 9 para comenzar: ")
valid = False
while not valid:
while posicion not in ["1", "2", "3", "4", "5", "6", "7", "8" ,"9"]:
posicion = input("Por favor elegir una posicion desde 1 hasta 9 para jugar: ")
posicion = int(posicion) - 1
if board[posicion] == "_":
valid = True
else:
print ("Esta posicion ya esta ocupada, elegir otra: ")
board[posicion] = jugador
display_board()
Can some help me. I heave this code:
#Replace Incident Discription
def replace(line):
#Vul hier in waar je op zoekt, waar je het naar verandert wilt hebben, en hoever daarna de tekst moet beginnen die uit de FLEX gehaald word.
rename01 = "AUT.BR","Automatische brandmelding. ",71
rename02 = "BR GEBOUW","Brand gebouw. ",74
rename03 = "BR INDUSTRIE","Brand industrie. ",77
rename04 = "BR CONTROLE","Brand controle. ",76
rename05 = "BR BUITEN","Brand buiten. ",74
rename06 = "BR WEGVERVOER","Brand wegvervoerder. ",78
rename07 = "BR WONING","Brand woning. ",74
rename08 = "BR SPOORVERVOER","Brand spoorvervoerder. ",80
rename09 = "ONG WATER","Ongeval water. ",74
rename10 = "ONG LUCHTVAART","Ongeval luchtvaart. ",79
rename11 = "ONG SPOOR","Ongeval spoor. ",74
rename12 = "ONG WEG","Ongeval wegvervoerder. ",72
# Zoek de term op die gebruikt word in de melding. Vervang deze term en plak vanaf een bepaalde offset de melding tekst er achter.
if rename01[0].lower() in line.lower():
return rename01[1] + line[rename01[2]:]
elif rename02[0].lower() in line.lower():
return rename02[1] + line[rename02[2]:],
elif rename03[0].lower() in line.lower():
return rename03[1] + line[rename03[2]:]
elif rename04[0].lower() in line.lower():
return rename04[1] + line[rename04[2]:]
elif rename05[0].lower() in line.lower():
return rename05[1] + line[rename05[2]:]
elif rename06[0].lower() in line.lower():
return rename06[1] + line[rename06[2]:]
elif rename07[0].lower() in line.lower():
return rename07[1] + line[rename07[2]:]
elif rename08[0].lower() in line.lower():
return rename08[1]+ line[rename08[2]:]
elif rename09[0].lower() in line.lower():
return rename09[1] + line[rename09[2]:]
elif rename10[0].lower() in line.lower():
return rename10[1] + line[rename10[2]:]
elif rename11[0].lower() in line.lower():
return rename11[1] + line[rename11[2]:]
elif rename12[0].lower() in line.lower():
return rename12[1] + line[rename12[2]:]
elif rename13[0].lower() in line.lower():
return rename13[1] + line[rename13[2]:]
else:
return(line[63:])
I use this def to find a special text in a string that looks like:
"FLEX: 2017-07-10 07:45:34 1600/2/A 11.059 [001201972] ALN P 1 BR WONING Warwickstraat Steenbergen NB 201634 (inci-02)"
I search for "BR WONING" and want to change this is Brand woning. it wil return the text Brand woning. and then the rest of the sting that starts with flex with a different offset.
Wenn i test this def all seems to be good. But wenn a call this function an it is used in a other python project I get the fault: TypeError: can only concatenate tuple (not “str”) to tuple Error
second Python project:
print("Uitruk STB " + curtime()+replace(line)+groupid+' '),
I m looking for a easy fix so I can keep the code and only change small things.
Also ways to do it better is nice but first I would like to know what is going wrong.
Thank y
I need to do a limete of type 4 characters, with numbers it goes and does not return error, but with letters it returns that error as it is in the title. I need to limit from "0 to 9" and "A to D".
In the limiteUsuario() method, everything is ok.
from tkinter import *
import tkinter as tk
class loginUser:
def __init__(self, window, master=None):
self.wind = window
self.wind.title("System F2T")
#Definicoes de fonte p/ o layout de login
self.fonteTitulo = ("Arial","10","bold")
self.fontePadrao = ("Arial", "10")
self.var = StringVar() #create the var first before you assign them
self.var2 = StringVar()
#Labels e campos de texto do sistema de login
self.userLabel = Label(text="Digite seu usuário:", font=self.fontePadrao,bg="#000",fg="#FFF").place(x=27,y=60)
self.user = Entry(textvariable=self.var, font=self.fontePadrao,bg="#FFF",fg="#000")
self.user.place(x=140,y=60,width=110)
self.senhaLabel = Label(text="Digite sua senha:", font=self.fontePadrao,bg="#000",fg="#FFF").place(x=29,y=90)
self.senha = Entry(textvariable=self.var2, font=self.fontePadrao,bg="#FFF",fg="#000")
self.senha.place(x=140,y=90,width=110)
self.max_user = 1
self.var.trace("w", self.limiteUsuario)
self.max_senha = 4
self.var2.trace("w", self.limiteSenha)
def limiteUsuario(self,*args):
u = self.var.get()
if len(u) == 1 and not 65<=ord(u)<=68 and not 48<=ord(u)<=57: # you can also use *if not u in "ABCD"*
self.var.set("")
elif len(u) > 1:
if not 65<=ord(u[-1])<=68: # retirar ultimo caracter caso nao seja digito
self.var.set(u[:-1])
else: # aproveitar apenas os primeiros 5 chars
self.var.set(u[:self.max_user])
def limiteSenha(self,*args):
text = self.var2.get()
text = ''.join(char for char in text if char in 'ABCD')
if len(text) == 4 and not 65<=ord(text)<=68 and not 48<=ord(text)<=57: # you can also use *if not u in "ABCD"*
self.var2.set("")
elif len(text) > 4:
if not 65<=ord(text[-1])<=68: # retirar ultimo caracter caso nao seja digito
self.var2.set(text[:-1])
else: # aproveitar apenas os primeiros 5 chars
self.var2.set(text[:self.max_senha])
print(self.var2.set(text))
if __name__ == "__main__":
root = Tk()
root['bg'] = "#000"
loginUser(root)
#Tamanho da janela
root.geometry("330x200")
root.mainloop()
ord() can convert only single char - like ord("a") - but you have string with many chars - like ord("BXA7D")
You can use for loop to work with every char separatelly
text = "BXA7D" # text = self.var2.get()
text = ''.join(char for char in text if char in 'ABCD')
print(text) # self.var2.set(text)
# BAD
or longer
text = "BXA7D" # text = self.var2.get()
result = []
for char in text:
if char in 'ABCD':
result.append(char)
text = ''.join(result)
print(text) # self.var2.set(text)
# BAD
EDIT: I don't know what result exactly you want. Delete all string if there is ABCD0123456789 or remove only chars ABCD0123456789
This remove all string if there is char ABCD0123456789 or cut to 5 chars.
def limiteSenha(self,*args):
s = self.var2.get()
if len(s) > 5:
for char in s:
if char not in 'ABCD0123456789':
s = ""
break # exit for-loop because there is no need to check rest
self.var2.set(s[:self.max_senha])
elif len(s) == 5:
if not 65<=ord(s[-1])<=68: # retirar ultimo caracter caso nao seja digito
self.var2.set(s[:-1])
else: # aproveitar apenas os primeiros 5 chars
self.var2.set(s[:self.max_senha])