Unsolved lowercasing function doesn't work in a different function
-
Please bear with me, I am new to Python.
The first function I wrote was one to lowercase any uppercase characters in a string that passed through it, which works by itself, while ignoring any non-uppercase alphabetical ASCII characters.
However, when I try to use it in my second function, (which SHOULD use the lowercasing function on whatever the user inputs and then sticks it in a file) I'm left with a file that contains the the string that's initially passed through without any of the lowercasing function.
import os.path
from os import pathdef lowercaser(text):
text = [ord(c) for c in text]
length = len(text)i = 0 while length != i: if 65 <= text[i] <= 90: text[i] = text[i] + 32 i += 1 text = [chr(c) for c in text] text = "".join(text)
def does_rfid_list_exist():
if path.exists("rfidList.txt"):
print("File found!")else: print("File was not located! Creating new file.\n") f = open("rfidList.txt", "a+") user_input = input("Please enter your name!\n") lowercaser(user_input) f.write(user_input) f.close()
does_rfid_list_exist()
I have no idea why they don't work together, and I've broken it down as far as I can. Any ideas?
-
def lowercaser(text): text = ... def does_rfid_list_exist(): user_input = input("Please enter your name!\n") lowercaser(user_input) f.write(user_input)
When you pass parameters to methods, Python works on a copy of the variable passed in. If the method changes that variable it does not affect the variable passed in by the caller --- that just retains its original value. So, here your
lowercaser()
makes its change to a copy ofuser_input
, and all its work is discarded when it returns. When youf.write(user_input)
you are saving its original value, fromuser_input = input()
.Your
def lowercaser(text)
needs to finish with areturn text
, to return the alteredtext
. And your call needs to beuser_input = lowercaser(user_input)
. -
Hi and welcome to devnet,
Why not just use Python str lower function ?
-
@SGaist
I assume this is learning exercise! :) He references a learning course he is doing.