-2

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.

Mason Caiby
  • 1,846
  • 6
  • 17
Haley
  • 23
  • 1
  • 2

5 Answers5

4

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.

Mason Caiby
  • 1,846
  • 6
  • 17
3

You can use the following idea:

A = 65 Z = 90

If you subtract ord('A') from the input, you reduce the range to [0, 25]

So, you need to define the output inside the range [0, 25]. To avoid getting out this range, you should use '%'.

char_input = input()
return chr((ord(char_input) - ord('A') + 1) % 26 + ord('A'))

it means that, giving the input, you will subtract the value of ord('A') to "fix" the range and, after that, add + 1. You will take % 26 to avoid getting out the range. After all of that, add ord('A') again.

0

The below method is using ascii_letters.

import string

// returns a string of all the alphabets
// abcdefghijklmnopqrstuvwxyz"

   result = string.ascii_letters 

// get the index of the input alphabet and return the next alphabet in the results string. 
// using the modulus to make sure when 'Z' is given as the input it returns to the first alphabet. 

   result[(result.index(alphabet.lower()) + 1) % 26].upper() 
Yatish Kadam
  • 454
  • 2
  • 11
  • The provided answer was flagged for review as a Low Quality Post. Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). This provided answer may be correct, but it could benefit from an explanation. Code only answers are not considered "good" answers. From [review](https://stackoverflow.com/review). – MyNameIsCaleb Sep 25 '19 at 20:50
  • @MyNameIsCaleb reason? – Yatish Kadam Sep 25 '19 at 20:57
  • **This provided answer may be correct, but it could benefit from an explanation. Code only answers are not considered "good" answers** Add an explanation for your answer and potentially links to the docs for the functions/methods you used if relevant. – MyNameIsCaleb Sep 25 '19 at 20:58
0

Hope this is what you are looking for

_chr = input('Enter character(A-Z): ')
if _chr == 'Z':
    print('A')
else:
    print(chr(ord(_chr) + 1))
Hansraj Das
  • 209
  • 4
  • 7
0
alpha=input()
if alpha =='Z': print('A')
else:print(chr(ord(alpha)+1))

"You will need to use an if statement"