Python User-Defined Functions

Imagine you want to create a square with sides of a particular length. Additionally, you want to color it. You can create two separate functions to perform the above tasks. The first function will make a square of the specified length. You can use the second function to color it based on the specifications. Thus, as we can understand, a function is used to perform a specific task. If you define the function yourself, it is a user-defined function. On the other hand, the Python function that come along with Python are known as in-built functions. All the functions apart from in-built functions and library functions come under the category of user-defined functions. You can give any name to a user-defined function. The only restriction is that the name should not be a Python keyword.

Advantages of User-Defined Functions in Python

Once you define a function, you will have to call it to use it.  Since we are customizing the definition depending on our requirements, there are several advantages of a user-defined function over other Python functions. A few of them are:-

  • Firstly, a user-defined function helps to break the code into smaller blocks. Thus, it will be easy for a programmer to understand the functionality of each section. Additionally, it will be easier for maintenance purposes. In case any bug is present, debugging a smaller segment will be easier compared to debugging a large block of code.
  • Secondly, as mentioned above, we can modify a user-defined function as per our requirements. Thus, a user-defined function helps us create definitions that are not a part of the in-built Python function It can help to cater to our needs.
  • Most programs have certain repetitive sections of code. A user-defined function allows us to write the code for such parts of the code. Once the user-defined function is defined, you will need to call the function to execute the section. Thus, the overall effort required to complete the program reduces.
  • Additionally, the division of the program into smaller modules allows the option to divide the work among team members.
  • A user-defined function also promotes the concept of data hiding.

A function in Python can be assigned to a variable or stored in the form of a collection. Users can pass arguments through functions as well. All the aforementioned features allow flexibility to the programmers.

Example of a User-Defined Function

We can use the keyword ‘def’ to create a function. Below is an example of a user-defined function to multiply to two numbers (say ‘A’ and ‘B)

				
					#Program to demonstrate how to multiply two numbers using a user-defined function



def multiply_numbers(a,b):

   product = a * b

   return product



n1 = 5

n2 = 6



print("The product is", multiply_numbers(n1, n2))

				
			

In the above example, the multiply_numbers is a user-defined function. The function can accept two numbers in the form of arguments as it has been defined with two parameters. Within the print() function, we are calling the function to multiply the two numbers by passing n1 and n2 as arguments. Here, print() is an in-built Python function. Thus, we do not need to define the function. A good practice is to name the functions based on the tasks that they will be performing. It will be easier to identify them later on.

The Output of the above Program

				
					Enter a number: 5

Enter another number: 6

The product is 30

				
			

Function Completed

Method - Actions()

#lowercase

				
					#variable.method()
#string.method()
# to covert all characters in lowercase at once by using variable method is .lower()

name="MASTER TECH"
print(name .lower())

output : kundan
 # To convert all characters in uppercase at once by using string method is . lower()
 print ("MASTER TECH".lower())
 output: master tech
				
			

#uppercase

				
					# To convert all charcters in uppercase at once by using variable method is , upper()
 
 name= "Aptech Learning"
 print(name.upper())
 
 OUTPUT:APTECH Learning
 # To convert all charcters in uppercase at once by using string method is .upper()
 print("APTECH LEARNING".upper())
 OUTPUT: APTECH LEARNING
				
			

#capitalize

				
					# To capitialize the first character of all words .capitalize()

name = "aptech learning"
print(name.capitalize())

OUTPUT: Aptech learning
				
			

#title

				
					# To convert the characters into a title by using .title()

name = "Master tech Education"
print(name.title())

OUTPUT: Master tech Education
				
			

#replace

The .replace method is used to replace a part of the string with another string. It takes the portion to be replaced and the rep

SYNTAX : variable.replace(old text,new text)

				
					today = "Sunday"
  print(today.replace("Sun","Mon"))
  
				
			
				
					Output : Monday
				
			

