1.
Python Features
Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation.
1. Easy to Learn and Use
Python is easy to learn as compared to other programming languages. Its syntax is
straightforward and much the same as the English language. Python is very easy to code as
compared to other popular languages like Java and C++. Anyone can learn Basic Python
syntax in just a few hours. Thus, it is programmer-friendly.
2. Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while Java
or C takes multiple lines.
3. Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.
4. Portable 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. It enables programmers to develop the
software for several competing platforms by writing a program only once.
5. Free and Open Source
Python is freely available for everyone. It is freely available on its official
website www.python.org. Anyone can download its source code without paying any penny.
6. Object-Oriented Language
Python supports object-oriented language. It supports inheritance, polymorphism, and
encapsulation, etc. The object-oriented procedure helps to write reusable code and develop
applications in less code.
7. Extensible
If needed, some of Python code can be written in other languages like C or C++. This makes
Python an extensible language, meaning that it can be extended to other languages.
8. Large Standard Library
It provides a vast range of libraries for the various fields such as machine learning, web
development, and also for the scripting. There are also libraries for regular expressions,
documentation-generation, unit-testing, web browsers, threading, databases, CGI, email, image
manipulation, and a lot of other functionality.
9. GUI Programming Support
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy
are the libraries which are used for developing the web application.
10. Embeddable
It is also possible to Python code in a source code in a different language like C or C++.
11. Dynamically Typed
Python is dynamically-typed. This means that the type for a value is decided at runtime, not in
advance. We don’t need to specify the type of data while declaring it.
2. Python Data Types
Data types are the classification or categorization of data items. It represents the kind of value
that tells what operations can be performed on a particular data. Since everything is an object
in Python programming, data types are actually classes and variables are instance (object) of
these classes.
Following are the standard or built-in data type of Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
Numeric data type represent the data which has numeric value. These values are defined as
int, float and complex class in Python.
Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an integer
value can be.
Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E followed
by a positive or negative integer may be appended to specify scientific notation.
Complex Numbers – Complex number is represented by complex class. It is specified
as (real part) + (imaginary part)j.
For example – 2+3j
Sequence Type
Sequence is the ordered collection of similar or different data types. Sequences allows to store
multiple values in an organized and efficient fashion. There are several sequence types in
Python –
String
List
Tuple
Strings are arrays of bytes representing Unicode characters. A string is a collection of one or
more characters put in a single quote, double-quote or triple quote.
Lists are just like the arrays, which is an ordered collection of data. It is very flexible as the
items in a list do not need to be of the same type. Lists in Python can be created by just
placing the sequence inside the square brackets[].
Tuple: is also an ordered collection of Python objects. The only difference between type and
list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is
represented by tuple class. tuples are created by placing a sequence of values separated by
‘comma’ with parentheses for grouping of the data sequence.
Boolean: Data type with one of the two built-in values, True or False. Boolean objects that
are equal to True are truthy (true), and those equal to False are falsy (false).
Set: is an unordered collection of data type that is iterable, mutable and has no duplicate
elements. The order of elements in a set is undefined though it may consist of various
elements. Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces, separated by ‘comma’.
Dictionary: is an unordered collection of data values, used to store data values. Dictionary
holds key:value pair. Each key-value pair in a Dictionary is separated by a colon ‘ :’.
A Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’. Values in a dictionary can be of any datatype and can be duplicated,
whereas keys can’t be repeated and must be immutable. Dictionary can also be created by the
built-in function dict(). An empty dictionary can be created by just placing it to curly
braces{}.
3. Define string and discuss built-in functions on strings
A string is a collection of one or more characters put in a single quote, double-quote or triple
quote. Python has a set of built-in methods.
Method Description
count() Returns the number of times a specified value occurs in a string
capitalize() Converts the first character to upper case
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
join() Joins the elements of an iterable to the end of the string
lower() Converts a string into lower case
upper() Converts a string into upper case
swapcase() Swaps cases, lower case becomes upper case and vice versa
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
4. Define dictionary and discuss built-in functions on dictionaries?
Dictionary: is an unordered collection of data values, used to store data values. Dictionary
holds key:value pair. Each key-value pair in a Dictionary is separated by a colon ‘ :’.
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
values() Returns a list of all the values in the dictionary
update() Updates the dictionary with the specified key-value pairs
pop() Removes the element with the specified key
5. Difference between List, Set and Tuple in Python
List: Lists are like dynamic sized arrays that can store any data element in it.
The main characteristics of lists are –
The list is a datatype available in Python which can be written as a list of
comma-separated values (items) between square brackets.
List are mutable .i.e it can be converted into another data type and can store any
data element in it.
List can store any type of element.
Example Program on List:
#Creating an empty List
List = []
print("Blank List: ")
print(List)
# Creating a List of numbers
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)
# Creating a List of strings and accessing using index
List = ["Geeks", "For", "Geeks"]
print("\nList Items: ")
print(List[0])
print(List[2])
Output:
Blank List:
[]
List of numbers:
[10, 20, 14]
List Items:
Geeks
Geeks
Tuple: Tuple is a collection of Python objects much like a list. The sequence of values
stored in a tuple can be of any type, and they are indexed by integers. Values of a tuple
are syntactically separated by ‘commas’ and enclosed in parentheses.
The main characteristics of tuples are –
Tuple is an immutable sequence in python.
It cannot be changed or replaced since it is immutable.
It is defined under parenthesis().
Tuples can store any type of element.
Example Program on Tuple:
#Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
# Creating a Tuple with the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
#Creating a Tuple with the use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)
Output:
Initial empty Tuple:
()
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
('G', 'e', 'e', 'k', 's')
Set: In Python, Set is an unordered collection of data type that is iterable, mutable, and
has no duplicate elements. The major advantage of using a set, as opposed to a list, is that
it has a highly optimized method for checking whether a specific element is contained in
the set.
The main characteristics of set are –
Sets are an unordered collection of elements
The order in which the elements are added into the set is not fixed, it can change
frequently.
It is defined under curly braces{}
Sets are mutable, however, only immutable objects can be stored in it.
Example Program on Set:
#Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
# Creating a Set with the use of Constructor
String = 'GeeksForGeeks'
set1 = set(String)
print("\nSet with the use of an Object: " )
print(set1)
# Creating a Set with the use of a List
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)
Output:
Initial blank Set:
set()
Set with the use of an Object:
{'G', 's', 'e', 'o', 'r', 'F', 'k'}
Set with the use of List:
{'Geeks', 'For'}
6. Discuss various categories of operators available in python?
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
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:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Miltiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x**y
// Floor Division x//y
#Program showing usage of Arithmetic operators:
Num1=10
Num2=20
print(“Num1+Num2=“, num1+num2)
print(“Num1-Num2=“, num1-num2)
print(“Num1*Num2=“, num1*num2)
print(“Num1/Num2=“, num1/num2)
print(‘5^3=‘, 5**3) # 5 power 3
print(“20%3=“, 20%3) # remainder is 2
print(“22//7=“, 22//7) # integer division
Assignment operators are used to assign values to variables:
Comparison operators are used to compare two values:
Logical operators are used to combine conditional statements:
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:
Membership operators are used to test if a sequence is presented in an object:
Bitwise operators are used to perform operations on individual bits of a number:
7. Discuss the conditional statements in Python?
The if statement contains a logical expression using which data is compared and a
decision is made based on the result of the comparison.
Syntax:
if expression:
statements
If the boolean expression evaluates to TRUE, then the block of statement(s) inside
the if statement is executed. If boolean expression evaluates to FALSE, then the first
set of code after the end of the if statement(s) is executed.
if Statement Flowchart:
Example:
a=3
if a > 2:
print(a, "is greater")
Alternative if (If-Else):
An else statement can be combined with an if statement. An else statement contains
the block of code (false block) that executes if the conditional expression in the if
statement resolves to 0 or a FALSE value.
Syntax of if - else :
if test expression:
Body of if stmts
else:
Body of else stmts
Example of if - else:
a=int(input('enter the number'))
if a>5:
print("a is greater")
else:
print("a is smaller than the input given")
Chained Conditional: (If-elif-else):
The elif statement allows us to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE.
Syntax of if – elif - else :
if test expression:
Body of if stmts
elif test expression:
Body of elif stmts
else:
Body of else stmts
Example of if - elif – else:
a=int(input('enter the number'))
b=int(input('enter the number'))
c=int(input('enter the number'))
if a>b:
print("a is greater")
elif b>c:
print("b is greater")
else:
print("c is greater")
8. Explain the iterative statements of python?
A loop statement allows us to execute a statement or group of statements multiple times
as long as the condition is true.
Repeated execution of a set of statements with the help of loops is called iteration.
Loops statements are used when we need to run same code again and again, each time
with a different value.
In Python Iteration (Loops) statements are of three types:
1. While Loop
2. For Loop
3. Nested For Loops
While loop:
The while loop contains a boolean expression and the code inside the loop is
repeatedly executed as long as the boolean expression is true.
The statements that are executed inside while can be a single line of code or a
block of multiplestatements.
Syntax:
while(expression):
Statement(s)
Flowchart:
Example:
i=1
whilei<=6:
print("Mrcet college")
i=i+1
For loop:
Python for loop is used for repeated execution of a group of statements for the desired
number of times. It iterates over the items of lists, tuples, strings, the dictionaries and
other iterable objects
Syntax:
for var in sequence:
Statement(s)
A sequence of values assigned to var in each iteration holds the value of item
in sequence in each iteration
Flowchart:
Example:
#Iterating over a list
numbers = [1, 2, 4, 6, 11, 20]
sum=0
for val in numbers :
sum+=val
print(sum)
Iterating over a dictionary:
#creating a dictionary
college = {"ces":"block1","it":"block2","ece":"block3"}
for i in college.items() :
print(i)
Nested For loop:
When one Loop defined within another Loop is called Nested Loops.
Syntax:
for val in sequence:
for val in sequence:
statements
Example:
for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')