I am having issues trying to get my code to print the last value of the range when I am running a loop. Here is the problem I was given with my code at the end:
JavaScript
x
37
37
1
start_character = "A"
2
end_character = "Z"
3
4
#You may modify the lines of code above, but don't move them!
5
#When you Submit your code, we'll change these lines to
6
#assign different values to the variables.
7
8
#Print all the letters from start_character to end_character,
9
#each on their own line. Include start_character and
10
#end_character themselves.
11
#
12
#Remember, you can convert a letter to its underlying ASCII
13
#number using the ord() function. ord("A") would give 65.
14
#ord("Z") would give 90. You can use these values to write
15
#your loop.
16
#
17
#You can also convert an integer into its corresponding ASCII
18
#character using the chr() function. chr(65) would give "A".
19
#chr(90) would give "Z". So, for this problem, you'll need
20
#to convert back and forth between ordinal values and
21
#characters based on whether you're trying to loop over
22
#numbers or print letters.
23
#
24
#You may assume that both start_character and end_character
25
#are uppercase letters (although you might find it fun to
26
#play around and see what happens if you put other characters
27
#in instead!).
28
29
30
#Add your code here! With the original values for
31
#start_character and end_character, this will print the
32
#letters from A to Z, each on their own line.
33
34
for char in range(ord(start_character), ord(end_character)):
35
for h in chr(char):
36
print(h)
37
Here is the output I receive:
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
I know I am missing something simple, and adding +1 to end_character didn’t work due to it not being a string.
Advertisement
Answer
I think you just need to make sure you are adding 1 to the ordinal, not the char. Additionally you don’t need the inner for
loop, all you need to do is cast the current index back to a character with chr()
:
JavaScript
1
3
1
for char in range(ord(start_character), ord(end_character)+1):
2
print(chr(char))
3