Hello,
I am trying to write a little program in python. It manipulates strings according to rules of a formal system. I have written each rule in the form of a function. The function works fine, it takes the input string, and changes it if it fits the rules. The problem is that the function will not let me access the new string outside of the function. I thought that was what the "return" did?
When I try to access the changed string outside of the function, it just uses the value of the string before it went into the function...
How do I "export" the changed string, so I can use it outside of the function that changed it? I sort of need to keep the variable name the same throughout the program. Here is the code for your bemusement. Keep in mind I am an absolute coding noob please
Code:
# first we set some variables
m = "M"
i = "I"
u = "U"
start_string = m + i # the string you begin with according to the book
print "You begin with", start_string # just because ;)
print
string = start_string
print "The Rules:"
print "Rule I: if string ends with 'I', add 'U'"
print "Rule II: if string is 'Mx', make it 'Mxx'"
print "Rule III: if 'III' occurs, make it 'U'"
print "Rule IV: if 'UU' occurs, drop it"
print
# start defining rules
# RULE I, if string ends with "I", add "U"
def rule_I(string):
x_string = string
char_string = x_string[-1]
if char_string == i:
x_string = x_string + u
string = x_string
print "Rule I: string is now:", string #prints "MIU" as it should...
return string # this does not appear to do anything
else:
print "Rule I does not apply here"
# run the original "MI" through the rules
print "First level iteration"
print
rule_I(string)
print string #this prints "MI", the string before it went into rule_I()
TIA
PS: i have ommited the other rules here, I want to get the first one working first...