Print characters to a given letter and include line breaks at the end

Asked

Viewed 193 times

-1

Create a program that receives an uppercase alphabetic character as input and displays the alphabet sequence from 'A' to the read character. The program must repeat the procedure until the character 'F is entered'.

Input format

A capital alphabetic character [ 'A' .. 'Z' ].

Z
B
C
W
E
F

Output format

For each character given as input, a line with the alphabetical sequence uppercase from 'A' to the given character, separated by a space.

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 
A B 
A B C 
A B C D E F G H I J K L M N O P Q R S T U V W 
A B C D E

Code created since then, below:

letra = input()
letra = ord(letra)

while letra != 70:
    for i in range(65,letra+1):
        print(chr(i),end=' ')
    letra = input()
    letra = ord(letra)

Even works, but does not give the expected output with line break.

2 answers

1

To perform line breaking, simply add a print() empty before getting user input or using the special character "\n" within the function input().

See the code below:

letra = input()
letra = ord(letra)

while letra != 70:

    for i in range(65, letra + 1):
        print(chr(i), end = ' ')
    print()

    letra = input()
    letra = ord(letra)

There is a more beautiful and idiomatic way of printing the letters that would be to create a list with the characters and then deconstruct it in the call of the print(). Thus, it will not be necessary to specify the spacing at the end of the printing.

chars = [chr(id_) for id_ in range(65, char + 1)]
print(*chars)

There’s also another problem with your code, which doesn’t make any mistakes, but maybe it’s not something you’d like to happen. As the goal of the program is to receive and display uppercase letters, what would happen if the user inserted a lowercase letter ?

The answer is that the program would print all uppercase letters and would only stop until it reached the lowercase letter. So you can use the method upper() to capitalize the user input.

Below is the refactored code I made:

def show_chars(char):
    chars = [chr(id_) for id_ in range(65, char + 1)]
    print(*chars)

while True:
    char = ord(input("Letra: ").upper())
    if char == 70: break
    show_chars(char) 
  • 2

    Not more beautiful shape, idiomatic form or if you want to be informal when commenting use pythonic form.

  • Hey Augusto, speaking in idiomatic form I have a question. It is correct to use a code of if on the same line as I did in the reply or it is better to always put the indented code below ?

  • Jean, I’m not a purist at this point, I use the way you did. Who could better answer it is the staff of the academic or personal area most committed to the theoretical part. I have myths CPD addictions, in production we often take shortcuts to save time and that the staff of Academia calls my attention in my answers.

1


First, eliminate the repetitions of your code. There’s no reason to call input before the while and then inside it. Just do it once and use it inside the main loop. In fact, since the program must accept only one letter from "A" to "Z", you can create a function to do this validation separately:

def ler_letra():
    while True:
        letra = input()
        if len(letra) == 1 and 'A' <= letra <= 'Z':
            return letra
        else: print('Digite uma letra de A a Z')

while True:
    letra = ler_letra()
    if letra == 'F':
        break
    print(' '.join(chr(i) for i in range(65, ord(letra) + 1)))

The function ler_letra checks whether what was typed is in fact a letter from "A" to "Z". If not, it asks to be typed again, and only returns when typed (while True creates a loop infinity that repeats itself until a valid letter is typed, and only in this case leaves the function with return). It is important to check this, because if a string with more than one character is typed, ord error (and if it is not a letter, it is no use to continue with the algorithm).

Then I make one loop infinite reading the letter and checking if it is "F" (and if it is, the break interrupts that loop). If it’s not "F," print the letters and the loop continues.

To print, I used join to join the letters, separating them with space. To generate the letters, I used a Generator Expression, much more succinct and pythonic. With this the letters are printed with a space between them, and the line break is already added at the end.

But of course you can also use your loop adding a print() after the for, as suggested in another answer - the difference is that when using end=' ', an extra space is added at the end, and this may or may not make a difference (for an exercise it may not do, but there are cases where it does - for example, if the output of one program is read by another, a more or less space can make a difference in processing - it may seem like a silly detail, but programming is full of these details and it’s important to get used to itwith them from now on).


But of course, if you do not need to validate that the entered value is a letter (because it is an exercise, can be that all entries are valid, as it has not been asked to validate), and if the extra space at the end of the lines makes no difference, then it could simply be:

while True:
    letra = input()
    if letra == 'F':
        break
    for i in range(65, ord(letra) + 1):
        print(chr(i), end=' ')
    print()

Note that you don’t need to ask for the input before the loop. Just do the while True (repeating "indefinitely"), and stopping it if "F".


A more generic solution would be to have a list of valid letters, and when printing you create a sub-list that goes to the index of the indicated letter:

def ler_letra(letras_validas):
    while True:
        letra = input()
        if letra in letras_validas:
            return letra
        else: print('Digite uma letra válida')

from string import ascii_uppercase
maiusculas = list(ascii_uppercase)

while True:
    letra = ler_letra(maiusculas)
    if letra == 'F':
        break
    print(' '.join(maiusculas[:maiusculas.index(letra) + 1]))

In that case I used ascii_uppercase, which already has all the uppercase letters from A to Z in order, but the above code can be used for any character list you want, leaving the code a little more generic (since the previous solutions are specific to the letters from A to Z).

So I no longer need to test if the size of the typed string is 1, because now it is enough to check if it is in the list (by the way, now the list can contain strings of varying sizes that will work the same way).

Browser other questions tagged

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