user3977009x
user3977009x

Reputation: 71

How to print an incrementing character

In Python, I am trying to build a function that will print a letter and a series of random numbers on a line. The number of lines printed will be between 1-10, dependent on user input. The end result should look like this:

A 10 11 15 20 40 (actual numbers will vary, between 1-69)
B 12 15 19 30 45 
etc..

My problem is getting the first character to print. I can't seem to find a way to increment the character so that the next line is B, the next after that is C, etc.

Here is what I have:

def generateLetter():
    value = 'A'
    newVar = (chr(ord(value[0])+1))
    value = newVar
    print(value)

def main():
    howMany = input('print how many lines?')
    count = 0
    while howMany > 10:
        if count == 3:
            break;
            count +=1
    if howMany <=10:
        print ('now printing ', howMany, 'lines')
    for each in range (howMany):
        generateLetter(),
        #another function to generate random string of numbers

Currently, the above results in this:

B
5 6 7 8 9
B
10 11 12 13 14
etc...

What am I doing wrong?

Upvotes: 0

Views: 81

Answers (2)

Prune
Prune

Reputation: 77847

If you're allowed to use a global variable, you can stash the value there. Also, don't increment it until you've used "A" in the first call. Usually, this is done with a Class variable instead of a global, but you don't have a Class around this.

value = 'A'
def generateLetter():
    global value
    print(value)
    value = (chr(ord(value[0])+1))

Upvotes: 1

Chuancong Gao
Chuancong Gao

Reputation: 660

You code in function generateLetter always print B. You need to pass a parameter indicating the the current step to the function.

Try this:

def generateLetter(i):
    print(chr(ord('A') + i))

def main():
    ...
    for each in range(howMany):
        generateLetter(each)
        ...

Upvotes: 0

Related Questions