0% found this document useful (0 votes)
3 views21 pages

M1 Unit3

The document discusses Python type conversion, detailing implicit and explicit conversions with examples. It explains how to define and call functions, handle arguments, and utilize Python's built-in math functions and modules. Additionally, it covers importing functions from other files for code reusability.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views21 pages

M1 Unit3

The document discusses Python type conversion, detailing implicit and explicit conversions with examples. It explains how to define and call functions, handle arguments, and utilize Python's built-in math functions and modules. Additionally, it covers importing functions from other files for code reusability.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

BA 405: Unit 3: Python Type Conversion

Compiled By
Dr. Meghdoot Ghosh MBA, M.Sc, UGC(NET), Ph.D

In programming, type conversion is the process of converting data of one


type to another. For example: converting int data to str.
There are two types of type conversion in Python.

 Implicit Conversion - automatic type conversion

 Explicit Conversion - manual type conversion

Python Implicit Type Conversion

In certain situations, Python automatically converts one data type to


another. This is known as implicit type conversion.

Example 1: Converting integer to float

Let's see an example where Python promotes the conversion of the lower
data type (integer) to the higher data type (float) to avoid data loss.

integer_number = 123
float_number = 1.23

new_number = integer_number + float_number

# display new value and resulting data type


print("Value:",new_number)
print("Data Type:",type(new_number))

Output

Value: 124.23
Data Type: <class 'float'>
In the above example, we have created two
variables: integer_number and float_number of int and float type
respectively.
Then we added these two variables and stored the result in new_number.

As we can see new_number has value 124.23 and is of the float data
type.
It is because Python always converts smaller data types to larger data
types to avoid the loss of data.

Note:
 We get TypeError, if we try to add str and int. For example, '12' + 23.
Python is not able to use Implicit Conversion in such conditions.
 Python has a solution for these types of situations which is known as
Explicit Conversion.

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to


required data type.

We use the built-in functions like int(), float(), str(), etc to perform
explicit type conversion.
This type of conversion is also called typecasting because the user casts
(changes) the data type of the objects.

Example 2: Addition of string and integer Using Explicit

Conversion
num_string = '12'
num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion


num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))

Output

Data type of num_string before Type Casting: <class 'str'>


Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>

In the above example, we have created two


variables: num_string and num_integer with str and int type values
respectively. Notice the code,

num_string = int(num_string)

Here, we have used int() to perform explicit type conversion


of num_string to integer type.
After converting num_string to an integer value, Python is able to add
these two variables.
Finally, we got the num_sum value i.e 35 and data type to be int.

Key Points to Remember


1. Type Conversion is the conversion of an object from one data type to
another data type.

2. Implicit Type Conversion is automatically performed by the Python


interpreter.

3. Python avoids the loss of data in Implicit Type Conversion.

4. Explicit Type Conversion is also called Type Casting, the data types of
objects are converted using predefined functions by the user.
5. In Type Casting, loss of data may occur as we enforce the object to a
specific data type.

Python Functions
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()

Arguments
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")

Arguments are often shortened to args in Python documentations.

Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function


definition.

An argument is the value that is sent to the function when it is called.

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")
If you try to call the function with 1 or 3 arguments, you will get an error:

Example
This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil")

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access the
items accordingly:

Example
If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Arbitrary Arguments are often shortened to *args in Python documentations.

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")


The phrase Keyword Arguments are often shortened to kwargs in Python
documentations.

Arbitrary Keyword Arguments, **kwargs


If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the
function definition.

This way the function will receive a dictionary of arguments, and can access
the items accordingly:

Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:

def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

Arbitrary Kword Arguments are often shortened to **kwargs in Python


documentations.

Default Parameter Value


The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the
function.

E.g. if you send a List as an argument, it will still be a List when it reaches
the function:

Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Return Values
To let a function return a value, use the return statement:

Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

The pass Statement


function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to avoid
getting an error.
Example
def myfunction():
pass

Positional-Only Arguments
You can specify that a function can have ONLY positional arguments, or ONLY
keyword arguments.

To specify that a function can have only positional arguments, add , / after
the arguments:

Example
def my_function(x, /):
print(x)

my_function(3)

Without the , / you are actually allowed to use keyword arguments even if
the function expects positional arguments:

Example
def my_function(x):
print(x)

my_function(x = 3)

But when adding the , / you will get an error if you try to send a keyword
argument:

Example
def my_function(x, /):
print(x)

my_function(x = 3)
Keyword-Only Arguments
To specify that a function can have only keyword arguments,
add *, before the arguments:

Example
def my_function(*, x):
print(x)

my_function(x = 3)

Without the *, you are allowed to use positionale arguments even if the
function expects keyword arguments:

Example
def my_function(x):
print(x)

my_function(3)

But when adding the *, / you will get an error if you try to send a positional
argument:

Example
def my_function(*, x):
print(x)

my_function(3)

Combine Positional-Only and Keyword-


Only
You can combine the two argument types in the same function.

