Python Forum
Simple problem with functions and returns
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple problem with functions and returns
#1
Hello guys I hope You will be able to help me with these simple functions. I can not understand and I tried everything.I spent couple days, watched videos etc. My main problem is I don’t know how to pass the choice from "option" frrom main() to the started(operation), and I don’t know how I should use the operator in the other function. I will add some instructions to the code so everyone can understand what I am talking about. Thank You in advance guys. Please for understanding.

def menu():
    """
    Task 2: Display a menu of options and read the user's response.

    A menu consisting of the following options should be displayed:
    'Load Data', 'Process Data', 'Visualise Data', 'Save Data' and 'Exit'

    The user's response should be read in and returned as an integer corresponding to the selected option.
    For example, 1 for 'Load Data', 2 for 'Process Data' and so on.

    If the user enters a invalid option then a suitable error message should be displayed and the value
    None should be returned.

    :return: None if invalid selection otherwise an integer corresponding to a valid selection
    """
    # TODO: My code
    print("\nWhat would You like to do ?")
    print(" \n 1- Load Data\n 2- Process Data\n 3- Visualise Data\n 4- Save Data\n 5- Exit  ")
    option = int(input())
    if option == 1:
        return option
    if option == 2:
        return option
    if option == 3:
        return option
    if option == 4:
        return option
    if option == 5:
        return option
    else:
        print("Invalid selection")
        return





def started(operation):
    """
    Task 3: Display a message to indicate that an operation has started.

    The function should display a message in the following format:
    '{operation} has started.'
    Where {operation} is the value of the parameter passed to this function

    :param operation: A string indicating the operation being started
    :return: Does not return anything
    """
    # TODO: My code here
    operation =
    if operation == 1:
        print("Loading has started")
menu()
started()
buran write Mar-17-2021, 01:59 PM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#2
It will be easier to read your code on this forum if you use /python tags as described here: BBCode

Your function menu() is going to return either an integer value or None if the input is invalid. You could assign this value to a variable and then pass it to started(), or you could pass it directly:

# Assign the value returned by menu() to a variable and then call started()
op = menu()
started(op)

# Pass the value returned by menu() directly
started(menu())
Also, to simplify your code in the menu function, you can do just a single comparison to determine if the input is what you expect before returning. (Note that your current code would throw an error if the user enters a non-integer value, by the way.)

if 1 <= option <=5:
    return option
else:
    print("Invalid selection")
    return
Reply
#3
Sorry, next time I will paste how it should be

But still do not understand the question why first parameter is requested as integer and later as string? I should create if statement for example if op == 1 , print ("Loading has started) ?
Reply
#4
I'm not sure I understand your question at this point. The value returned by menu() is an integer (if input is valid), so that is what is being passed to started().

Assuming the user inputs a "1" when prompted, started(menu()) is the same thing as started(1). The argument passed in the function call is referenced within the function with the name operation.

def started(operation):
   print(f'The value of operation is {operation}.')

started(1)
Output:
The value of operation is 1.
Reply
#5
The problem is that I do not understand the task

I am told that the function should display a message {operation} has started.
but below that, I have :param operation: A string indicating the operation is started.

Does that mean it has to change from integer to a string? I have no clue that's my main problem
Reply
#6
I see what you are saying. The instructions say that your menu function should return an integer, but they also imply that the argument you pass to the started function should be a string. That doesn't make a lot of sense without a third function or other code to determine what string value to pass based on the integer returned by menu().

I'd suggest asking the person who gave the assignment to clarify what is expected. At some point in the code, you'll obviously need to associate 1 with "Loading", 2 with "Processing", etc. There are a variety of ways to do that, but it would help to know what your instructor is looking for.
Reply
#7
Thank You for your reply. Definitely, I will ask. I am glad that is not only me but the question is not clear.
Reply
#8
(Mar-17-2021, 12:10 PM)danlopek14q Wrote: Does that mean it has to change from integer to a string? I have no clue that's my main problem
Your menu() function should return int. Based on value returned from menu() you need to decide what operation (str) to pass as argument to your function started(). Have you learned about dict or other data structures?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
not yet . I tried to do it like this :

def menu():
  print("\nWhat would You like to do ?")
  print(" \n 1- Load Data\n 2- Process Data\n 3- Visualise Data\n 4- Save Data\n 5- Exit  ")
  option = int(input())
  if option == 1:
    return option
  if option == 2:
      return option
  if option == 3:
      return option
  if option == 4:
      return option
  if option == 5:
      return option
  else:
      print("Invalid selection")
      return


def started (operation):
    operation = menu()
    if operation <= 4 :
      #IS that ok format for message ?
        print(f"{operation} A string indicating the operation being started ") 
    if operation == 1 :
       operation = "Loading data"
      # Or that one is correct ?
       print (f"{operation} has started ") 

started(menu)
Reply
#10
On line 30, when you call started(menu) without parentheses after menu, you are passing in the function itself rather than its return value. To pass the value that is returned by the function, you need to include the parentheses like started(menu()). This calls the menu function and passes its return value to the started function.

Within the started function, there is no need for operation = menu() on line 21 if you pass the return value on line 30 as described above.

To get from an integer like "1" to a string like "Loading data", the most efficient approach would be to use some type of collection variable like the dict suggested by buran. Since you indicated that you haven't learned about those yet, something like you have in lines 25-28 would also work.

def menu():
    print("\nWhat would You like to do ?")
    print(" \n 1- Load Data\n 2- Process Data\n 3- Visualise Data\n 4- Save Data\n 5- Exit  ")
    option = int(input())
    if option == 1:
        return option
    if option == 2:
        return option
    if option == 3:
        return option
    if option == 4:
        return option
    if option == 5:
        return option
    else:
        print("Invalid selection")
        return
 

def started(operation):
    if operation == 1 :
        operation = "Loading data"
    elif operation == 2:
        operation = "Processing data"
    # And so on, for the rest of the available options...
    # Don't forget to account for the possibility of None being returned by menu()
   
    print (f"{operation} has started ") 
 

started(menu())
There are several places the code could be refactored to be more efficient and/or avoid unnecessary repetition, but this seems to accomplish what is being asked. However, if your started function is expected to take a string as its argument, you would need to determine what string to pass first:

# Assume menu() is defined the same as above

def started(operation):
    # This function now just takes a string argument and prints the "has started" message. 
    print (f"{operation} has started ") 
 

choice = menu()  # Stores the integer or None value returned by menu() in the variable named choice

# Determine what string to pass to started() based on the value of choice.
# This could potentially be done in a function instead.
if choice == 1 :
    op_string = "Loading data"
elif choice == 2:
    op_string = "Processing data"
# And so on....

# Finally, pass the string value to the started() function to be printed
started(op_string)
Again, there are better ways to do some of this, but I'm trying to keep the code as simple as possible while maintaining what you've already written.

*EDIT* - Your indentation is not consistent between functions, you should always use 4 spaces for indents.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Functions and if elif problem Bruizeh 2 3,695 Aug-27-2021, 03:37 AM
Last Post: naughtyCat
  simple function problem stereokim123 5 3,214 Aug-26-2021, 04:44 PM
Last Post: naughtyCat
  I have a simple problem ahmed 5 2,450 Jul-17-2021, 02:50 PM
Last Post: ahmed
  Functions returns content of dictionary as sorted list kyletremblay15 1 2,005 Nov-21-2019, 10:06 PM
Last Post: ichabod801
  Problem with a simple script Niko047 2 3,299 Jul-21-2017, 09:02 PM
Last Post: Niko047

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020