1

Estoy haciendo un programa que mira si una string tiene mayusculas o minúsculas:

import string 
numbers   = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
letters   = string.ascii_lowercase
letters   = letters.split()
word      = input("Inserte una contraseña: ")
lowercase = False
uppercase = False

for i in word:
    for a in range(len(letters)): 
        c = letters[a]
        if i == c.upper():
            uppercase = True
    if uppercase == True:
        break
else:
    print("Pon una mayúscula")

for i in word:
  for a in range(len(letters)): 
    if i in letters:
      lowercase = True
      break
  if lowercase == True:
    break
else:
    print("Pon una minuscula")

Sin embargo siempre dice que no hay ni minúsculas ni mayusculas, y no se porque

1 respuesta 1

2

El problema está en que haces lo siguiente:

letters   = string.ascii_lowercase

esto retorna una cadena con todas las letras ASCII:

>>> print(letters)
'abcdefghijklmnopqrstuvwxyz'

Posteriormente haces:

letters   = letters.split()

Lo que retorna:

print(letters)
['abcdefghijklmnopqrstuvwxyz']

Cuando recorres tu cadena word lo que haces es comparar cada carácter con 'abcdefghijklmnopqrstuvwxyz' y 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', por lo que te retorna False siempre.

Para pasar una cadena a una lista cuyos items son los caracteres del string basta con hacer:

>>> letters   = string.ascii_lowercase
>>> letters = list(letters)`
>>> print(letters)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

No obstante, no necesitas las listas, en python puedes iterar directamente sobre los caracteres de un string con un for in o usando índices. Simplemente crea tus strings e itera sobre ellos:

numbers = string.digits
letters   = string.ascii_lowercase

Para iterar sobre un iterable usa for in, no uses range + indices (a no ser que modifiques el iterable durante el ciclo). El primer método es mucho más legible, corto, "Pythónico" y además, es considerablemente más eficiente.

Por otro lado, puedes simplificar tu código usando generadores y any:

import string 

word = input("Inserte una contraseña: ")

if not any(c in string.ascii_uppercase for c in word):
    print("Ingrese una mayúscula.")
if not any(c in string.ascii_lowercase for c in word):
    print("Ingrese una minúscula.")
if not any(c in string.digits for c in word):
    print("Ingrese un número.")

O usar str.isupper y str.islower, y str.sdigit:

word = input("Inserte una contraseña: ")

if not any(c.isupper() for c in word):
    print("Ingrese una mayúscula.")
if not any(c.islower() for c in word):
    print("Ingrese una minúscula.")
if not any(c.isdigit() for c in word):
    print("Ingrese un número.")

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.