Henry Chang
Henry Chang

Reputation: 86

Python changing a small part of the function

The purpose of this function is to encrypt and decrypt a text message:

def program(str):
    i = 0
    message = []
    while i < len(str):
        message.append(ord(str[i]))
        i += 1
    print(message)
program (text)

Is it possible to change the ord() call so I do not have to create a completely new function? Sort of like the str where I can re-enter a new string every single time I run the function.

Upvotes: 0

Views: 270

Answers (3)

KernelPanic
KernelPanic

Reputation: 600

I believe I understand what you want here. You want to be able to call program so it runs ord on each character in your string, but you also want to be able to run (for instance) chr on each character in your string without having to make a whole new function called program_chr.

Happily, Python supports first-class functions, so this is definitely possible. You can just pass a function as an argument to program, just as easily as you pass a string.

def program (my_str, my_fn):
    i = 0
    message = []
    while i<len(my_str):
        message.append(my_fn(my_str[i]))
        i += 1
    print(message)

program("my_string", ord)

This outputs [109, 121, 95, 115, 116, 114, 105, 110, 103], without ord ever appearing in program!

You can use any function for this, including ones you define yourself:

def silly_fn (char):
    return 12

program("my_string", silly_fn)

This outputs [12, 12, 12, 12, 12, 12, 12, 12, 12].


Relevant note: I changed the parameter str to my_str, because str is a built-in function, and it's never good practice to redefine those without good reason!

Upvotes: 1

Kumar Sambhav Pandey
Kumar Sambhav Pandey

Reputation: 1743

You question is not very clear but are you looking something like this ?

def program (str):
    i, j = 0, 0
    message = []
    for i in range(len(str)):
      while j<len(str[i]):
        message.append(ord(str[i][j]))
        j += 1
    print(message)

text1 = 'This is test1'
text2 = 'This is test2'
text3 = 'This is test3'
text4 = 'This is test4'

str_list = [text1,text2,text3,text4]

program (str_list)

This outputs

[84, 104, 105, 115, 32, 105, 115, 32, 116, 101, 115, 116, 49]

Upvotes: 0

Nairit
Nairit

Reputation: 163

Sorry if I did not interpret the question correctly; the wording is a bit confusing. I am assuming that when you said "completely new function", you meant "completely new loop". If you are asking whether or not it's possible to ditch the while loop completely, as far as I know, it is not possible. It is possible to use a for loop though.

for i in range(len(str)):
    message.append(ord(str[i]))

Again, sorry if I misinterpreted your question.

Upvotes: 0

Related Questions