Tuesday, November 22, 2022

[FIXED] How do you impose restrictions on function arguments in Python?

Issue

I am writing a function to plot a graph. The problem is, there are restrictions on the inputs of the function that I am unsure how to put into code. For example, in

def PlotGraph(data, sex, c_list, status='current'):

The restrictions that I need to impose are the following:

  1. The PlotGraph function must accept either sex or c_list as in input, but not both. Sex is a string that can only be 'male' or 'female' and c_list is a list of integers.

  2. Status must be either 'current' or 'previous', but defaulted at 'current', which I have implemented.

For (1) I have searched around but cannot find a method as to how only one of the two types of data can be inputted AND to impose what the variable type of either input must be. For (2) I have an idea to include in the function

if status != 'current' or 'previous': 
    print("Invalid input") 

But I'm not sure if this will work if no input is submitted for status. If you have any ideas on how I can implement the stated restrictions, it would be much appreciated. Thank you.


Solution

In your given function signature, you have both sex and c_list as required positional arguments; this signature prohibits accepting a call with only one of them. Instead, try a single argument for both:

def PlotGraph(data, key, status='current'):
    if type(key) == int:
        sex = key
    elif type(key) == list:
        c_list = key
    else:
        print ("invalid key argument")

YOu have the right idea for checking status, except that you need to learn how to check against multiple values.



Answered By - Prune
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.