Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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 path

    def 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?



  • @gorgenasty

    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 of user_input, and all its work is discarded when it returns. When you f.write(user_input) you are saving its original value, from user_input = input().

    Your def lowercaser(text) needs to finish with a return text, to return the altered text. And your call needs to be user_input = lowercaser(user_input).


  • Lifetime Qt Champion

    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.


Log in to reply