0

I have written following code:

def  contalpha(n):
    num = 65
    for i in range(0, n):
        for j in range(0, i+1):
            ch = chr(num)
            print(ch, end=" ")
            num = num +1
        print("\r")
n = 7
contalpha(n)

The output is:

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 [ \ 

but what I want is:

A B C D E
A B C D
A B C 
A B 
A 

How can I make it?

3 Answers 3

2

I'd advise against using chr. Ascii can be confusing, instead just use a string of all capital ascii characters (which is a sequence of characters, and can be handily found in the string module).

import string

def contalpha(n):
    for i in range(n, 0, -1):
        print(*string.ascii_uppercase[:i], sep=' ')

contalpha(5)

outputs:

A B C D E
A B C D
A B C
A B
A
Sign up to request clarification or add additional context in comments.

3 Comments

I am not a Python programmer, so maybe I don't know something important here, but can you tell me what can be confusing in terms of ASCII and it's capital letters block?
I don't know about you, but to me string.ascii_uppercase is more obvious than [chr(i) for i in range(65, 91)]. Basically, don't reinvent the wheel.
Thanks for reply, this really a simple way
0

You need to reverse the range in order to start from the bigger row range(0, n)[::-1]. Then you need to set num = 65 every time you start a new row for it to always start from A.

There you go:

def  contalpha(n):
    num = 65
    for i in range(0, n)[::-1]:
        for j in range(0, i+1):
            ch = chr(num)
            print(ch, end=" ")
            num = num +1
        num = 65
        print("\r")
n = 7
contalpha(n)

Output

A B C D E F G 
A B C D E F 
A B C D E 
A B C D 
A B C 
A B 
A 

Comments

0

Try this:

def  contalpha(n):
    for i in range(n, 0, -1):
        num = 65
        for j in range(0, i):
            ch = chr(num)
            print(ch, end=" ")
            num = num +1
        print("\r")
n = 7
contalpha(n)

First you need to set num to 65 every outer loop to get alphabets from A again and second you should reverse outer loop range to print from max size to min size.

output:

A B C D E F G 
A B C D E F 
A B C D E 
A B C D 
A B C 
A B 
A

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.