Any argument before the / , are positional-only, and any


argument after the *, are keyword-only.
Example
def my_function(a, b, /, *, c, d):
print(a + b + c + d)

my_function(5, 6, c = 7, d = 8)

Python Math
Python has a set of built-in math functions, including an extensive math
module, that allows you to perform mathematical tasks on numbers.

Built-in Math Functions


The min() and max() functions can be used to find the lowest or highest value
in an iterable:

Example
x = min(5, 10, 25)
y = max(5, 10, 25)

print(x)
print(y)

The abs() function returns the absolute (positive) value of the specified
number:

Example
x = abs(-7.25)

print(x)

The pow(x, y) function returns the value of x to the power of y (xy).

Example
Return the value of 4 to the power of 3 (same as 4 * 4 * 4):

x = pow(4, 3)

print(x)
The Math Module
Python has also a built-in module called math, which extends the list of
mathematical functions.

To use it, you must import the math module:

import math

When you have imported the math module, you can start using methods and
constants of the module.

The math.sqrt() method for example, returns the square root of a number:

Example
import math

x = math.sqrt(64)

print(x)

The math.ceil() method rounds a number upwards to its nearest integer, and
the math.floor() method rounds a number downwards to its nearest integer,
and returns the result:

Example
import math

x = math.ceil(1.4)
y = math.floor(1.4)

print(x) # returns 2
print(y) # returns 1

The math.pi constant, returns the value of PI (3.14...):

Example
import math

x = math.pi
print(x)

Python math Module


Python has a built-in module that you can use for mathematical tasks.

The math module has a set of methods and constants.

Math Methods
Method Description

math.acos() Returns the arc cosine of a number

math.acosh() Returns the inverse hyperbolic cosine of a number

math.asin() Returns the arc sine of a number

math.asinh() Returns the inverse hyperbolic sine of a number

math.atan() Returns the arc tangent of a number in radians

math.atan2() Returns the arc tangent of y/x in radians

math.atanh() Returns the inverse hyperbolic tangent of a number

math.ceil() Rounds a number up to the nearest integer

math.comb() Returns the number of ways to choose k items from n


items without repetition and order

math.copysign() Returns a float consisting of the value of the first


parameter and the sign of the second parameter
math.cos() Returns the cosine of a number

math.cosh() Returns the hyperbolic cosine of a number

math.degrees() Converts an angle from radians to degrees

math.dist() Returns the Euclidean distance between two points (p


and q), where p and q are the coordinates of that point

math.erf() Returns the error function of a number

math.erfc() Returns the complementary error function of a number

math.exp() Returns E raised to the power of x

math.expm1() Returns Ex - 1

math.fabs() Returns the absolute value of a number

math.factorial() Returns the factorial of a number

math.floor() Rounds a number down to the nearest integer

math.fmod() Returns the remainder of x/y

math.frexp() Returns the mantissa and the exponent, of a specified


number

math.fsum() Returns the sum of all items in any iterable (tuples,


arrays, lists, etc.)

math.gamma() Returns the gamma function at x

math.gcd() Returns the greatest common divisor of two integers

math.hypot() Returns the Euclidean norm


math.isclose() Checks whether two values are close to each other, or
not

math.isfinite() Checks whether a number is finite or not

math.isinf() Checks whether a number is infinite or not

math.isnan() Checks whether a value is NaN (not a number) or not

math.isqrt() Rounds a square root number downwards to the nearest


integer

math.ldexp() Returns the inverse of math.frexp() which is x * (2**i) of


the given numbers x and i

math.lgamma() Returns the log gamma value of x

math.log() Returns the natural logarithm of a number, or the


logarithm of number to base

math.log10() Returns the base-10 logarithm of x

math.log1p() Returns the natural logarithm of 1+x

math.log2() Returns the base-2 logarithm of x

math.perm() Returns the number of ways to choose k items from n


items with order and without repetition

math.pow() Returns the value of x to the power of y

math.prod() Returns the product of all the elements in an iterable

math.radians() Converts a degree value into radians

math.remainder() Returns the closest value that can make numerator


completely divisible by the denominator

math.sin() Returns the sine of a number

math.sinh() Returns the hyperbolic sine of a number

math.sqrt() Returns the square root of a number

math.tan() Returns the tangent of a number

math.tanh() Returns the hyperbolic tangent of a number

math.trunc() Returns the truncated integer parts of a number

Math Constants
Constant Description

math.e Returns Euler's number (2.7182...)

math.inf Returns a floating-point positive infinity

math.nan Returns a floating-point NaN (Not a Number) value

math.pi Returns PI (3.1415...)

math.tau Returns tau (6.2831...)

Importing Functions
In Python, functions play a vital role in programming as they help in creating
reusable code. However, sometimes it can be tedious to rewrite the same
function over and over again. Luckily, Python makes it easy to reuse
functions by allowing you to import them from different files.

Python's Import Function: How to


