M1 Unit3
M1 Unit3
Compiled By
Dr. Meghdoot Ghosh MBA, M.Sc, UGC(NET), Ph.D
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
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.
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.
Conversion
num_string = '12'
num_integer = 23
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Output
num_string = int(num_string)
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.
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")
Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
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:
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:
my_function("Emil")
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])
Keyword Arguments
You can also send arguments with the key = value syntax.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
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"])
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)
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))
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)
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.
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)
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.
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
Example
import math
x = math.pi
print(x)
Math Methods
Method Description
math.expm1() Returns Ex - 1
Math Constants
Constant Description
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.
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.
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:
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
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.
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
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() ).
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.
return a + b
return a - b
# To import these functions into a main script, we can use the following syntax:
result1 = add(10, 5)
result2 = subtract(10, 5)
print(result1) # Output: 15
print(result2) # Output: 5
numbers1 = [1, 2, 3, 4, 5]
numbers2 = [5, 4, 3, 2, 1]
return a + b
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.