Python (Module-I)
Python (Module-I)
What is a Program?
A computer program is a collection of instructions that can be executed by
a computer to perform a specific task.
A computer program is usually written by a computer p r ogrammer in a
programming language. From the program in its human-readable form of source
code, a compiler or assembler can derive machine code—a form consisting of
instructions that the computer can directly execute. Alternatively, a computer
program may be executed with the aid of an interpreter.
2. Interpreter:
An interpreter is a program that translates a programming language into a
comprehensible language. –
It translates only one statement of the program at a time.
Interpreters, more often than not are smaller than compilers.
S.No. Compiler Interpreter
2 As it scans the code in one go, the Considering it scans code one line at
errors (if any) are shown at the a time, errors are shown line by line.
end together.
4. It converts the source code into It does not convert source code into
object code. object code instead it scans it line
by line
5 It does not require source code It requires source code for later
for later execution. execution.
Python History
Python was developed by Guido van Rossum in the late eighties and early
C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under
although Guido van Rossum still holds a vital role in directing its progress.
There is a fact behind choosing the name Python. Guido van Rossum was reading
the script of a popular BBC comedy series "Monty Python's Flying Circus". It
was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit
mysterious. So he decided to select naming Python after the "Monty Python's
Flying Circus" for their newly created programming language.
The comedy series was creative and well random. It talks about everything.
Thus it is slow and unpredictable, which made it very interesting.
Features of Python
Easy to Learn and Use: Python is easy to learn and use. It is developer-
friendly and high-level programming language.
Expressive Language: Python language is more expressive means that it is
more understandable and readable.
Interpreted Language: Python is an interpreted language i.e. interpreter
executes the code line by line at a time. This makes debugging easy and thus
suitable for beginners.
Cross-platform Language: Python can run equally on different platforms such
as Windows, Linux, Unix and Macintosh etc. So, we can say that Python is a
portable language.
Free and Open Source: Python language is freely available at official web
address. The source code is also available. Therefore, it is open source.
Object-Oriented Language: Python supports object-oriented language and
concepts of classes and objects come into existence.
Extensible: It implies that other languages such as C/C++ can be used to
compile the code and thus it can be used further in our python code.
Large Standard Library: Python has a large and broad library and provides a
rich set of modules and functions for rapid application development.
GUI Programming Support: Graphical user interfaces can be developed using
Python.
Integrated: It can be easily integrated with languages like C, C++, JAVA, etc.
Platform independent: Write once and run anywhere
Dynamically typed Language: We cannot require specifying the data type
explicitly. Dynamically typed language provides more flexibility to the
programmer. We are not fixed the type of the variable.
Python comments
A comment is text that doesn’t affect the outcome of a code; it is just
a piece of text to let someone know what you have done in a program or what
is being done in a block of code.
This is especially helpful when someone else has written a code and you are
analyzing it for bug fixing or making a change in logic, by reading a comment
you can understand the purpose of code much faster than by just going
through the actual code.
Types of Comments in Python
There are two types of comments in Python.
1. Single-line comment
2. Multiple-line comment
Single line comment
In python we use # special character to start the comment. Let’s take few
examples to understand the usage.
# This is just a comment. Anything written here is ignored by Python
Multi-line comment:
To have a multi-line comment in Python, we use triple single quotes at the
beginning and at the end of the comment, as shown below.
'''
This is a
multi-line
comment
'''
or assert None
We can get the list of keywords in your current version by typing the
following in the prompt.
>>> help("keywords")
(or)
>>> import keyword
>>> print(keyword.kwlist)
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc.
Valid Identifiers:
Names like myClass, var_1 and print_this_to_screen, all are valid example.
Invalid Identifiers:
1variable is invalid
global is invalid
ab@ is invalid
Things to Remember
Python is a case-sensitive language. This means, Variable and variable are not
the same.
Always give the identifiers a name that makes sense. While c = 10 is a valid
name, writing count = 10 would make more sense, and it would be easier to
figure out what it represents when you look at your code after a long gap.
Multiple words can be separated using an underscore,
like this_is_a_long_variable.
Variable
Variables are nothing but reserved memory locations to store values. It
means that when you create a variable, you reserve some space in the
memory.
Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning
different data types to the variables, you can store integers, decimals or
characters in these variables.
Example −
#!/usr/bin/python3
print (counter)
print (miles)
print (name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and
name variables, respectively.
This produces the following result −
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example −
a = b = c = 1
Here, an integer object is created with the value 1, and all the three variables
are assigned to the same memory location.
You can also assign multiple objects to multiple variables.
For example −
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a
and b respectively, and one string object with the value "john" is assigned to the
variable c.
Input/output Statements
Python input( ) function
The input() method reads a line from input, converts into a string and returns
it.
Syntax
input(prompt)
prompt(optional) → A String, representing a default message before the input.
Examples
>>> x = input()
2
>>> x
'2'
>>> x1 = input("Enter a String")
Enter a String 2
>>> x1
' 2'
>>> y = int(input("Enter a number"))
Enter a number2
>>> y
2
>>> y1 = float(input("Enter a floating value"))
Enter a floating value 2.5
>>> y1
2.5
Python print()
The print() function prints the given object to the standard output device
(screen) or to the text stream file.
Syntax of print()
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
print() Parameters
objects - object to the printed. * indicates that there may be more than one
object
sep - objects are separated by sep. Default value: ' '
end - end is printed at last
file - must be an object with write(string) method. If omitted
it, sys.stdout will be used which prints objects on the screen.
flush - If True, the stream is forcibly flushed. Default value: False
Examples:
>>> print("Hello","world")
Hello world
>>> print("hello","world",sep="")
helloworld
>>> print("hello","world",sep="-")
hello-world
>>> print(192,168,17,1,sep=".")
192.168.17.1
print_st.py
print("Welcome to python",end=" ")
print("programming")
output
Welcome to python programming
Python indentation
Python indentation uses to define the block of the code. The other
programming languages such as C, C++, and Java use curly braces {}, whereas
Python uses an indentation. Whitespaces are used as indentation in Python.
Indentation uses at the beginning of the code and ends with the unintended
line. That same line indentation defines the block of the code (body of a
function, loop, etc.)
Generally, four whitespaces are used as the indentation. The amount of
indentation depends on user, but it must be consistent throughout that block.
for i in range(5):
print(i)
if(i == 3):
break
To indicate a block of code we indented each line of the block by the same
whitespaces.
Consider the following example.
print("Task Complete")
Output:
The above code, if and else are two separate code blocks. Both code blocks
are indented four spaces. The print("Task Complete") statement is not
indented four whitespaces and it is out of the if-else block.
If the indentation is not used properly, then that will result
in IndentationError.
Data types
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.
Example
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<class 'int'>
<class 'str'>
<class 'float'>
All integer literals or variables are objects of the int class. Use
the type() method to get the class name, as shown below.
>>>type(100)
<class 'int'> # type of x is int
>>> x=1234567890
>>> type(x)
<class 'int'> # type of x is int
>>> y=5000000000000000000000000000000000000000000000000000000
>>> type(y) # type of y is int
<class 'int'>
Leading zeros in non-zero integers are not allowed e.g. 000123 is invalid number,
0000 is 0.
>>> x=01234567890
SyntaxError: invalid token
>>> x=1_234_567_890
>>> x
1234567890
Note that integers must be without a fractional part (decimal point). It includes
a fractional then it becomes a float.
>>> x=5
>>> type(x)
<class 'int'>
>>> x=5.0
>>> type(x)
<class 'float'>
>>> int('100')
100
>>> int('-10')
-10
>>> int('5.5')
5
>>> int('100', 2)
4
Binary
A number having 0b with eight digits in the combination of 0 and 1 represent
the binary numbers in Python. For example, 0b11011000 is a binary number
equivalent to integer 216.
>>> x=0b11011000
>>> x
216
>>> x=0b_1101_1000
>>> x
216
>>> type(x)
<class 'int'>
Octal
A number having 0o or 0O as prefix represents an octal number. For example,
0O12 is equivalent to integer 10.
>>> x=0o12
>>> x
10
>>> type(x)
<class 'int'>
Hexadecimal
A number with 0x or 0X as prefix represents hexadecimal number.
For example, 0x12 is equivalent to integer 18.
>>> x=0x12
>>> x
18
>>> type(x)
<class 'int'>
Float
In Python, floating point numbers (float) are positive and negative real
numbers with a fractional part denoted by the decimal symbol or the
scientific notation E or e,
Example: 1234.56, 3.142, -1.55, 0.23.
>>> f=1.2
>>> f
1.2
>>> type(f)
<class 'float'>
>>> f=123_42.222_013
>>> f
12342.222013
>>> f=2e400
>>> f
inf
>>> f=1e3
>>> f
1000.0
>>> f=1e5
>>> f
100000.0
>>> f=3.4556789e2
>>> f
345.56789
>>> float('5.5')
5.5
>>> float('5')
5.0
>>> float(' -5')
-5.0
>>> float('1e3')
1000.0
>>> float('-Infinity')
-inf
>>> float('inf')
inf
Complex Number
A complex number is a number with real and imaginary components.
Example: 5 + 6j is a complex number where 5 is the real component and 6
multiplied by j is an imaginary component.
>>> a=5+2j
>>> a
(5+2j)
>>> type(a)
<class 'complex'>
You must use j or J as imaginary component. Using other character will throw
syntax error.
>>> a=5+2k
SyntaxError: invalid syntax
>>> a=5+j
SyntaxError: invalid syntax
>>> a=5j+2j
>>> a
7j
Sequence types
A sequence is a group of items with a deterministic ordering.
String
In Python, string is an immutable sequence data type.
It is the sequence of Unicode characters wrapped inside single, double, or
triple quotes.
str1='''This is
the first
Multi-line string.
'''
print(str1)
str2="""This is
the second
Multi-line
string."""
print(str2)
Output:
This is
the first
Multi-line string.
This is
the second
Multi-line
string.
If a string literal required embedding double quotes as part of a string then, it
should be put in single quotes. Likewise, if a string includes a single quote as a
part of a string then, it should be written in double quotes.
Output:
>>> greet='Hello'
>>> len(greet)
5
The sequence uses an index, starting with zero to fetch a certain item (a
character in case of a string) from it.
Positive Indexing 0 1 2 3 4
H e l l o
Negative Indexing -5 -4 -3 -2 -1
>>> greet='hello'
>>> greet[0]
'h'
>>> greet[1]
'e'
>>> greet[2]
'l'
>>> greet[3]
'l'
>>> greet[4]
'o'
>>> greet[5] # throw error if index > len(string)-1
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
greet[5]
IndexError: string index out of range
Python supports negative indexing too, starting with -(length of string) till -1.
>>> greet='hello'
>>> greet[-5]
'h'
>>> greet[-4]
'e'
>>> greet[-3]
'l'
>>> greet[-2]
'l'
>>> greet[-1]
'o'
The string is an immutable object. Hence, it is not possible to modify it. The
attempt to assign different characters at a certain index results in errors.
>>> greet='hello'
>>> greet[0]='A'
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
greet[0]='A'
TypeError: 'str' object does not support item assignment
str Class
>>> greet='hello'
>>> type(greet)
<class 'str'>
>>> str(100)
'100'
>>> str(-10)
'-10'
>>> str(True)
'True'
Escape Sequences
Output:
Output:
\f Form feed
List
In Python, the list is a mutable sequence type. A list object contains one or
more items of different data types in the square brackets [] separated by a
comma.
A list can contain unlimited data depending upon the limitation of your
computer's memory.
nums=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]
List items can be accessed using a zero-based index in the square brackets [].
Indexes start from zero and increment by one for each item. Accessing an item
using a large index than the list's total items would result in IndexError.
Negative Indexing
names = ['Jeff', 'Bill', 'Steve', 'Yash']
print(names[-4]) # prints 'Jeff'
print(names[-3]) # prints 'Bill'
print(names[-2]) # prints 'Steve'
print(names[-1]) # prints 'Yash'
A list can contain multiple inner lists as items that can be accessed using
indexes.
List Class
All the list objects are the objects of the list class in Python. Use
the list() constructor to convert from other sequence types such as tuple, set,
dictionary, string to list.
nums=[1,2,3,4]
print(type(nums))
mylist=list('Hello')
print(mylist)
nums=list({1:'one',2:'two'})
print(nums)
Output:
<class 'list'>
['H', 'e', 'l', 'l', 'o']
[1, 2]
[10, 20, 30]
[100, 200, 300]
Tuples
()
('Jeff', 'Bill', 'Steve', 'Yash')
(1, 2, 3, 4, 5)
(1, 'Steve', True, 25, 12000)
'Jeff'
<class 'string'>
(Jeff)
<class 'tuple'>
Access Tuple Elements
Each element in the tuple is accessed by the index in the square brackets []. An
index starts with zero and ends with (number of elements – 1).
Example:
nums = (1, 2, 3, 4, 5)
print(nums[0]) # prints 1
print(nums[1]) # prints 2
print(nums[4]) # prints 5
Output:
Jeff
Bill
Steve
Yash
1
2
5
The tuple supports negative indexing also, the same as list type. The negative
index for the first element starts from -number of elements and ends with -1
for the last element.
Example: Negative Indexing
Jeff
Bill
Steve
Yash
If the element at the specified index does not exist, then the error "index out
of range" will be thrown.
>>> names[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
Tuple elements can be unpacked and assigned to variables, as shown below.
However, the number of variables must match with the number of elements in a
tuple; otherwise, an error will be thrown.
Example: Access Tuple Elements using Indexes
Tuple is unchangeable. So, once a tuple is created, any operation that seeks to
change its contents is not allowed. For instance, trying to modify or delete an
element of names tuple will result in an error.
>>> names = ('Jeff', 'Bill', 'Steve', 'Yash')
>>> names[0] = 'Swati'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
However, you can delete an entire tuple using the del keyword.
>>> del names
Tuple Class
The underlying type of a tuple is the tuple class. Check the type of a variable
using the type() function.
Example:
names = ('Jeff', 'Bill', 'Steve', 'Yash')
print('names type: ', type(names))
nums = (1,2,3,4,5)
print('nums type: ', type(nums))
Output:
names type: <class 'tuple'>
nums type: <class 'tuple'>
The tuple() constructor is used to convert any iterable to tuple type.
Example:
tpl = tuple('Hello') # converts string to tuple
print(tpl)
tpl = tuple([1,2,3,4,5]) # converts list to tuple
print(tpl)
Output:
('H','e','l','l','o')
(1,2,3,4,5)
range() Method
The range() method returns the immutable sequence numbers between the
specified start and the stop parameter, increment by step parameter.
Syntax:
range(start, stop, step)
Parameters:
start: (Optional) An integer to start counting from, defaults to 0.
stop: An integer to stop the count at.
step: (Optional) An integer that indicates the incremental value from start
parameter value, defaults to 1.
Return Value:
Returns an immutable sequence object of numbers.
Example: range()
num_range = range(5) #start=0, stop=5, step=1
print(type(num_range))
print(num_range)
print('Values = ', num_range[0], num_range[1], num_range[2],
num_range[3], num_range[4])
Output
<class 'range'>
range(0, 5)
Values = 0 1 2 3 4
In the above example, the range(5) returns the range object with the default
start 0, stop 5, and default step 1. The range is an immutable sequence, so that
values can be accessed by passing indexes in the square brackets [].
The in operator is used to check whether the particular number exists in the
range sequence or not, as shown below.
Example:
num_range = range(5) #start=0, stop=5, step=1
print(0 in num_range)
print(4 in num_range)
print(5 in num_range)
print(6 in num_range)
Output
True
True
False
False
The range object can be converted to the other iterable types such as list,
tuple, and set.
Example: Convert Range to other Iterables
print(list(range(5)))
print(tuple(range(5)))
print(set(range(5)))
Output
[0, 1, 2, 3, 4]
(0, 1, 2, 3, 4)
{0, 1, 2, 3, 4}
The following creates a different range objects with different values of start
and step parameters.
Example: range()
num_range1 = range(1, 5) #start=1, stop=5, step=1
print('range(1, 5) = ', list(num_range1))
Dictionary
The dictionary is an unordered collection that contains key:value pairs
separated by commas inside curly brackets. Dictionaries are optimized to
retrieve values when the key is known.
Example: Dictionary
capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New
Delhi"}
Above, capitals is a dictionary object which contains key-value pairs inside { }.
The left side of : is a key, and the right side is a value. The key should be unique
and an immutable object. A number, string or tuple can be used as key. Hence,
the following dictionaries are also valid:
Example: Dictionary Objects
d = {} # empty dictionary
items={("Parker","Reynolds","Camlin"):"pen",
("LG","Whirlpool","Samsung"): "Refrigerator"} # tuple key, string
value
Access Dictionary
Dictionary is an unordered collection, so a value cannot be accessed using an
index; instead, a key must be specified in the square brackets.
Example: Get Dictionary Values
>>> capitals = {"USA":"Washington DC", "France":"Paris",
"India":"New Delhi"}
>>>capitals["USA"]
'Washington DC'
>>> capitals["France"]
'Paris'
>>> capitals["usa"] # Error: Key is case-sensitive
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
capitals['usa']
KeyError: 'usa'
>>> capitals["Japan"] # Error: key must exist
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
capitals['Japan']
KeyError: 'Japan'
Note:
Keys are case-sensitive. So, usa and USA are treated as different keys. If the
specified key does not exist then it will raise an error.
Set
A set is a mutable collection of distinct hashable objects, same as
the list and tuple. It is an unordered collection of objects, meaning it does not
record element position or order of insertion and so cannot access elements
using indexes.
A set object contains one or more items, not necessarily of the same type,
which are separated by a comma and enclosed in curly brackets {}.
Example: Python Set Object
even_nums = {2, 4, 6, 8, 10} # set of even numbers
emp = {1, 'Steve', 10.5, True} # set of different objects
A set doesn't store duplicate objects. Even if an object is added more than
once inside the curly brackets, only one copy is held in the set object. Hence,
indexing and slicing operations cannot be done on a set object.
Example: Set of Distinct Elements
>>> nums = {1, 2, 2, 3, 4, 4, 5, 5}
>>> nums
{1, 2, 3, 4, 5}
The order of elements in the set is not necessarily the same as the order given
at the time of assignment. Python optimizes the structure of a set for
performing operations over it, as defined in mathematics.
Only immutable (and hashable) objects can be a part of a set object. Numbers
(integer, float, as well as complex), strings, and tuple objects are accepted, but
set, list, and dictionary objects are not.
Example: Set Elements
>>> myset = {(10,10), 10, 20} # valid
>>> myset
{10, 20, (10, 10)}
>>> myset = {[10, 10], 10, 20} # can't add a list
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
myset = {[10, 10], 10, 20}
TypeError: unhashable type: 'list'
>>> myset = { {10, 10}, 10, 20} # can't add a set
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
myset = { {10, 10}, 10, 20}
TypeError: unhashable type: 'set'
In the above example, (10,10) is a tuple, hence it becomes part of the set.
However, [10,10] is a list, hence an error message is displayed saying that the
list is unhashable. (Hashing is a mechanism in computer science which enables
quicker search of objects in the computer's memory.)
Even though mutable objects are not stored in a set, the set itself is a mutable
object.
Use the set() function to create an empty set. Empty curly braces will create an
empty dictionary instead of an empty set.
Example: Creating an Empty Set
>>> emp = {} # creates an empty dictionary
>>> type(emp)
<class 'dict'>
>>> s = set() # creates an empty set
>>> type(s)
<class 'set'>
The set() function also use to convert string, tuple, or dictionary object to a set
object.
frozenset()
The python frozenset() function returns an immutable frozenset object
initialized with elements from the given iterable.
syntax
frozenset(iterable)
Parameters
iterable: An iterable object such as list, tuple etc.
Return
It returns an immutable frozenset object initialized with elements from the
given iterable.
Example
working of frozenset().
# tuple of letters
letters = ('m', 'r', 'o', 't', 's')
fSet = frozenset(letters)
print('Frozen set is:', fSet)
print('Empty frozen set is:', frozenset())
Output:
Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})
Empty frozen set is: frozenset()
In the above example, we take a variable that consists tuple of letters and
returns an immutable frozenset object.
Example
working of frozenset() with dictionaries.
# random dictionary
person = {"name": "Phill", "age": 22, "sex": "male"}
fSet = frozenset(person)
print('Frozen set is:', fSet)
Output:
Frozen set is: frozenset({'name', 'sex', 'age'})
bool()
The bool() method converts a value to the bool class object containing either
True or False.
Syntax:
bool(value)
Parameters:
value: (Optional) The value to be converted to boolean.
Return Value:
Returns True for truthy value else returns False for falsy value 0, None or ''
Example:
value = [0]
print("Boolean of [0] is: ", bool(value))
value = 0
print("Boolean of 0 is: ", bool(value))
value = 1
print("Boolean of 1 is: ", bool(value))
value = -1
print("Boolean of -1 is: ", bool(value))
value = None
print("Boolean of None is: ",bool(value))
value = True
print("Boolean of True is: ", bool(value))
value = False
print("Boolean of False is: ", bool(value))
Output
Boolean of [0] is: True
Boolean of 0 is: False
Boolean of 1 is: True
Boolean of -1 is: True
Boolean of None is: False
Boolean of True is: True
Boolean of False is: False
Boolean of a string is: True
Type Checking
Type Checking is the programming language feature that specifies how the
variables are created and their types are identified by the language compiler or
interpreter.
Python is a dynamically typed language. This means that the Python interpreter
does type checking only as code runs, and that the type of a variable is allowed
to change over its lifetime.
type()
Python type() returns the type of the specified object if a single argument is
passed to the type().
Syntax
type(object)
Parameter
The object argument is required, and it can be string,
integer, list, tuple, set, dictionary, float, etc.
Example
str = 'Hello'
print(type(str))
int = 123
print(type(int))
float = 21.19
print(type(float))
negative = -19
print(type(negative))
dictionary = {'name':'King', 'age': 36}
print(type(dictionary))
list = [1, 2, 3]
print(type(list))
tuple = (19, 21, 46)
print(type(tuple))
output
<class 'str'>
<class 'int'>
<class 'float'>
<class 'int'>
<class 'dict'>
<class 'list'>
<class 'tuple'>
isinstance()
Python isinstance() function is used to check if an object is an instance of the
specified class or not.
syntax
isinstance(object, classinfo)
This function returns True if the object is instance of classinfo argument or
instance of classinfo subclass.
If the object is not an instance of classinfo or its subclass, then the function
returns False.
classinfo argument can be a tuple of types. In that case, isinstance() will
return True if the object is an instance of any of the types.
If classinfo is not a type or tuple of types, a TypeError exception is raised.
Example
i = 10
print('i is int:', isinstance(i, int))
f = 10.5
print('f is float:', isinstance(f, float))
s = 'a'
print('s is str:', isinstance(s, str))
t = (1, 2)
print('t is tuple:', isinstance(t, tuple))
li = []
print('li is list:', isinstance(li, list))
d = {}
print('d is dict:', isinstance(d, dict))
output
i is int: True
f is float: True
s is str: True
t is tuple: True
li is list: True
d is dict: True
Formatted String
Python uses C-style string formatting to create new, formatted strings.
The "%" operator is used to format a set of variables enclosed in a
"tuple" (a fixed size list), together with a format string, which contains
normal text together with "argument specifiers", special symbols like
"%i","%f","%s" and "%d".
%i → int
%d → int
%f → float
%s → String type
Syntax
print("formatted string" %(variable list))
Example
a = 10
b = 20
c = 30
print("a value is %i" %a)
print("b value is %d and c value is %d" %(b,c))
Output
a value is 10
b value is 20 and c value is 30
Example
s = “Durga”
list = [10,20,30,40]
print("Hello %s ...The List of Items are %s" %(s,list))
Output
Hello Durga ...The List of Items are [10, 20, 30, 40]
format()
This method lets us concatenate elements within a string through positional
formatting.
The format() method formats the specified value(s) and insert them inside
the string's placeholder.
The placeholder is defined using curly brackets: {}. The placeholders can be
identified using named indexes {price}, numbered indexes {0}, or even
empty placeholders {}.
The format() method returns the formatted string. print() with replacement
operator {}
Syntax
string.format(value1, value2...)
Example
#named indexes:
txt = "My name is {Name}, I'm {age}".format(Name = "John", age = 36)
#numbered indexes:
txt2 = "My name is {0}, I'm {1}".format("John",36)
#empty placeholders:
txt3 = "My name is {}, I'm {}".format("John",36)
print(txt)
print(txt2)
print(txt3)
Output
My name is John, I’m 36
My name is John, I’m 36
My name is John, I’m 36