pythonif-statementchrord

How to increment letters in Python?


Write a program that takes a character as input (a string of length 1), which you should assume is an upper-case character; the output should be the next character in the alphabet. If the input is 'Z', your output should be 'A'. (You will need to use an if statement.) So far I've tried several codes like this:

chr = input()
if chr == '65':
        x = chr(ord(chr) + 1)
print(chr(65) + 1)

It says it prints with no output, just unsure how to get to the the right output. Im very new to programming.


Solution

  • This should work:

    my_chr = ord(input())
    if my_chr == 90:
            print('A')
    else:
        print(chr(my_chr+1))
    

    It takes the input letter (A-Z) and gets its ord() value. It then checks to see if the value is equal to Z (ord('Z') == 90) and prints A otherwise, it increments it by 1 then turns it back to a string and prints it.