#split

				
					print("Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(","))
				
			
				
					['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
				
			

Type Error, Type Conversion & Type Checking

				
					len(123456)
				
			
				
					Run Output:TypeError:object of type'int'has no len()
				
			
				
					Solution : len("123456")
				
			
				
					num_char = len(input("Enter your name"))
print("your name has "+ num-char + "charaters")
Run Output: TyeError:can only concatenatestr(not"int")to concatenatestr
Solution:

num_char =len(input("Enter your name"))
new_char = str(num_char)
print("your name has" + new_char + "charaters")
				
			

Python Variables

. In Python, you can declare and use variables in a simple and intuitive way. Here are some examples of variables in Python:

  • Integer:
  • Float:
  • String:
  • Boolean:
  • List:
  • Tuple:
  • Dictionary:

By learning how to use variables, you can start building more complex programs in Python.

Integer = int() in python

In Python, integers are classified into zero, positive, or negative whole numbers with no fractional part and infinite precision, such as 0, 100, -10, and so on. If there is a decimal, it is considered as a float variable. The int class includes all integer literals and variables.

Example-

Syntax of int() in Python

The syntax of the method, int() in Python is very simple:

				
					int(value, base)
				
			

The value parameter is required, but the base parameter is optional.

Parameters of int() in Python

The method – int() in python takes two parameters, one optional and the other required. The parameters given in int in python are:

  1. value: The value parameter is a required parameter. The valueis the number or string to be converted into an integer object.
  2. base: The base parameter is optional. The default value specified is 10. The base-10 value resembles the number having base address 10, i.e. decimal numbers.

We can specify the base type of the number other than 10, such as

  • 8 for octal number (to convert octal number into an equivalent decimal number).
  • 16 for hexadecimal number (to convert a hexadecimal number into an equivalent decimal number).
  • 2 for binary number (to convert the binary number into an equivalent decimal number).

 

Return Values of int() in Python

The int in python returns the integer object value of the given string or floating number. If we do not give any parameter in the method, it will return 0.

Exception of int() in Python

The int() in python raises an error whenever we pass a data type other than a string or an integer. For example, if we try to typecast a list using int in python. The following error will be printed:

				
					TypeError: int() argument must be a string, a bytes-like object, or a number, not 'list'
				
			

This exception raised by int() in python is known as TypeError. Refer to this article’s topic – More Example to know more about the exceptions.

Example:-

Let us convert a floating-point number into an integer using the method int() in python.

				
					floating_number = 5.5
integer_number = int(floating_number)
print("Integer number is:",integer_number)

				
			

Output:-

				
					Integer number is: 5
				
			

Float in python ?

Float is a function or reusable code in the Python programming language that converts values into floating point numbers. Floating point numbers are decimal values or fractional numbers like 133.5, 2897.11, and 3571.213, whereas real numbers like 56, 2, and 33 are called integers. Using the float function in Python on a specific value will convert it into a decimal number or fractional form. In simple terms, the purpose of the float function in Python is to convert real numbers or integers into floating point numbers.

Python float()

The float() method returns a floating point number from a number or a string.

Example:-

				
					int_number = 25

# convert int to float
float_number = float(int_number)

print(float_number)

# Output: 25.0

				
			

Float() Syntax:-

The syntax for float() is:-

				
					float([x])
				
			

Float() Parameters

  • x (Optional) – number or string that needs to be converted to floating point number
    If it’s a string, the string should contain decimal points

Parameter Type

Usage

Float number

Use as a floating number

Integer

Use as an integer

String

Must contain decimal numbers. Leading and trailing whitespaces are removed. Optional use of “+”, “-” signs. Could contain NaN, Infinity, inf (lowercase or uppercase).

Float() Return Value

The float() method returns:

  • Equivalent floating point number if an argument is passed
  • 0.0 if no arguments passed
  • Overflow Error exception if the argument is outside the range of Python float

Example :- How float() works in Python?

				
					# for integers
print(float(10))

# for floats
print(float(11.22))

# for string floats
print(float("-13.33"))


# for string floats with whitespaces
print(float("     -24.45\n"))


# string float error
print(float("abc"))
Run Code

				
			

Output:-

				
					10.0
11.22
-13.33
-24.45
ValueError: could not convert string to float: 'abc'

				
			

String in python ?

Python Strings

In Python, a string is a sequence of characters. For example, “hello” is a string containing a sequence of characters ‘h’, ‘e’, ‘l’, ‘l’, and ‘o’.

We use single quotes or double quotes to represent a string in Python. For example,