Optimize code in Python

Asked

Viewed 491 times

4

I made the code below but I have the feeling that it can be improved and that maybe I’m turning it too much.

It is a code in which I have a text input and if it is not written in all uppercase letters I ask the person to write again, if it is correct it returns 'Texto correto.'

n = input('Digite o texto todo em maiúscula: ')
res = n.isupper()

while res != True:
  n = input('Texto errado, digite tudo em maiúscula: ')
  res= n.isupper()
  continue

if res == True:

  print('Texto correto!')

6 answers

6


It’s not really an optimization I just refactored your code.

n = input('Digite o texto todo em maiúscula: ')
while not n.isupper():
  n = input('Texto errado, digite tudo em maiúscula: ')
print('Texto correto!')

Code working on Repl.it

6

The two answers gave certain codes, but I’ll give my version because I hate it when it violates the DRY, even in small code because then one learns to always do so, so without repeating relevant parts and I think it would be the "most optimized" that one can do without getting unreadable or do some crazy:

while True:
    n = input('Digite tudo em maiúscula: ')
    if n.isupper():
        print('Texto correto')
        break

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

He doesn’t say he’s wrong, but there are currents that indicate that this is not even good for UX, why say there was a mistake without need, but if you want to do it:

while True:
    n = input('Digite tudo em maiúscula: ')
    if n.isupper():
        print('Texto correto')
        break
    else:
        print('Texto errado')

It doesn’t seem so simple anymore, but at least it doesn’t have two codes doing the same thing (which in this example is not complicated, but you will learn to avoid this tip ode).

5

A one-Liner for you:

f = lambda: input('Digite em maiúsculo: ').isupper() and 'Texto Correto!' or f()

To execute:

f()

5

You can do it like this:

n = input('Digite o texto todo em maiúscula: ')
while True:
    if n.isupper():
        print('Texto correto')
        break
    else:
        n = input('Texto errado, digite tudo em maiúscula: ')

while True creates a loop infinite, which is only interrupted by the break - which in turn only happens if n.isupper() return True. That is, if n.isupper() for True, he prints the message and leaves the while.

Note that if a value is boolean (as is the return of isupper), do not need to compare it with True or False, just put it directly as condition of the if.

In your case, if res != True could be written as if not res, as well as if res == True may simply be if res, but actually this variable res nor is it necessary.

If n.isupper return False, he falls in the else and asks you to type the text again.


Just remembering that isupper checks that all calls cased characteres of the string are uppercase, and there must be at least one of these in the string.

In the case, cased characters are those belonging to the Unicode categories "Letter, Uppercase", "Letter, Lowercase" and "Letter, Titlecase". But this does not mean that the string only contains these characters. For example, if the string is "1A" or "A, B", then isupper also returns True (the digit "1", the comma and the space are not cased characters, so are not checked).

2

From version 3.8 of Python you can use assignment Expression:

while not (texto := input('Digite um texto todo em maiúsculas: ')).isupper():
    print('Erro! Por favor, digite o texto com todas as letras maiúsculas')

print(f'Agora sim, você digitou: {texto}')

0

I found a lighter and simpler way, reducing the number of variables and putting the while in a single row:

n=input(f'Digite o texto todo em maiúscula: ')
while not n.isupper(): n=input(f'Texto errado, digite tudo em maiúscula: ')
print(f'Texto correto!')

I put f in print to use flash memory (not to weigh in RAM) and used the boolean state of n in uppercase directly in while. I hope I’ve helped!

  • 1

    Could you describe this detail better using the prefix f to use flash memory and not RAM? For the prefix f defines that the string can be interpolated, because it impacts the memory that will be used?

  • When you print a string, it goes into the RAM to be printed. However, when you put the f in front of the string, it stops going to the RAM and goes to the flash memory (faster) and is later printed on the screen. And that’s why the code gets faster when you put f in front of the string in print !!!

  • 1

    But what is the relation of f-strings to flash memory? Where did you read that this happens? There is the documentation link that states this?

  • Dude, I saw it in a video class about 2 or 3 years ago, when I was programming more in Arduino... Then, when I went to learn Python, I could use that too! I don’t know why, but it works!!!

  • 1

    Python does not work like that. The prefix f is to inform the interpreter that the string will be interpolated. It has no connection to the memory used.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.