Search code examples
pythonpython-3.xvariablesuser-inputgspread

Updating Variable from User Input


I am trying to make a program which the user enters contact information which is than stored in a Google Sheets document. The user enters their input, through the phrase:

def add_phone():
    contact_phone = input("Please enter the contact's phone number: ")

I use this to set the contact_phone variable, which is defined at the top of the document by contact_phone = ''. The problem is that when I try to send this information to the Google Sheets document

def store_info(contact_phone):
    worksheet.append_row(contact_phone)

It says

Traceback (most recent call last):
  File "/Users/user/PycharmProjects/contactList/main.py", line 46, in <module>
    add_contact()
  File "/Users/user/PycharmProjects/contactList/main.py", line 19, in add_contact
    store_info()
TypeError: store_info() missing 7 required positional arguments: 'contact_fname', 'contact_lname', 'contact_phone', 'contact_email', 'contact_address', 'contact_birthday', and 'contact_notes'

As you can see I am using more variables than just contact_phone but the same problem applies with all variables used (contact_fname, contact_lname, etc.) I was wondering if there was any way to update the variable from '' to the inputted variable (phone number) before I reach this step, without stopping the code.

I have tried setting the variable to itself after the input is inputted by the user (contact_phone = contact_phone), but I have had no success.


Solution

  • I figured out the answer. I started by defining global variables in my input functions: global contact_phone (as suggested by user: martineau).

    This didn't fix all of my problems though. I had one function that had all the steps, including the input functions and my function which sends/saves the information to the Google Sheet document. I realized that the variables wouldn't update until the function finished so I removed the Google Sheets function (which read the inputted variables) from the main function and called it on its own after I called my main function:

    add_contact()
    store_info()
    

    This lets the variables update to what the user inputted when the function would end. Then my next function (store_info) would be able to read the inputted variables and send these updated variables to the Google Sheet document, allowing them to be whatever is inputted by the user. Thanks to everyone who contributed!