-1

I'm trying to make a shifted letter encoder in python but for some reason it only went through the for loop once how can I fix this?

import string

uppercase = list(string.ascii_uppercase)
a = input("Your word: ")

def encode(str):
    for i in str:
        currentletterindex = uppercase.index(i)
        shifted = uppercase[currentletterindex+1]
        return shifted

print(encode(a))
martineau
  • 119,623
  • 25
  • 170
  • 301
Blue Duck
  • 56
  • 7
  • 4
    I'm not sure about what you're trying to achieve but there is a `return` statement inside your `for` loop so you will always exit the function during its first iteration. – Marc Dillar Jun 19 '21 at 23:50
  • When all else fails. review the [documentation](https://docs.python.org/3/reference/simple_stmts.html#the-return-statement) (of the `return` statement. – martineau Jun 20 '21 at 01:57

2 Answers2

0

nvm, I tried to run it without function and it works well

import string

uppercase = list(string.ascii_uppercase)
a = input("Your word: ")

for i in a:
    if i in uppercase:
        current_index = uppercase.index(i)
        shifted = uppercase[current_index+1]
        print(shifted, end='')
Blue Duck
  • 56
  • 7
0

The problem is caused by the return statement in the function. The return statement stops the function and makes it return the value. You should only call return when you are done with anything you need to do in that function. You could solve this by adding the output to a string.

Code:

import string

uppercase = list(string.ascii_uppercase)
a = input("Your word: ")

def encode(input_str):
    output_str = ""
    for letter in input_str:
        currentletterindex = uppercase.index(letter)
        shifted = uppercase[currentletterindex+1]
        output_str += shifted
    return output_str

print(encode(a))
KetZoomer
  • 2,701
  • 3
  • 15
  • 43