Python : Functions and Argument and Return


Functions :

In Python, a functions is a block code that only runs when it is called and when its called also you can also pass data known  as parameters into a function, and you return data as well in the form of a result. the way of creating a function in python is by using the Keywords "def" which is what defines it like the following:  

def my_function():

    print("Hello this is what a function is : )")

to call a function in python you would use a functions name followed by a parenthesis like the following:

Input:

def my_function():

    print("THIS IS HOW YOU DO A FUNCTION!")

my_function()

Output: THIS IS HOW YOU DO A FUNCTION!

Argument:

Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:

Example; 

def my_function(fname):

  print(fname + " Refsnes")

my_function("Emil")

my_function("Tobias")

my_function("Linus")

Number of Arguments:

By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

Example:

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):

  print(fname + " " + lname)

my_function("Emil", "Refsnes")

Specify a Variable Type

There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions:

  • int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)
  • float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)
  • str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals.

x = 1   # int 

 y = 2.8  # float 

 z = 1j   # complex 

 To verify the type of any object in Python, use the type() function: 

 Example:

print(type(x))

 print(type(y))

 print(type(z))

Leave a comment

Log in with itch.io to leave a comment.