Python Functions and Arguments Explained
Python Functions and Arguments Explained
FUNCTIONS
Python Functions
This tutorial will go over the fundamentals of Python functions, including what they are, their syntax,
their primary parts, return keywords, and significant types. We'll also look at some examples of
Python function definitions.
What are Python Functions?
A collection of related assertions that carry out a mathematical, analytical, or evaluative operation is
known as a function. An assortment of proclamations called Python Capabilities returns the specific
errand. Python functions are necessary for intermediate-level programming and are easy to define.
Function names meet the same standards as variable names do. The objective is to define a function
and group-specific frequently performed actions. Instead of repeatedly creating the same code block
for various input variables, we can call the function and reuse the code it contains with different
variables.
Client-characterized and worked-in capabilities are the two primary classes of capabilities in Python.
It aids in maintaining the program's uniqueness, conciseness, and structure.
Advantages of Python Functions
Pause We can stop a program from repeatedly using the same code block by including functions.
o Once defined, Python functions can be called multiple times and from any location in a
program.
o Our Python program can be broken up into numerous, easy-to-follow functions if it is
significant.
o The ability to return as many outputs as we want using a variety of arguments is one of
Python's most significant achievements.
o However, Python programs have always incurred overhead when calling functions.
However, calling functions has always been overhead in a Python program.
Syntax
# An example Python Function
def function_name( parameters ):
# code block
The accompanying components make up to characterize a capability, as seen previously.
o The start of a capability header is shown by a catchphrase called def.
o function_name is the function's name, which we can use to distinguish it from other functions.
We will utilize this name to call the capability later in the program. Name functions in Python
must adhere to the same guidelines as naming variables.
o Using parameters, we provide the defined function with arguments. Notwithstanding, they are
discretionary.
o A colon (:) marks the function header's end.
o We can utilize a documentation string called docstring in the short structure to make sense of
the reason for the capability.
o Several valid Python statements make up the function's body. The entire code block's
indentation depth-typically four spaces-must be the same.
o A return expression can get a value from a defined function.
Calling a Function
Calling a Function To define a function, use the def keyword to give it a name, specify the arguments
it must receive, and organize the code block.
When the fundamental framework for a function is finished, we can call it from anywhere in the
program. An illustration of how to use the a_function function can be found below.
Function Arguments
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments
1) Default Arguments
A default contention is a boundary that takes as information a default esteem, assuming that no worth
is provided for the contention when the capability is called. The following example demonstrates
default arguments.
Code
# Python code to demonstrate the use of default arguments
# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling the function and passing only one argument
print( "Passing only one argument" )
function(30)
# Now giving two arguments to the function
print( "Passing two arguments" )
function(50,30)
Output:
Passing only one argument
number 1 is: 30
number 2 is: 20
number 2 is: 30
2) Keyword Arguments
Keyword arguments are linked to the arguments of a called function. While summoning a capability
with watchword contentions, the client might tell whose boundary esteem it is by looking at the
boundary name.
We can eliminate or orchestrate specific contentions in an alternate request since the Python
translator will interface the furnished watchwords to connect the qualities with its boundaries. One
more method for utilizing watchwords to summon the capability() strategy is as per the following:
Code
# Python code to demonstrate the use of keyword arguments
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling function and passing arguments without using keyword
print( "Without using keyword" )
function( 50, 30)
# Calling function and passing arguments using keyword
print( "With using keyword" )
function( n2 = 50, n1 = 30)
Output:
Without using keyword
number 1 is: 50
number 2 is: 30
number 1 is: 30
number 2 is: 50
3) Required Arguments
Required arguments are those supplied to a function during its call in a predetermined positional
sequence. The number of arguments required in the method call must be the same as those provided
in the function's definition.
We should send two contentions to the capability() all put together; it will return a language structure
blunder, as seen beneath.
Code
# Calling function and passing two arguments out of order, we need num1 to be 20 and num2 to be 3
0
print( "Passing out of order arguments" )
function( 30, 20 )
number 1 is: 30
number 2 is: 20
4) Variable-Length Arguments
We can involve unique characters in Python capabilities to pass many contentions. However, we
need a capability. This can be accomplished with one of two types of characters:
"args" and "kwargs" refer to arguments not based on keywords.
To help you understand arguments of variable length, here's an example.
Code
# Python code to demonstrate the use of variable-length arguments
# Defining a function
def function( *args_list ):
ans = []
for l in args_list:
[Link]( [Link]() )
return ans
# Passing args arguments
object = function('Python', 'Functions', 'tutorial')
print( object )
# defining a function
def function( **kargs_list ):
ans = []
for key, value in kargs_list.items():
[Link]([key, value])
return ans
# Paasing kwargs arguments
object = function(First = "Python", Second = "Functions", Third = "Tutorial")
print(object)
Output:
['PYTHON', 'FUNCTIONS', 'TUTORIAL']
RETURN STATEMENT:
When a defined function is called, a return statement is written to exit the function and return the
calculated value.
Syntax:
2704
None
Code
Here, we can see that the initial value of num is 10. Even though the function number() changed the
value of num to 50, the value of num outside of the function remained unchanged.
This is because the capability's interior variable num is not quite the same as the outer variable
(nearby to the capability). Despite having a similar variable name, they are separate factors with
discrete extensions.
Factors past the capability are available inside the capability. The impact of these variables is global.
We can retrieve their values within the function, but we cannot alter or change them. The value of a
variable can be changed outside of the function if it is declared global with the keyword global.
Python Capability inside Another Capability
Capabilities are viewed as top-of-the-line objects in Python. First-class objects are treated the same
everywhere they are used in a programming language. They can be stored in built-in data structures,
used as arguments, and in conditional expressions. If a programming language treats functions like
first-class objects, it is considered to implement first-class functions. Python lends its support to the
concept of First-Class functions.
A function defined within another is called an "inner" or "nested" function. The parameters of the
outer scope are accessible to inner functions. Internal capabilities are developed to cover them from
the progressions outside the capability. Numerous designers see this interaction as an embodiment.
Code
A return statement
A return statement ends the execution of a function, and returns control to the calling function.
Execution resumes in the calling function at the point immediately following the call. A return
statement can return a value to the calling function.
Function Arguments
Arguments and Parameters in Python
Be it any programming language, Arguments and Parameters are the two words that cause a lot of
confusion to programmers. Sometimes, these two words are used interchangeably, but actually, they
have two different yet similar meanings. This tutorial explains the differences between these two
words and dives deep into the concepts with examples.
Both arguments and parameters are variables/ constants passed into a function. The difference is that:
1. Arguments are the variables passed to the function in the function call.
2. Parameters are the variables used in the function definition.
3. The number of arguments and parameters should always be equal except for the variable
length argument list.
Example:
def add_func(a,b):
sum = a + b
return sum
num1 = int(input("Enter the value of the first number: "))
num2 = int(input("Enter the value of the second number: "))
print("Sum of two numbers: ",add_func(num1, num2))
Output:
Mechanism:
Observe that in the above example, num1 and num2 are the values in the function call with which we
called the function. When the function is invoked, a and b are replaced with num1 and num2, the
operation is performed on the arguments, and the result is returned.
Functions are written to avoid writing frequently used logic again and again. To write a general logic,
we use some variables, which are parameters. They belong to the function definition. When we
need the function while writing our program, we need to apply the function logic on the variables we
used in our program, called the arguments. We then call the function with the arguments.
Types of Arguments:
Based on how we pass arguments to parameters, arguments are of two types:
1. Positional arguments
2. Keyword arguments
o Given some parameters, if the respective arguments are passed in order one after the other,
those arguments are called the "Positional arguments."
o If the arguments are passed by assigning them to their respective parameters in the function
call with no significance to the passing order, they are called "Keyword arguments".
Example:
def details(name, age, grade):
print("Details of student:", name)
print("age: ", age)
print("grade: ", grade)
details("Raghav", 12, 6)
details("Santhosh", grade = 6, age = 12)
Output:
Details of student: Raghav
age: 12
grade: 6
Details of student: Santhosh
age: 12
grade: 6
Points to grasp from the Example:
First Function Call:
o The function has three parameters-name, age and grade. So, it accepts three arguments.
o In the first function call:
details("Raghav", 12, 6)
The arguments are passed position-wise to the parameters, which mean according to the passed
order:
o name is replaced with "Raghav."
o age is replaced with 12 and
o grade is replaced with 6
o In the first function call, the order of passing the arguments matter. The parameters accept the
arguments in the given order only.
o In the Second Function Call:
When the addresses of the arguments are passed into parameters instead of values, this method of
invoking a function is called "Call by Reference".
o Both the arguments and parameters refer to the same memory location.
o Changes to the parameters (pointers) will affect the values of the arguments in the program.
o By default, C language follows Call by value, but using the indirection operator and pointers;
we can simulate Call by reference.
000000000062FE1C
000000000062FE1C
In Python:
a = 20
print(id(a))
a = 21
print(id(a))
Output:
140714950863232
140714950863264
o As you can observe: In C, after reassigning the value, the variable is still in the same memory
location, while in Python, it refers to a different memory location. (id -> address in Python).
o But that's not all. There are other types of objects too.
Example:
Mutable Objects:
a = [23, 45, 89]
print(id(a))
[Link](49)
print(id(a))
Output:
2253724439168
2253724439168
Understanding:
A list is immutable, which means we can alter or modify it after creating it. As you can observe,
when created with the name a, it is saved in the address "2253724439168". Using append(), we
altered it by appending another value. It is still in the same memory location, meaning the same
object is modified.
Immutable Objects:
a = 20
print(id(a))
a += 23
print(id(a))
Output:
140714950863232
140714950863968
Understanding:
This is the case we discussed before in the tutorial. An int object is immutable, meaning we can't
modify it once created. You might wonder we still added 23 in the above code. Observe that the
object when created is not the same object after adding. Both are in different memory locations
which means they are different objects.
So, how are arguments passed to the parameters when a function is invoked?
With all the knowledge about assignment operation in Python:
1. The passing is like a "Call by Reference" if the arguments are mutable.
2. The passing is like "Call by Value" if the arguments are immutable.
Example:
def details(name, age, grade, marks):
[Link](26)
name += " Styles"
print("Details of the student: ")
print("name: ",name)
print("age: ",age)
print("grade: ", grade)
print("marks: ", marks)
name = "Harry"
age = 15
grade = 10
marks = [25, 29, 21, 30]
details (name, age, grade, marks)
print(grade)
print(marks)
Output:
age: 15
grade: 10
10
Let
us
study
Data Science
and
Blockchain
Explanation-
Let's understand what we have done in the above program,
1. In the first step, we have created a function that will take variable arguments as its parameters.
2. After this, we have used a for loop that will take each element or parameter in this case and
print it.
3. Finally, we have passed six strings as the parameters in our function.
4. On executing the program, the desired output is displayed.
Let's have a look at one more program based on *args.
#program to demonstrate *args in python
def my_func(par1,par2,*argp):
#displaying the first parameter
print("The first parameter is: ",par1)
#displaying the second parameter
print("The second parameter is: ",par2)
for i in argp:
#printing each element from the list
print(i)
#passing the parameters in function
my_func("Let","us","study","Data Science","and","Blockchain")
Output:
study
Data Science
and
Blockchain
Explanation-
It's time to have a glance at the explanation of this program.
1. In the first step, we have created a function that will take two parameters and then rest as
variable arguments as its parameters.
2. In the next step, we have defined the function in which we have displayed the values of the
first two parameters.
3. After this, we have used a for loop that will take each element or parameter in this case and
print it.
4. Finally, we have passed six strings as the parameters in our function.
5. On executing the program, the desired output is displayed.
a_key=Let
b_key=us
c_key=study
d_key=Data Science
e_key=and
f_key=Blockchain
Explanation-
Let us see what we have done in the above program.
1. In the first step, we have created a function that takes keyworded arguments as its parameters.
2. After this, in the function definition we have specified that a for loop will be used to fetch the
key-value pair.
3. Finally, we have passed six key value pairs inside the function.
4. On executing this program, the desired output is displayed.
b_key=us
c_key=study
d_key=Data Science
e_key=and
f_key=Blockchain
Explanation-
Check out the explanation of this program,
1. In the first step, we have created a function that takes one parameter and rest as keyworded
arguments as its parameters.
2. After this, in the function definition, we have specified that a for loop will be used to fetch
the key-value pair.
3. Finally, we have passed five key-value pairs inside the function and so it displays only those
pairs in the output and doesn't consider the first string.
4. On executing this program, the desired output is displayed.
We will conclude this article with a program that illustrates how *args and **kwargs can be used in a
single program.
#program to demonstrate **kwargs in python
def my_func(*args,**kwargs):
#displaying the value of args
print("The value of args is:",args)
#displaying the value of kwargs
print("The value of kwargs is:",kwargs)
#passing the values in function
my_func("Let","us","study",a_key="Data Science",b_key="and",c_key="Blockchain")
Output:
The value of kwargs is: {'a_key': 'Data Science', 'b_key': 'and', 'c_key': 'Blockchain'}
Explanation-
1. In the first step, we have created a function that takes *args and **kwargs (non-keyworded
and keyworded arguments) as its parameters.
2. After this, we have the function definition where we have displayed the values of both
parameters.
3. Finally, we have passed six parameters in the function, from which three are strings and the
other three are key-value pairs.
To insert characters that are illegal in a string, use an escape [Link] escape character is
a backslash \ followed by the character you want to insert.
Example:
Output:
Raw Strings:
Raw strings are particularly useful when working with regular expressions, as they allow
you to specify patterns that may contain backslashes without having to escape them. They are also
useful when working with file paths, as they allow you to specify paths that contain backslashes
without having to escape them. Raw strings can also be useful when working with strings that
contain characters that are difficult to type or read, such as newline characters or tabs. In general,
raw strings are useful anytime you need to specify a string that contains characters that have
special meaning in Python, such as backslashes, and you want to specify those characters literally
without having to escape them.
Example:
str = r'Python\nis\easy\to\learn'
Output: Python\nis\easy\to\learn
Explanation: As we can see that the string is printed as raw,
and it neglected all newline sign(\n) or tab space (\t).
String Formatting:
String formatting in Python allows you to create dynamic strings by combining variables
and values. String formatting in Python allows you to create dynamic strings by combining
variables and values.
Example:
print("The mangy, scrawny stray dog %s gobbled down" %'hurriedly' +
"the grain-free, organic dog food.")
Output:
The mangy, scrawny stray dog hurriedly gobbled down the grain-free, organic dog
food.
Python Operators:
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
** Exponentiation x ** y Try
== Equal x == y Try
and Returns True if both statements are true x < 5 and x < 10 Try
»
not Reverse the result, returns False if the result not(x < 5 and x < 10) Try
is true
»
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Operator Description Example Try
is not Returns True if both variables are not the same x is not y Try
object
»
<< Zero fill left Shift left by pushing zeros in from the right and let the x << 2 T
shift leftmost bits fall off
»
>> Signed right Shift right by pushing copies of the leftmost bit in from x >> 2 T
shift the left, and let the rightmost bits fall off
»
Operator Precedence:
Example
Parentheses has the highest precedence, meaning that expressions inside parentheses must be
evaluated first:
print((6 + 3) - (6 + 3))
Example
Multiplication * has higher precedence than addition +, and therefor multiplications are
evaluated before additions:
print(100 + 5 * 3)
The precedence order is described in the table below, starting with the highest precedence at
the top:
Try
() Parentheses
Try
** Exponentiation
Try
& Bitwise AND
Try
^ Bitwise XOR
Try
| Bitwise OR
== != > >= < <= is is not in not Comparisons, identity, and membership operators Try
in
»
Try
not Logical NOT
Try
and AND
Try
or OR
»
If two operators have the same precedence, the expression is evaluated from left to right.
Example
Addition + and subtraction - has the same precedence, and therefor we evaluate the
expression from left to right:
print(5 + 4 - 7 + 3)
Output:
We all are equal
Understanding Python f-string
PEP 498 introduced a new string formatting mechanism known as Literal String
Interpolation or more commonly as F-strings (because of the leading f character preceding the
string literal). The idea behind f-String in Python is to make string interpolation simpler.
To create an f-string in Python, prefix the string with the letter “f”. The string itself can be
formatted in much the same way that you would with str. format(). F-strings provide a concise
and convenient way to embed Python expressions inside string literals for formatting.
Example:
name = 'Ele'
print(f"My name is {name}.")
Output:
My name is Ele
Python String Template Class
In the String module, Template Class allows us to create simplified syntax for output
specification. The format uses placeholder names formed by $ with valid
Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with
braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing
$$ creates a single escaped $:
Formatting string using Template Class:
This code imports the Template class from the string module. The Template class allows us
to create a template string with placeholders that can be substituted with actual values. Here we are
substituting the values n1 and n2 in-place of n3 and n4 in the string n.
Example:
# Python program to demonstrate
# string interpolation
n1 = 'Hello'
n2 = 'GeeksforGeeks'
Output:
Hello ! This is GeeksforGeeks.
Formatting string using center() method:This code returns a new string padded
with spaces on the left and right sides.
Example:
string = "GeeksForGeeks!"
width = 30
centered_string = [Link](width)
print(centered_string)
Output:
GeeksForGeeks!
String Operations:
In python, String operators represent the different types of operations that can be employed
on the program's string type of variables. Python allows several string operators that can be applied
on the python string are as below: Assignment operator: “=.” Concatenate operator: “+.” String
repetition operator: “*.”
String operators with examples:
In python, String operators represent the different types of operations that can be employed on
the program’s string type of variables. Python allows several string operators that can be applied on
can be defined with either single quotes [‘ ’], double quotes[“ ”] or triple quotes[‘’’ ‘’’]. var_name =
Code:
string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
print(string1)
print(string2)
print(string3)
Output:
hello
hello
hello
Code:
string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)
Output:
helloworld
below example.
Code:
string1 = "helloworld "
print(string1*2)
print(string1*3)
print(string1*4)
print(string1*5)
Output:
helloworld helloworld
operator. The index is interpreted as a positive index starting from 0 from the left side and a negative
string[a]: Returns a character from a positive index a of the string from the left side as
string[-a]: Returns a character from a negative index a of the string from the right side as
string[a:b]: Returns characters from positive index a to positive index b of the as displayed
string[a:-b]: Returns characters from positive index a to the negative index b of the string as
string[a:]: Returns characters from positive index a to the end of the string.
string[:b] Returns characters from the start of the string to the positive index b.
string[-a:]: Returns characters from negative index a to the end of the string.
string[:-b]: Returns characters from the start of the string to the negative index b.
Code:
string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])
Output:
ello
ellowo
lloworld
hello
hellowor
ld
dlrowolleh
“==” operator returns Boolean True if two strings are the same and return Boolean False if
“!=” operator returns Boolean True if two strings are not the same and return Boolean False if
These operators are mainly used along with if condition to compare two strings where the
Code:
string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string2==string3)
print(string1!=string4)
print(string2!=string3)
Output:
False
True
True
False
“a” in the string: Returns boolean True if “a” is in the string and returns False if “a” is not in
the string.
“a” not in the string: Returns boolean True if “a” is not in the string and returns False if “a”
is in the string.
A membership operator is also useful to find whether a specific substring is part of a given
string.
Code:
string1 = "helloworld"
print("w" in string1)
print("W" in string1)
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
print("Hello" in string1)
print("hello" not in string1)
Output:
True
False
False
True
True
False
False
of a non-allowed character in python string is inserting double quotes in the string surrounded by
double-quotes.
Code:
Output:
SyntaxError:invalid syntax
variable along with string, the “%” operator is used along with python string. “%” is prefixed to
another character indicating the type of value we want to insert along with the python string.
Code:
name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)
Output:
Hey india
my age is 19
In Python, the terms “mutable” and “immutable” refer to the ability of an object to be
changed after it is [Link] object is considered mutable if its state or value can be modified after
it is created. This means that you can alter its internal data or attributes without creating a new object.
Examples of mutable objects in Python include lists, dictionaries, and sets. If you modify a mutable
object, any references to that object will reflect the [Link] of these states are integral to
Python data structure.
What is Mutable?
Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’
is the ability of objects to change their values. These are often the objects that store a collection of
data.
What is Immutable?
Immutable is the when no change is possible over time. In Python, if the value of an object
cannot be changed over time, then it is known as immutable. Once created, the value of these objects
is permanent.
Lists
Sets
Dictionaries
User-Defined Classes (It purely depends upon the user to define the characteristics)
Objects of built-in type that are immutable are:
# Printing the elements from the list cities, separated by a comma & space
print(city, end=’, ’)
print(weekdays)
Python has a set of built-in methods that you can use on [Link] string methods returns new
values. They do not change the original string.
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it was found
index() Searches the string for a specified value and returns the position of where it was found
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was foun
rindex() Searches the string for a specified value and returns the last position of where it was foun
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
swapcase() Swaps cases, lower case becomes upper case and vice versa
zfill() Fills the string with a specified number of 0 values at the beginning
Function Description
delattr() Deletes the specified attribute (property or method) from the specified object
dict() Returns a dictionary (Array)
divmod() Returns the quotient and the remainder when argument1 is divided by
argument2
hasattr() Returns True if the specified object has the specified attribute
(property/method)
map() Returns the specified iterator with the specified function applied to each item
(by default)
The relational operators compare the Unicode values of the characters of the strings from
the zeroth index till the end of the string. It then returns a boolean value according to the operator
used.
Example:
print("Geek" == "Geek")
print("Geek" < "geek")
print("Geek" != "Geek")
Output:
True
True
False
False
The == operator compares the values of both the operands and checks for value equality.
Whereas is operator checks whether both the operands refer to the same object or not. The same is
the case for != and is not.
Example:
str1 = "Geek"
str2 = "Geek"
str3 = str1
print(str1 is str1)
print(str1 is str2)
print(str1 is str3)
str1 += "s"
str4 = "Geeks"
print(str1 is str4)
Output:
ID of str1 = 0x7f6037051570
ID of str2 = 0x7f6037051570
ID of str3 = 0x7f6037051570
True
True
True
ID of str4 = 0x7f60356137a0
False
The object ID of the strings may vary on different machines. The object IDs of str1, str2
and str3 were the same therefore they the result is True in all the cases. After the object id of str1 is
changed, the result of str1 and str2 will be false. Even after creating str4 with the same contents as
in the new str1, the answer will be false as their object IDs are different.
Vice-versa will happen with is not.
String Comparison in Python Creating a user-defined function.
By using relational operators we can only compare the strings by their unicodes. In order
to compare two strings according to some other parameters, we can make user-defined functions.
In the following code, our user-defined function will compare the strings based upon the
number of digits.
Python3
count1 = 0
count2 = 0
for i in range(len(str1)):
count1 += 1
for i in range(len(str2)):
count2 += 1
print(compare_strings("123", "12345"))
print(compare_strings("12345", "geeks"))
print(compare_strings("12geeks", "geeks12"))
Output:
False
False
True
Python Modules:
What is a Module?
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Example
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
[Link]("Jonathan")
Note: When using a function from a module, use the syntax: module_name.function_name.
Variables in Module:
The module can contain functions, as already described, but also variables of all types
(arrays, dictionaries, objects etc):
Example
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Naming a Module
You can name the module file whatever you like, but it must have the file extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example
import mymodule as mx
a = mx.person1["age"]
print(a)
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Example
import platform
x = [Link]()
print(x)
Using the dir() Function:
There is a built-in function to list all the function names (or variable names) in a module.
The dir() function:
Example
import platform
x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create yourself.
You can choose to import only parts from a module, by using the from keyword.
Example
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
print (person1["age"])
Pythontutor
It is advisable to use online pythontutor to visualize execution of Python code
See how pythontutor visualizes object reference
See that two (or even more names, a and c in this example) may reference the same
object (integer '1'). This is typically called "shared object reference"
(b) Namespaces
What is a namespace?
In [7]:
x=1
x='spam'
print(x)
del x
print(x)
spam
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-2bb509689422> in <module>()
4
5 del x
----> 6 print(x)
x=1 introduces 'x' in the namespace but name 'x' is not recognized after executing
the 'del x' command. 'x' is deleted from the namespace.
Please note that when working interactively in a Python shell (like, for example,
jupyter notebook) you may either use the print() function to present values
onscreen or simply write the name or expression whose value you want in the
output.
In the latter case only the last expression in the cell will be presented in the output
unless you define otherwise by adjusting the notebook settings
In [1]:
x=1
y = 2.5
x+y
# Just writing the expression will present the outcome
Out[1]:
3.5
In [5]:
x=1
y = 2.5
print(x, y, 2*x**y)
# Better use print() when you want to present more than one values
1 2.5 2.0
(c) Modules
What is a module?
A module is practically any .py file containing useful code (for example:
statements, functions, and classes) that can be used for code development.
As the name implies, modules promote the idea of modular development in
practice. Python offers a simple yet powerful way to link modules and use/reuse
code in many different situations
import module_name
The 'import' command imports the namespace of the module to the namespace of
the code you are writing in your main program. For example:
In [ ]:
import random
print([Link](1,10))
The 'random' module offers functions for generating and managing random
numbers. The 'import random' command imports the namespace of 'random' in your
program code. We shall see more of that later.
Note the use of 'dot notation' to refer to the imported
names: 'module_name.imported_name'. This is a practical way to visualize
namespaces and import them safely in your code.
There are two other common ways to write the 'import' command. One you should
avoid; the other you should follow.
Avoid this:
In [4]:
from random import *
print(randint(1,10))
The benefit here is that you import the entire module namespace and you can use it
without writing the module name as a prefix.
However: this technique provides no visual cues as to the origin of the names and it
may confuse you - so avoid it unless you are completely confident about your code!
Follow this:
In [6]:
import random as rn
print([Link](1,10))
Python is a multi-purpose, high level, and dynamic programming language. It provides many
built-in modules and functions to perform various types of tasks. Aside from that, we can also
create our own modules using Python. A module is like a library in Java, C, C++, and C#. A
module is usually a file that contains functions and statements. The functions and statements
of modules provide specific functionality. A Python module is saved with the .py extension.
In this article, we will learn to create our own Python modules.
A module is typically used to divide the large functionality into small manageable files. We
can implement our most used functions in a separate module, and later on, we can call and
use it everywhere. The module’s creation promotes reusability and saves a lot of time.
Let’s create a new module named “MathOperations”. This module contains functions to
perform addition, subtraction, multiplication, and division.
def addition(num1,num2):
return num1+num2
def subtraction(num1,num2):
return num1-num2
def multiplication(num1,num2):
return num1*num2
#creating division function
def division(num1,num2):
return num1/num2
Part- A
Choose the best answer:
str1="6/4"
print("str1")
a). 1
b). 6/4
c). 1.5
d). str1
a). class
b). function
c). method
d). module
4. Program code making use of a given module is called a ______ of the module.
a) Client
b) Docstring
c) Interface
d) Modularity
str1="poWer"
[Link]()
print(str1)
a). POWER
b). Power
c). power
d). poWer
str1="Stack of books"
print(len(str1))
a). 13
b). 14
c). 15
d). 16
str1="Information"
print(str1[2:8])
a). format
b). formatio
c). orma
d). ormat
a). define
b). fun
c). def
d). function
10. Which of the following items are present in the function header?
a). function name
b). parameter list
c). return value
d). Both A and B
11. Which of the following will print the pi value defined in math module?
a). print(pi)
b). print([Link])
c). from math import pi
print(pi)
d). from math import pi
print([Link])
a). .
b). *
c). ->
d). &
print(z(6))
a). 6
b). 36
c). 0
d). error
print(chr(ord(chr(97))))
a). a
b). A
c). 97
d). error
Part – B
1. Explain about Python strings?
2. Explain about Python strings operators?
3. Explain about example of a string in Python?
4. How to do length of a string in Python?
5. Why strings are immutable with an example in Python?
6. What are immutable strings in Python?
7. What are immutable strings write a short note?
8. What are string function and method in Python?
9. What are the 5 string methods?
10. What are the 2 string method in Python?
Part-C
1. What is the method string?
2. What is string function and method in Python?
3. What are the built-in types in Python?
4. What are 4 built-in data types in Python?
5. How strings are immutable in Python with example?
6. Explain about string immutable data types in Python?
7. What are examples of immutable in Python?
8. Explain about string Comparison ?
9. What are the modules and namespace in Python?
10. How to defining our own modules?