Use It for Enhanced Code Reusability
Python's import function is a powerful tool for enhanced code
reusability. It allows us to import functions from other files, which can
save us a lot of time and effort when building larger projects.

To import functions from a file, we first need to create a Python module.


This is simply a file with a .py extension that contains the functions we
want to import. We can then use the import keyword to bring those
functions into our main script: from my_module import my_function

Alternatively, we can also import the entire module and access its
functions using dot notation: import my_module

By using the import function in Python, we can easily reuse code across
multiple projects and improve our overall efficiency as developers.

The Different Ways to Import


Functions from Files in Python
Importing functions in Python is a common practice to reuse code and
improve code organization. There are different ways to import functions in
Python, including importing a function from a file or importing a function
as a module.

To import a function from a file in Python, use the following syntax: from
file_name import function_name

This allows you to use the function in your code without having to write
the entire code again. For example:

Alternatively, you can import a function as a module, which can be useful


if you want to import multiple Python's functions from the same
module: import file_name
Overall, importing functions in Python is a powerful way to make your
code more efficient and readable.

Call a Function from Another File


One of the common practices in Python is to reuse code by importing
functions from other Python files. This allows you to bring specific
functions into your current script. To do this, use the following syntax:

from file_name import function_name

For instance, to import the add function from a file


called math_operations.py, you can use:

from math_operations import add

Once you've imported the function, you can easily use it in your code.
Here's an example:

result = add(2, 3)

print(result) # Output: 5

To import multiple specific functions, such as add and subtract,


from math_operations.py, you can use the following syntax:

from math_operations import add, subtract

Now both the add and subtract functions from the math_operations.py file
can be called as follows:

print(add(2, 3))

print(subtract(5, 3))
This process is a powerful way to enhance code reusability in Python. By
importing functions from other files, you can save time and effort and
make your code more efficient and organized.

Common Errors When Importing Functions in Python and How


to Fix Them

When importing functions in Python, common errors include import


errors, syntax errors, and module attribute errors.

If you encounter an error when trying to call a function from another file,
there are a few things you can try to fix it. First, make sure that the file
you're trying to import from is located in the same directory as your
Python script. If not, you may need to specify the path to the file.

Next, check the syntax of the import statement to make sure it's correct.
If you're using the from keyword, make sure you've included the correct
function name. If you're using the import keyword, make sure you're
referring to the correct module name.

Finally, double-check the function name to make sure it's spelled correctly
and that it's defined in the file you're trying to import from.

For example, let's say you want to import the runsqlscript function from
the sqlideutils module. Here's how you could do it using
the from keyword: from sqlideutils import runsqlscript

And here's how you could do it using the import keyword: import
sqlideutils with runsqlscript = sqlideutils.runsqlscript

Organizing Your Python Code: How to Create a Custom Module


with Importable Functions

Organizing your Python code is crucial to make it readable, maintainable,


and reusable. One way of achieving this is by creating a custom module
containing importable functions.

To create a custom module with importable functions, follow these steps:

1. Create a new Python file with the .py extension and give it a descriptive name
(e.g., myfunctions.py).
2. Define one or more functions in the file using the def keyword and a function
name (e.g., mod_function).
3. Save the file.
4. Import the function(s) from the file into another Python script using
the import keyword and the file name without the .py extension (e.g. import
myfunctions).
5. Call the imported function(s) in the script using the function name as defined in
the file (e.g., myfunctions.mod_function() ).

Advanced Python Techniques: How to Build and Import


External Packages with Multiple Functions

Import functions is an advanced Python technique that allows us to


build and import external packages with multiple functions. It is a
powerful feature that enhances code reusability and organization.

There are several ways to import multiple functions in Python. One way is
to define functions in a separate file and then import them into the main
script using the import function from file syntax. Another way is to use
the map function with multiple arguments to apply a function to multiple
iterables simultaneously.

Here are two examples of how to use import functions in Python:

Example 1: Importing Functions from a Separate File

# Suppose we have a file named `my_functions.py` that contains the following


functions:

def add(a, b):

return a + b

def subtract(a, b):

return a - b

# To import these functions into a main script, we can use the following syntax:

# from my_functions import add, subtract

result1 = add(10, 5)
result2 = subtract(10, 5)

print(result1) # Output: 15

print(result2) # Output: 5

Here, we import the add and subtract functions from


the my_functions.py file and use them in the main script.

Example 2: Using the Map Function with Multiple


Arguments
Suppose we have two lists, numbers1 and numbers2, and we want to add
them element-wise. We can use the map function with multiple
arguments to achieve this:

numbers1 = [1, 2, 3, 4, 5]

numbers2 = [5, 4, 3, 2, 1]

def add(a, b):

return a + b

result = list(map(add, numbers1, numbers2))

print(result) # Output: [6, 6, 6, 6, 6]

Here, we define the add function and use the map function to apply it to
the numbers1 and numbers2 lists element-wise. The result is a new
list containing the element-wise sum of the two lists.

You might also like