Python
Python
Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.
Python's syntax and dynamic typing with its interpreted nature make it an ideal
language for scripting and rapid application development.
Python is not intended to work in a particular area, such as web programming. That is
why it is known as multipurpose programming language because it can be used with
web, enterprise, 3D CAD, etc.
We don't need to use data types to declare variable because it is dynamically typed so
we can write a=10 to assign an integer value in an integer variable.
Python makes the development and debugging fast because there is no compilation
step included in Python development, and edit-test-debug cycle is very fast.
Python History
Python was invented by Guido van Rossum in 1991 at CWI in Netherland. The idea of
Python programming language has taken from the ABC programming language or we
can say that ABC is a predecessor of Python language.
There is also a fact behind the choosing name Python. Guido van Rossum was a fan of
the popular BBC comedy show of that time, "Monty Python's Flying Circus". So he
decided to pick the name Python for his newly created programming language.
Python has the vast community across the world and releases its version within the
short period.
o Data Science
o Data Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Computer Vision or Image Processing Applications.
o Speech Recognitions
Python Popular Frameworks and Libraries
Python has wide range of libraries and frameworks widely used in various fields such
as machine learning, artificial intelligence, web applications, etc. We define some
popular frameworks and libraries of Python as follows.
1. a = 5
The variable a holds integer value five and we did not define its type. Python interpreter
will automatically interpret variables a as an integer type.
Python enables us to check the type of the variable used in the program. Python
provides us the type() function, which returns the type of the variable passed.
Consider the following example to define the values of different data types and
checking its type.
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Standard data types
A variable can hold different types of values. For example, a person's name must be
stored as a string whereas its id must be stored as an integer.
Python provides various standard data types that define the storage method on each
of them. The data types defined in Python are given below.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
In this section of the tutorial, we will give a brief introduction of the above data-types.
We will discuss each one of them in detail later in this tutorial.
Numbers
Number stores numeric values. The integer, float, and complex values belong to a
Python Numbers data-type. Python provides the type() function to know the data-
type of the variable. Similarly, the isinstance() function is used to check an object
belongs to a particular class.
Python creates Number objects when a number is assigned to a variable. For example;
1. a = 5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python
has no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.
Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
Example - 1
Output:
Example - 2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Python Lists are similar to arrays in C. However, the list can contain data of different
types. The items stored in the list are separated with a comma (,) and enclosed within
square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator
(+) and repetition operator (*) works with the list in the same way as they were working
with the strings.
Output:
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection
of the items of different data types. The items of the tuple are separated with a comma
(,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items
of a tuple.
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
The items in the dictionary are separated with the comma (,) and enclosed in the curly
braces {}.
Output:
Boolean
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. It denotes by the class bool. True can be
represented by any non-zero value or 'T' whereas false can be represented by the 0 or
'F'. Consider the following example.
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can
modify after creation), and has unique elements. In set, the order of the elements is
undefined; it may return the changed sequence of the element. The set is created by
using a built-in function set(), or a sequence of elements is passed in the curly braces
and separated by the comma. It can contain various types of values. Consider the
following example.
Output:
Arithmetic Operators
Arithmetic operators are used to performing mathematical operations like addition,
subtraction, multiplication, and division.
In Python 3.x the result of division is a floating-point while in Python 2.x division
of 2 integer was an integer and to obtain an integer result in Python 3.x floored (//
integer) is used.
Operator Description Syntax
+ Addition: adds two operands x+y
– Subtraction: subtracts two operands x–y
* Multiplication: multiplies two operands x*y
/ Division (float): divides the first operand by the second x/y
// Division (floor): divides the first operand by the second x // y
% Modulus: returns the remainder when the first operand is x%y
divided by the second
** Power: Returns first raised to power second x ** y
PRECEDENCE:
P – Parentheses
E – Exponentiation
M – Multiplication (Multiplication and division have the same precedence)
D – Division
A – Addition (Addition and subtraction have the same precedence)
S – Subtraction
The modulus operator helps us extract the last digit/s of a number. For example:
x % 10 -> yields the last digit
x % 100 -> yield last two digits
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)
Output
13
5
36
2.25
2
1
6561
Comparison Operators
Comparison of Relational operators compares the values. It either
returns True or False according to the condition.
Operator Description Syntax
> Greater than: True if the left operand is greater than the right x>y
< Less than: True if the left operand is less than the right x<y
== Equal to: True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
>= Greater than or equal to True if the left operand is greater than x >= y
or equal to the right
<= Less than or equal to True if the left operand is less than or x <= y
equal to the right
is x is the same as y x is y
is not x is not the same as y x is not
y
= is an assignment operator and == comparison operator.
Example: Comparison Operators in Python
# a > b is False
print(a > b)
# a < b is True
print(a < b)
# a == b is False
print(a == b)
# a != b is True
print(a != b)
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)
Output
False
True
False
True
False
True
Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT operations.
It is used to combine conditional statements.
Operator Description Syntax
and Logical AND: True if both the operands are true x and y
Python3
a = True
b = False
print(a and b)
# Print a or b is True
print(a or b)
print(not a)
Output
False
True
False
Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to
operate on binary numbers.
Operator Description Syntax
| Bitwise OR x|y
~ Bitwise NOT ~x
Python3
a = 10
b =4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
# print bitwise left shift operation
print(a << 2)
Output
0
14
-11
14
2
40
Assignment Operators
Assignment operators are used to assign values to the variables.
Operator Description Syntax
= Assign value of right side of expression to left side x=y+z
operand
+= Add AND: Add right-side operand with left side a+=b a=a+b
operand and then assign to left operand
-= Subtract AND: Subtract right operand from left a-=b a=a-b
operand and then assign to left operand
*= Multiply AND: Multiply right operand with left a*=b a=a*b
operand and then assign to left operand
/= Divide AND: Divide left operand with right operand a/=b a=a/b
and then assign to left operand
%= Modulus AND: Takes modulus using left and right a%=b a=a%b
operands and assign the result to left operand
//= Divide(floor) AND: Divide left operand with right a//=b a=a//b
operand and then assign the value(floor) to left
operand
**= Exponent AND: Calculate exponent(raise power) value a**=b a=a**b
using operands and assign value to left operand
&= Performs Bitwise AND on operands and assign value a&=b a=a&b
to left operand
|= Performs Bitwise OR on operands and assign value to a|=b a=a|b
left operand
^= Performs Bitwise xOR on operands and assign value to a^=b a=a^b
left operand
>>= Performs Bitwise right shift on operands and assign a>>=b a=a>>b
value to left operand
<<= Performs Bitwise left shift on operands and assign a <<= b a= a <<
value to left operand b
Python3
a = 10
# Assign value
b =a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
Output
10
20
10
100
102400
Identity Operators
is and is not are the identity operators both are used to check if two values are located
on the same part of the memory. Two variables that are equal do not imply that they
are identical.
is True if the operands are identical
is not True if the operands are not identical
Example: Identity Operator
Python3
a = 10
b = 20
c =a
print(a is not b)
print(a is c)
Output
True
True
Membership Operators
in and not in are the membership operators; used to test whether a value or variable is
in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
Example: Membership Operator
Python3
x = 24
y = 20
if (x not in list):
else:
if (y in list):
else:
Output
x is NOT present in given list
y is present in given list
Precedence and Associativity of Operators
Precedence and Associativity of Operators: Operator precedence and associativity
determine the priorities of the operator.
Operator Precedence
This is used in an expression with more than one operator with different precedence to
determine which operation to perform first.
Python3
expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0
print("Hello! Welcome.")
else:
print("Good Bye!!")
Output
610
Hello! Welcome.
Operator Associativity
If an expression contains two or more operators with the same precedence then
Operator Associativity is used to determine. It can either be Left to Right or from
Right to Left.
Example: Operator Associativity
Python3
# Left-right associativity
# 100 / 10 * 10 is calculated as
print(100 / 10 * 10)
# Left-right associativity
# 5 - 2 + 3 is calculated as
# (5 - 2) + 3 and not
# as 5 - (2 + 3)
print(5 - 2 + 3)
# left-right associativity
print(5 - (2 + 3))
# right-left associativity
# 2 ** 3 ** 2 is calculated as
# 2 ** (3 ** 2) and not
# as (2 ** 3) ** 2
print(2 ** 3 ** 2)
Output
100.0
6
0
512
Python Comments
We'll study how to write comments in our program in this article. We'll also learn about
single-line comments, multi-line comments, documentation strings, and other Python
comments.
Single-Line Comments
Single-line remarks in Python have shown to be effective for providing quick
descriptions for parameters, function definitions, and expressions. A single-line
comment of Python is the one that has a hashtag # at the beginning of it and continues
until the finish of the line. If the comment continues to the next line, add a hashtag to
the subsequent line and resume the conversation. Consider the accompanying code
snippet, which shows how to use a single line comment:
Code
Output:
Everything following the # is omitted. As a result, we may put the program mentioned
above in one line as follows:
Code
1. print( 'This is not a comment' ) # this code is to show an example of a single-line comment
Output:
This program's output will be identical to the example above. The computer overlooks
all content following #.
Multi-Line Comments
Python does not provide the facility for multi-line comments. However, there are
indeed many ways to create multi-line comments.
In Python, we may use hashtags (#) multiple times to construct multiple lines of
comments. Every line with a (#) before it will be regarded as a single-line comment.
Code
1. # it is a
2. # comment
3. # extending to multiple lines
In this case, each line is considered a comment, and they are all omitted.
Because Python overlooks string expressions that aren't allocated to a variable, we can
utilize them as comments.
AD
Code
We can observe that on running this code, there will be no output; thus, we utilize the
strings inside triple quotes(""") as multi-line comments.
Python Docstring
The strings enclosed in triple quotes that come immediately after the defined function
are called Python docstring. It's designed to link documentation developed for Python
modules, methods, classes, and functions together. It's placed just beneath the
function, module, or class to explain what they perform. The docstring is then readily
accessible in Python using the __doc__ attribute.
Code
Output:
Statement Description
If Statement The if statement is used to test a specific condition. If the condition is true,
a block of code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also
Statement provides the block of the code for the false case of the condition to be
checked. If the condition provided in the if statement is false, then the else
statement will be executed.
Nested if Nested if statements enable us to use if ? else statement inside an outer if
Statement statement.
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use
of parentheses for the block level code. In Python, indentation is used to declare a
block. If two statements are at the same indentation level, then they are the part of the
same block.
Generally, four spaces are given to indent the statements which are a typical amount
of indentation in python.
Indentation is the most used part of the python language since it declares the block
of code. All the statements of one block are intended at the same level indentation.
We will see how the actual indentation takes place in decision making and other stuff
in python.
The if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be any
valid logical expression which can be either evaluated to true or false.
The syntax of the if-statement is given below.
1. if expression:
2. statement
Example 1
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even")
Output:
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.
The syntax of the if-else statement is given below.
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
Example 1 : Program to check whether a person is eligible
to vote or not.
1. age = int (input("Enter your age? "))
2. if age>=18:
3. print("You are eligible to vote !!");
4. else:
5. print("Sorry! you have to wait !!");
Output:
Output:
AD
The elif statement works like an if-else-if ladder statement in C. It must be succeeded
by an if statement.
1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements
Example 1
1. number = int(input("Enter the number?"))
2. if number==10:
3. print("number is equals to 10")
4. elif number==50:
5. print("number is equal to 50");
6. elif number==100:
7. print("number is equal to 100");
8. else:
9. print("number is not equal to 10, 50 or 100");
Output:
Python
# while loop
count = 0
count = count + 1
print("Hello Dhiru")
Output:
Hello Dhiru
Hello Dhiru
Hello Dhiru
Using else statement with while loops
As discussed above, while loop executes the block until a condition is satisfied. When
the condition becomes false, the statement immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you
break out of the loop, or if an exception is raised, it won’t be executed.
If else like this:
if condition:
# execute these statements
else:
# execute these statements
and while loop like this are similar
while condition:
# execute these statements
else:
# execute these statements
Examples:
Python
count = 0
count = count + 1
print("Hello Dhiru")
else:
Output:
Hello Dhiru
Hello Dhiru
Hello Dhiru
In Else Block
Single statement while block
Just like the if block, if the while block consists of a single statement then we can
declare the entire loop in a single line as shown below:
Python
count = 0
Note: It is suggested not to use this type of loops as it is a never ending infinite loop
where the condition is always true and you have to forcefully terminate the compiler.
For Loop in Python
For loops are used for sequential traversal. For example: traversing a list or string or
array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for
in” loop which is similar to for each loop in other languages. Let us learn how to use
for in loop for sequential traversals.
Syntax:
for iterator_var in sequence:
statements(s)
It can be used to iterate over a range and iterators.
Python3
n =4
print(i)
Output :
0
1
2
3
Example with List, Tuple, string, and dictionary iteration using For Loops
Python
print("List Iteration")
l = ["dhiru", "for", "dhiru"]
for i in l:
print(i)
print("\nTuple Iteration")
for i in t:
print(i)
print("\nString Iteration")
s = "Dhirus"
for i in s:
print(i)
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d:
print("\nSet Iteration")
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i),
Output:
List Iteration
dhirus
for
dhirus
Tuple Iteration
dhirus
for
dhirus
String Iteration
G
e
e
k
s
Dictionary Iteration
xyz 123
abc 345
We can also use the index of elements in the sequence to iterate. The key idea is to
first calculate the length of the list and in iterate over the sequence within the range of
this length.
See the below example:
Python
# Iterating by index
print list[index]
Output:
dhirus
for
dhirus
Using else statement with for loops:
We can also combine else statement with for loop like in while loop. But as there is no
condition in for loop based on which the execution will terminate so the else block
will be executed immediately after for block finishes execution.
Below example explains how to do this:
Python
print (list[index])
else:
Output:
dhirus
for
dhirus
Inside Else Block
Nested Loops
Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.
Syntax:
Python
# Python program to illustrate
for j in range(i):
print()
Output:
1
2 2
3 3 3
4 4 4 4
Python
continue
Output:
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Break Statement:
It brings control out of the loop
Python
# or 's'
break
Output:
Current Letter : e
Pass Statement:
We use pass statement to write empty loops. Pass is also used for empty control
statements, functions and classes.
Python
# An empty loop
pass
Output:
Last Letter : s
Python3
print(fruit)
Output
apple
orange
kiwi
Here we can see the for loops iterates over iterable object fruit which is a list. Lists,
sets, dictionaries are few iterable objects while an integer object is not an iterable
object.
For loops can iterate over any iterable object (example: List, Set, Dictionary, Tuple or
String).
Now with the help of the above example, let’s dive deep and see what happens
internally here.
1. Make the list (iterable) an iterable object with help of the iter() function.
2. Run an infinite while loop and break only if the StopIteration is raised.
3. In the try block, we fetch the next element of fruits with the next() function.
4. After fetching the element we did the operation to be performed with the element.
(i.e print(fruit))
Python3
iter_obj = iter(fruits)
while True:
try:
fruit = next(iter_obj)
print(fruit)
except StopIteration:
# if StopIteration is raised,
break
Output
apple
orange
kiwi
We can see that under the hood we are calling iter() and next() method.
The break is commonly used in the cases where we need to break the loop for a given
condition.
1. #loop statements
2. break;
Example 1
1. list =[1,2,3,4]
2. count = 1;
3. for i in list:
4. if i == 4:
5. print("item matched")
6. count = count + 1;
7. break
8. print("found at",count,"location");
Output:
item matched
found at 2 location
Example 2
1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);
Output:
p
y
t
h
1. i = 0;
2. while 1:
3. print(i," ",end=""),
4. i=i+1;
5. if i == 10:
6. break;
7. print("came out of while loop");
Output:
Example 3
1. n=2
2. while 1:
3. i=1;
4. while i<=10:
5. print("%d X %d = %d\n"%(n,i,n*i));
6. i = i+1;
7. choice = int(input("Do you want to continue printing the table, press 0 for no?"))
8. if choice == 0:
9. break;
10. n=n+1
Output:
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
Both Python while and Python for loops can leverage the continue statements.
Output:
10
11
12
13
14
16
17
18
19
20
Now will repeat the above code, but this time with a string. We will take a string
"Javatpoint" and print each letter of the string except "a". This time we will use Python
while loop to do so. Until the value of the iterator is less than the string's length, the
while loop will keep executing.
Code
1. # Creating a string
2. string = "dhirendra"
3. # initializing an iterator
4. iterator = 0
5.
6. # starting a while loop
7. while iterator < len(string):
8. # if loop is at letter a it will skip the remaining code and go to next iteration
9. if string[iterator] == 'a':
10. continue
11. # otherwise it will print the letter
12. print(string[ iterator ])
13. iterator += 1
Output:
d
h
i
r
e
n
d
r
Definition The continue statement is utilized to skip The pass keyword is used
the current loop's remaining statements, when a phrase is necessary
go to the following iteration, and return syntactically to be placed but
control to the beginning. not to be executed.
Action It takes the control back to the start of Nothing happens if the
the loop. Python interpreter encounters
the pass statement.
Application It works with both the Python while and It performs nothing; hence it is
Python for loops. a null operation.
Syntax It has the following syntax: -: continue Its syntax is as follows:- pass
We can use the pass statement as a placeholder when unsure what code to provide.
So, we only have to place the pass on that line. Pass may be used when we don't wish
any code to be executed. We can simply insert a pass in places where empty code is
prohibited, such as loops, functions, class definitions, or if-else statements.
1. Keyword:
2. pass
Let's say we have a loop or an if-else statement that isn't to be filled now but that we
wish to in the future. The pass keyword cannot have an empty body as it will be
syntactically wrong. An error would be displayed by the Python interpreter suggesting
to fill the space. Therefore, we create a code block that performs nothing using the
pass statement.
Code
1. # Python program to show how to create an empty function and an empty class
2.
3. # Empty function:
4. def empty():
5. pass
6.
7. # Empty class
8. class Empty:
9. pass
Python Functions
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")
Try it Yourself »
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")
Try it Yourself »
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")
Try it Yourself »
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])
Try it Yourself »
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)
Try it Yourself »
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"])
Try it Yourself »
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Try it Yourself »
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)
Try it Yourself »
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))
Try it Yourself »
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
Recursion
Python also accepts function recursion, which means a defined function can
call itself.
The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.
To a new developer it can take some time to work out how exactly this
works, best way to find out is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
Approach:
o We can choose the desired operation from the option of a, b, c, and d.
o We can take two numbers, and if… elif… else, branching is used for executing the
particular operation.
o We will use add(), subtract(), multiply() and divide() function for evaluation the
respective operation in the calculator.
Example:
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
Fibonacci sequence:
A Fibonacci sequence is a sequence of integers which first two terms are 0 and 1 and
all other terms of the sequence are obtained by adding their preceding two numbers.
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
# take input from the user
nterms = int(input("How many terms? "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Output:
Python Program to Find Factorial of
Number Using Recursion
Factorial: Factorial of a number specifies a product of all integers from 1 to that
number. It is defined by the symbol explanation mark (!).
1. def recur_factorial(n):
2. if n == 1:
3. return n
4. else:
5. return n*recur_factorial(n-1)
6. # take input from the user
7. num = int(input("Enter a number: "))
8. # check is the number is negative
9. if num < 0:
10. print("Sorry, factorial does not exist for negative numbers")
11. elif num == 0:
12. print("The factorial of 0 is 1")
13. else:
14. print("The factorial of",num,"is",recur_factorial(num))
Python List
In this tutorial, we'll learn everything about Python lists: creating lists,
changing list elements, removing elements, and other list operations with
the help of examples.
Python lists are one of the most versatile data types that allow us to work
with multiple elements at once. For example,
separated by commas.
# list of integers
my_list = [1, 2, 3]
A list can have any number of items and they may be of different types
(integer, float, string, etc.).
# empty list
my_list = []
# list with mixed data types
my_list = [1, "Hello", 3.4]
A list can also have another list as an item. This is called a nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
List Index
# first item
print(my_list[0]) # p
# third item
print(my_list[2]) # o
# fifth item
print(my_list[4]) # e
# Nested List
n_list = ["Happy", [2, 0, 1, 5]]
# Nested indexing
print(n_list[0][1])
print(n_list[1][3])
Output
p
o
e
a
5
Traceback (most recent call last):
File "<string>", line 21, in <module>
TypeError: list indices must be integers or slices, not float
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to
the last item, -2 to the second last item and so on.
# last item
print(my_list[-1])
Output
e
p
List indexing in
Python
my_list = ['p','r','o','g','r','a','m','i','z']
Output
print(odd)
print(odd)
Run Code
Output
[1, 4, 6, 8]
[1, 3, 5, 7]
We can add one item to a list using the append() method or add several
items using the extend() method.
# Appending and Extending lists in Python
odd = [1, 3, 5]
odd.append(7)
print(odd)
print(odd)
Run Code
Output
[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]
We can also use + operator to combine two lists. This is also called
concatenation.
The * operator repeats a list for the given number of times.
# Concatenating and repeating lists
odd = [1, 3, 5]
print(["re"] * 3)
Run Code
Output
[1, 3, 5, 9, 7, 5]
['re', 're', 're']
print(odd)
odd[2:2] = [5, 7]
print(odd)
Run Code
Output
[1, 3, 9]
[1, 3, 5, 7, 9]
print(my_list)
print(my_list)
Output
We can use remove() to remove the given item or pop() to remove an item at
the given index.
The pop() method removes and returns the last item if the index is not
provided. This helps us implement lists as stacks (first in, last out data
structure).
And, if we have to empty the whole list, we can use the clear() method.
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# Output: 'o'
print(my_list.pop(1))
# Output: 'm'
print(my_list.pop())
my_list.clear()
# Output: []
print(my_list)
Run Code
Output
my_list = [3, 8, 1, 6, 8, 8, 4]
print(currencies)
list.append(item)
append() Parameters
The method takes a single argument
item - an item (number, string, list etc.) to be added at the end of the list
Output
Output
In the program, a single item ( wild_animals list) is added to the animals list.
Note: If you need to add items of a list (rather than the list itself) to another
list, use the extend() method.
The extend() method adds all the elements of an iterable (list, tuple, string
etc.) to the end of the list.
Example
# create a list
prime_numbers = [2, 3, 5]
list1.extend(iterable)
Here, all the elements of iterable are added to the end of list1 .
extend() Parameters
As mentioned, the extend() method takes an iterable such as list, tuple,
string etc.
Output
# languages tuple
languages_tuple = ('Spanish', 'Portuguese')
# languages set
languages_set = {'Chinese', 'Japanese'}
Output
You can also append all elements of an iterable to the list using:
1. the + operator
a = [1, 2]
b = [3, 4]
a += b # a = a + b
# Output: [1, 2, 3, 4]
print('a =', a)
Run Code
Output
a = [1, 2, 3, 4]
a[len(a):] = b
# Output: [1, 2, 3, 4]
print('a =', a)
Run Code
Output
a = [1, 2, 3, 4]
If you need to add an element to the end of a list, you can use
the append() method.
a1 = [1, 2]
a2 = [1, 2]
b = (3, 4)
# a1 = [1, 2, 3, 4]
a1.extend(b)
print(a1)
Output
[1, 2, 3, 4]
[1, 2, (3, 4)]
The index() method returns the index of the specified element in the list.
Example
animals = ['cat', 'dog', 'rabbit', 'horse']
# get the index of 'dog'
index = animals.index('dog')
print(index)
# Output: 1
Run Code
Output
The index of e: 1
The index of i: 2
Output
Output
The index of e: 1
The index of i: 6
Traceback (most recent call last):
File "*lt;string>", line 13, in
ValueError: 'i' is not in list
Python List insert()
In this tutorial, we will learn about the Python List insert() method with the
help of examples.
The insert() method inserts an element to the list at the specified index.
Example
print('List:', vowel)
list.insert(i, elem)
Here, elem is inserted to the list at the ith index. All the elements
after elem are shifted to the right.
insert() Parameters
The insert() method takes two parameters:
index - the index where the element needs to be inserted
element - this is the element to be inserted in the list
Notes:
If index is 0, the element is inserted at the beginning of the list.
If index is 3, the index of the inserted element will be 3 (4th element in the
list).
# insert 11 at index 4
prime_numbers.insert(4, 11)
print('List:', prime_numbers)
Run Code
Output
# number tuple
number_tuple = (3, 4)
Output
The remove() method removes the first matching element (which is passed
as an argument) from the list.
Example
# create a list
prime_numbers = [2, 3, 5, 7, 9, 11]
list.remove(element)
remove() Parameters
The remove() method takes a single element as an argument and removes
it from the list.
If the element doesn't exist, it throws ValueError: list.remove(x): x not in
list exception.
# 'rabbit' is removed
animals.remove('rabbit')
# Updated animals List
print('Updated animals list: ', animals)
Run Code
Output
# 'dog' is removed
animals.remove('dog')
Output
Here, only the first occurrence of element 'dog' is removed from the list.
Output
If you need to delete elements based on the index (like the fourth element),
you can use the pop() method.
Also, you can use the Python del statement to remove items from the list.
The count() method returns the number of times the specified element
appears in the list.
Example
# create a list
numbers = [2, 3, 5, 2, 11, 2, 7]
# Output: Count of 2: 3
Run Code
list.count(element)
count() Parameters
The count() method takes a single argument:
element - the element to be counted
# print count
print('The count of i is:', count)
# print count
print('The count of p is:', count)
Run Code
Output
# print count
print("The count of ('a', 'b') is:", count)
# print count
print("The count of [3, 4] is:", count)
Run Code
Output
The pop() method removes the item at the given index from the list and
returns the removed item.
Example
# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]
# Output:
# Removed Element: 5
# Updated List: [2, 3, 7]
Run Code
list.pop(index)
pop() parameters
The pop() method takes a single argument (index).
The argument passed to the method is optional. If not passed, the default
index -1 is passed as an argument (index of the last item).
If the index passed to the method is not in range, it throws IndexError: pop
index out of range exception.
# Updated List
print('Updated List:', languages)
Run Code
Output
If you need to pop the 4th element, you need to pass 3 to the pop() method.
Output
When -1 is passed:
Return Value: Ruby
Updated List: ['Python', 'Java', 'C++']
When -3 is passed:
Return Value: Python
Updated List: ['Java', 'C++']
If you need to remove the given item from the list, you can use
the remove() method.
And, you can use the del statement to remove an item or slices from the
list.
reverse() parameter
The reverse() method doesn't take any arguments.
# List Reverse
systems.reverse()
# updated list
print('Updated List:', systems)
Run Code
Output
# Reversing a list
# Syntax: reversed_list = systems[start:stop:step]
reversed_list = systems[::-1]
# updated list
print('Updated List:', reversed_list)
Run Code
Output
Output
Linux
macOS
Windows
prime_numbers = [11, 3, 7, 5, 2]
print(prime_numbers)
sort() Syntax
The syntax of the sort() method is:
list.sort(key=..., reverse=...)
Alternatively, you can also use Python's built-in sorted() function for the
same purpose.
sort() Parameters
By default, sort() doesn't require any extra parameters. However, it has
two optional parameters:
reverse - If True , the sorted list is reversed (or sorted in Descending order)
key - function that serves as a key for the sort comparison
# print vowels
print('Sorted list:', vowels)
Run Code
Output
list.sort(reverse=True)
sorted(list, reverse=True)
# print vowels
print('Sorted list (in Descending):', vowels)
Run Code
Output
# mixed list
prime_numbers = [2, 3, 5]
# copying a list
numbers = prime_numbers.copy()
copy() Syntax
The syntax of the copy() method is:
new_list = list.copy()
copy() Parameters
The copy() method doesn't take any parameters.
copy() Return Value
The copy() method returns a new list. It doesn't modify the original list.
# copying a list
new_list = my_list.copy()
Output
If you modify the new_list in the above example, my_list will not be
modified.
old_list = [1, 2, 3]
new_list = old_list
Howerver, there is one problem with copying lists in this way. If you
modify new_list , old_list is also modified. It is because the new list is
referencing or pointing to the same old_list object.
old_list = [1, 2, 3]
Output
However, if you need the original list unchanged when the new list is
modified, you can use the copy() method.
Related tutorial: Python Shallow Copy Vs Deep Copy
# mixed list
list = ['cat', 0, 6.7]
Output
list.clear()
clear() Parameters
The clear() method doesn't take any parameters.
print('List:', list)
Run Code
Output
List: []
Note: If you are using Python 2 or Python 3.2 and below, you cannot use
the clear() method. You can use the del operator instead.
print('List:', list)
Run Code
Output
List: []
Output
pow2 = []
for x in range(10):
pow2.append(2 ** x)
# Output: True
print('p' in my_list)
# Output: False
print('a' in my_list)
# Output: True
print('c' not in my_list)
Run Code
Output
True
False
True
Output
I like apple
I like banana
I like mango
Python Dictionary
Dictionary in Python is a collection of keys values, used to store data values like a
map, which, unlike other data types which hold only a single value as an element.
Example of Dictionary in Python
Dictionary holds key: value pair. Key-Value is provided in the dictionary to make it
more optimized.
print(Dict)
Output:
{1: 'Pythons', 2: 'For', 3: 'Pythons'}
Creating a Dictionary
In Python, a dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’. Dictionary holds pairs of values, one being the
Key and the other corresponding pair element being its Key:value. Values in a
dictionary can be of any data type and can be duplicated, whereas keys can’t be
repeated and must be immutable.
Note – Dictionary keys are case sensitive, the same name but different cases of Key
will be treated distinctly.
Python3
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
Output:
Dictionary with the use of Integer Keys:
{1: 'Pythons', 2: 'For', 3: 'Pythons'}
Dictionary with the use of Mixed Keys:
{'Name': 'Pythons', 1: [1, 2, 3, 4]}
Dictionary can also be created by the built-in function dict(). An empty dictionary can
be created by just placing to curly braces{}.
Python3
# Creating an empty Dictionary
Dict = {}
print(Dict)
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'Pythons', 2: 'For', 3: 'Pythons'}
Dictionary with each item as a pair:
{1: 'Pythons', 2: 'For'}
Complexities for Creating a Dictionary:
Time complexity: O(len(dict))
Space complexity: O(n)
Nested Dictionary
print(Dict)
Output:
{1: 'Pythons', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C':
'Pythons'}}
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Pythons', 2: 'For', 3: 1}
Dictionary after adding 3 elements:
{0: 'Pythons', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'Pythons', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'Pythons', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5:
{'Nested': {'1': 'Life', '2': 'Pythons'}}}
Complexities for Adding elements in a Dictionary:
Time complexity: O(1)/O(n)
Space complexity: O(1)
Accessing elements of a Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used
inside square brackets.
Python3
# Creating a Dictionary
print(Dict['name'])
print(Dict[1])
Output:
Accessing a element using key:
For
Accessing a element using key:
Pythons
There is also a method called get() that will also help in accessing the element from a
dictionary.This method accepts key as argument and returns the value.
Complexities for Accessing elements in a Dictionary:
Time complexity: O(1)
Space complexity: O(1)
Python3
# Creating a Dictionary
# method
print(Dict.get(3))
Output:
Accessing a element using get:
Pythons
Python3
# Creating a Dictionary
Dict = {'Dict1': {1: 'Pythons'},
'Dict2': {'Name': 'For'}}
Output:
{1: 'Pythons'}
Pythons
For
Dictionary methods
clear() – Remove all the elements from the dictionary
copy() – Returns a copy of the dictionary
get() – Returns the value of specified key
items() – Returns a list containing a tuple for each key value pair
keys() – Returns a list containing dictionary’s keys
pop() – Remove the element with specified key
popitem() – Removes the last inserted key-value pair
update() – Updates dictionary with specified key-value pairs
values() – Returns a list of all the values of dictionary
Python3
# demo for all dictionary methods
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
# copy() method
dict2 = dict1.copy()
print(dict2)
# clear() method
dict1.clear()
print(dict1)
# get() method
print(dict2.get(1))
# items() method
print(dict2.items())
# keys() method
print(dict2.keys())
# pop() method
dict2.pop(4)
print(dict2)
# popitem() method
dict2.popitem()
print(dict2)
# update() method
dict2.update({3: "Scala"})
print(dict2)
# values() method
print(dict2.values())
Output:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])
Python Tuples
A Python Tuple is a group of items that are separated by commas. The indexing, nested
objects, and repetitions of a tuple are somewhat like those of a list, however unlike a
list, a tuple is immutable.
The distinction between the two is that while we can edit the contents of a list, we
cannot alter the elements of a tuple once they have been assigned.
Example
Creating of Tuple:
To create a tuple, all the objects (or "elements") must be enclosed in parenthesis (),
each one separated by a comma. Although it is not necessary to include parentheses,
doing so is advised.
A tuple can contain any number of items, including ones with different data types
(dictionary, string, float, list, etc.).
Code:
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Tuples can be constructed without using parentheses. This is known as triple packing.
Code
Output:
Code
1. # Python program to show how to create a tuple having a single element
2. single_tuple = ("Tuple")
3. print( type(single_tuple) )
4. # Creating a tuple that has only one element
5. single_tuple = ("Tuple",)
6. print( type(single_tuple) )
7. # Creating tuple without parentheses
8. single_tuple = "Tuple",
9. print( type(single_tuple) )
Output:
<class 'str'>
<class 'tuple'>
<class 'tuple'>
Accessing Tuple Elements
We can access the objects of a tuple in a variety of ways.
o Indexing
ADTo access an object of a tuple, we can use the index operator [], where indexing in the tuple
starts from 0.
A tuple with 5 items will have indices ranging from 0 to 4. An IndexError will be raised
if we try to access an index from the tuple that is outside the range of the tuple index.
In this case, an index above 4 will be out of range.
AD
We cannot give an index of a floating data type or other kinds because the index in
Python must be an integer. TypeError will appear as a result if we give a floating index.
The example below illustrates how indexing is performed in nested tuples to access
elements.
Code
Output:
Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6
o Negative Indexing
AD
The last item of the collection is represented by -1, the second last item by -2, and so
on.
Code
Output:
Slicing
In Python, tuple slicing is a common practise and the most popular method for
programmers to handle practical issues. Think about a Python tuple. To access a variety
of elements in a tuple, you must slice it. One approach is to use the colon as a
straightforward slicing operator (:).
We can use a slicing operator, a colon (:), to access a range of tuple elements.
Code
1. # Python program to show how slicing works in Python tuples
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
4. # Using slicing to access elements of the tuple
5. print("Elements between indices 1 and 3: ", tuple_[1:3])
6. # Using negative indexing in slicing
7. print("Elements between indices 0 and -4: ", tuple_[:-4])
8. # Printing the entire tuple by using the default start and end values.
9. print("Entire tuple: ", tuple_[:])
Output:
Deleting a Tuple
A tuple's components cannot be altered, as was previously said. As a result, we are
unable to get rid of or remove tuple components.
Code
Output:
Output:
o Count () Method
The number of times the specified element occurs in the tuple is returned by the count
() function of Tuple.
Code
1. # Creating tuples
2. T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
3. T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
4. # counting the appearance of 3
5. res = T1.count(2)
6. print('Count of 2 in T1 is:', res)
7. # counting the appearance of java
8. res = T2.count('java')
9. print('Count of Java in T2 is:', res)
Output:
Count of 2 in T1 is: 5
Count of java in T2 is: 2
Index() Method:
The first instance of the requested element from the tuple is returned by the Index()
function.
Parameters:
o begin (Optional): the index used as the starting point for searching
o final (optional): The last index up until which the search is conducted
o Index() Method
Code
# Creating tuples
Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
res = Tuple_data.index(3)
print('First occurrence of 1 is', res)
# getting the index of 3 after 4th
# index
res = Tuple_data.index(3, 4)
print('First occurrence of 1 after 4th index is:', res)
Output:
First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6
Output:
True
False
False
True
Iterating Through a Tuple
We can use a for loop to iterate through each element of a tuple.
Code
Output:
Python
Tuple
Ordered
Immutable
Changing a Tuple
Tuples, as opposed to lists, are immutable objects.
This suggests that we are unable to change a tuple's elements once they have been
defined. The nested elements of an element can be changed, though, if the element
itself is a changeable data type like a list.
A tuple can be assigned to many values (reassignment).
Code
Output:
To merge multiple tuples, we can use the + operator. Concatenation is the term for
this.
Using the * operator, we may also repeat a tuple's elements for a specified number of
times. This is already shown above.
Code
The code is protected from any unintentional changes thanks to tuples. It is preferable
to store non-changing data in "tuples" rather than "lists" if it is required by a
programme.
If a tuple includes immutable values like strings, numbers, or another tuple, it can be
used as a dictionary key. Since "lists" are mutable, they cannot be utilized as dictionary
keys.
Python String
A string is a data structure in Python that represents a sequence of characters. It is an
immutable data type, meaning that once you have created a string, you cannot change
it. Strings are used widely in many different applications, such as storing and
manipulating text data, representing names, addresses, and other types of data that can
be represented as text.
Example:
"PythonsforPythons" or 'PythonsforPythons'
Python does not have a character data type, a single character is simply a string with a
length of 1. Square brackets can be used to access elements of the string.
Python3
Output:
A Computer Science portal for Pythons
# Creating a String
# with single Quotes
String1 = 'Welcome to the Pythons World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Python"
print("\nString with the use of Double Quotes: ")
print(String1)
# Creating a String
# with triple Quotes
String1 = '''I'm a Python and I live in a world of "Pythons"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Pythons World
Python3
# Python Program to Access
# characters of String
String1 = "PythonsForPythons"
print("Initial String: ")
print(String1)
Output:
Initial String:
PythonsForPythons
Python3
#Program to reverse a string
gfg = "PythonsforPythons"
print(gfg[::-1])
Output:
skeegrofskeeg
We can also reverse a string by using built-in join and reversed function.
Python3
# Program to reverse a string
gfg = "PythonsforPythons"
print(gfg)
Output:
skeegrofskeeg
String Slicing
To access a range of characters in the String, the method of slicing is used. Slicing in a
String is done by using a Slicing operator (colon).
Python3
# Python Program to
# demonstrate String slicing
# Creating a String
String1 = "PythonsForPythons"
print("Initial String: ")
print(String1)
Output:
Initial String:
PythonsForPythons
Python3
# Python Program to Update
# character of a String
#2
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)
Error:
Traceback (most recent call last):
File “/home/360bb1830c83a918fc78aa8979195653.py”, line 10, in
String1[2] = ‘p’
TypeError: ‘str’ object does not support item assignment
Updating Entire String:
Python3
# Python Program to Update
# entire String
# Updating a String
String1 = "Welcome to the Python World"
print("\nUpdated String: ")
print(String1)
Output:
Initial String:
Hello, I'm a Python
Updated String:
Welcome to the Python World
Deletion of a character:
Python3
# Python Program to Delete
# characters from a String
# Deleting a character
# of the String
String2 = String1[0:2] + String1[3:]
print("\nDeleting character at 2nd Index: ")
print(String2)
Error:
Initial String:
Hello, I’m a Python
Deleting character at 2nd Index:
Helo, I’m a Python
Deleting Entire String:
Deletion of the entire string is possible with the use of del keyword. Further, if we try
to print the string, this will produce an error because String is deleted and is
unavailable to be printed.
Python3
# Python Program to Delete
# entire String
# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)
Error:
Traceback (most recent call last):
File “/home/e4b8f2170f140da99d2fe57d9d8c6a94.py”, line 12, in
print(String1)
NameError: name ‘String1’ is not defined
Python3
# Python Program for
# Escape Sequencing
# of String
# Initial String
String1 = '''I'm a "String"'''
print("Initial String with use of Triple Quotes: ")
print(String1)
Output:
Initial String with use of Triple Quotes:
I'm a "Python"
Escaping Single Quote:
I'm a "Python"
Escaping Double Quotes:
I'm a "Python"
Escaping Backslashes:
C:\Python\Pythons\
Tab:
Hi Pythons
New Line:
Python
Pythons
To ignore the escape sequences in a String, r or R is used, this implies that the string
is a raw string and escape sequences inside it are to be ignored.
Python3
# Printing hello in octal
String1 = "\110\145\154\154\157"
print("\nPrinting in Octal with the use of Escape Sequences: ")
print(String1)
Output:
Printing in Octal with the use of Escape Sequences:
Hello
Printing Raw String in Octal Format:
This is \110\145\154\154\157
Printing in HEX with the use of Escape Sequences:
This is Pythons in HEX
Printing Raw String in HEX Format:
This is \x47\x65\x65\x6b\x73 in \x48\x45\x58
Formatting of Strings
Strings in Python can be formatted with the use of format() method which is a very
versatile and powerful tool for formatting Strings. Format method in String contains
curly braces {} as placeholders which can hold arguments according to position or
keyword to specify the order.
Python3
# Python Program for
# Formatting of Strings
# Default order
String1 = "{} {} {}".format('Pythons', 'For', 'Life')
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('Pythons', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)
# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Pythons', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)
Output:
Print String in default order:
Pythons For Life
Python3
# Formatting of Integers
String1 = "{0:b}".format(16)
print("\nBinary representation of 16 is ")
print(String1)
# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)
Output:
Binary representation of 16 is
10000
one-sixth is :
0.17
A string can be left() or center(^) justified with the use of format specifiers, separated
by a colon(:).
Python3
# String alignment
String1 = "|{:<10}|{:^10}|{:>10}|".format('Pythons',
'for',
'Pythons')
print("\nLeft, center and right alignment with Formatting: ")
print(String1)
Output:
Left, center and right alignment with Formatting:
|Pythons | for | Pythons|
Integer1 = 12.3456789
print("Formatting in 3.2f format: ")
print('The value of Integer1 is %3.2f' % Integer1)
print("\nFormatting in 3.4f format: ")
print('The value of Integer1 is %3.4f' % Integer1)
Output:
Formatting in 3.2f format:
The value of Integer1 is 12.35
Output:
class 'str'
class 'str'
5.0
Note: float values are decimal values that can be used with integers for computation.
Python3
# a file named "geek", will be opened with the reading mode.
file = open('geek.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)
The open command will open the file in the read mode and the for loop will print each
line present in the file.
Working of read() mode
There is more than one way to read a file in Python. If you need to extract a string that
contains all characters in the file then we can use file.read(). The full code would
work like this:
Python3
# Python code to illustrate read() mode
file = open("file.txt", "r")
print (file.read())
Another way to read a file is to call a certain number of characters like in the
following code the interpreter will read the first five characters of stored data and
return it as a string:
Python3
# Python code to illustrate read() mode character wise
file = open("file.txt", "r")
print (file.read(5))
Python3
# Python code to create a file
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
The close() command terminates all the resources in use and frees the system of this
particular program.
Working of append() mode
Let us see how the append mode works:
Python3
# Python code to illustrate append() mode
file = open('geek.txt', 'a')
file.write("This will add this line")
file.close()
There are also various other commands in file handling that is used to handle various
tasks like:
rstrip(): This function strips each line of a file off spaces from
the right-hand side.
lstrip(): This function strips each line of a file off spaces from
the left-hand side.
It is designed to provide much cleaner syntax and exception handling when you are
working with code. That explains why it’s good practice to use them with a statement
where applicable. This is helpful because using this method any files opened will be
closed automatically after one is done, so auto-cleanup.
Example:
Python3
data = file.read()
Python3
# Python code to illustrate with() alongwith write()
f.write("Hello World!!!")
Python3
data = file.readlines()
word = line.split()
print (word)
There are also various other functions that help to manipulate the files and their
contents. One can explore various other functions in Python Docs.