CH 1
CH 1
1 Fundamentals of Python
Topics Covered
What is Python?
• Python is a general purpose, dynamic, high-level, and interpreted programming
language.
• It supports Object Oriented programming approach to develop applications.
• It is simple and easy to learn and provides lots of high-level data structures.
• 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 supports multiple programming pattern, including object-oriented, imperative,
and functional or procedural programming styles.
• 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.
Features of Python
• 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.
• We have listed below a few essential features.
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. 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.
• It enables programmers to develop the software for several competing platforms by
writing a program only once.
6. Object-Oriented Language:
• Python supports object-oriented language and concepts of classes and objects come into
existence.
• It supports inheritance, polymorphism, and encapsulation, etc.
• The object-oriented procedure helps to programmer to write reusable code and develop
applications in less code.
7. 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.
• It converts the program into byte code, and any platform can use that byte code.
10. Integrated:
• It can be easily integrated with languages like C, C++, and JAVA, etc.
• Python runs code line by line like C,C++ Java. It makes easy to debug the code.
11. Embeddable:
• The code of the other programming language can use in the Python source code.
• We can use Python source code in another programming language as well.
Python Applications
• Python is known for its general-purpose nature that makes it applicable in almost every
domain of software development.
• Python makes its presence in every emerging field.
• It is the fastest-growing programming language and can develop any application.
• Here, we are specifying application areas where Python can be applied.
1. Web Applications:
• We can use Python to develop web applications.
• It provides libraries to handle internet protocols such as HTML and XML, JSON, Email
processing, request, beautifulSoup, Feedparser, etc.
• One of Python web-framework named Django is used on Instagram.
• Python provides many useful frameworks, and these are given below:
Django and Pyramid framework(Use for heavy applications)
3. Console-based Application:
• Console-based applications run from the command-line or shell.
• These applications are computer program which are used commands to execute.
• This kind of application was more popular in the old generation of computers.
• Python can develop this kind of application very effectively.
• It is famous for having REPL, which means the Read-Eval-Print Loop that makes it
the most suitable language for the command-line applications.
• Python provides many free library or module which helps to build the command-line
apps.
• The necessary IO libraries are used to read and write.
• It helps to parse argument and create console help text out-of-the-box.
• There are also advance libraries that can develop independent console apps.
4. Software Development:
• Python is useful for the software development process.
• It works as a support language and can be used to build control and management,
testing, etc.
SCons is used to build control.
Buildbot and Apache Gumps are used for automated continuous compilation and
testing.
Round or Trac for bug tracking and project management.
SciPy
Scikit-learn
NumPy
Pandas
Matplotlib
6. Business Applications:
• Business Applications differ from standard applications.
• E-commerce and ERP are an example of a business application.
• This kind of application requires extensively, scalability and readability, and Python
provides all these features.
• Oddo is an example of the all-in-one Python-based application which offers a range of
business applications.
• Python provides a Tryton platform which is used to develop the business application.
8. 3D CAD Applications:
• The CAD (Computer-aided design) is used to design engineering related architecture.
• It is used to develop the 3D representation of a part of a system.
• Python can create a 3D CAD application by using the following functionalities.
Fandango (Popular )
CAMVOX
HeeksCNC
AnyCAD
RCAM
9. Enterprise Applications:
• Python can be used to create applications that can be used within an Enterprise or an
Organization.
• Some real-time applications are OpenERP, Tryton, Picalo, etc.
Installation of Python
How to Install Python (Environment Set-up)?:
• In order to become Python developer, the first step is to learn how to install or update
Python on a local machine or computer.
• We will discuss the installation of Python on various operating systems.
Installation on Windows:
• Visit the link https://www.python.org/downloads/ to download the latest release
of Python.
• In this process, we will install Python 3.8.6 on our Windows operating system.
• When we click on the above link, it will bring us the following page.
Double-click the executable file, which is downloaded; the following window will
open. Select Customize installation and proceed. Click on the Add Path check box, it
will set the Python path automatically.
We can also click on the customize installation to choose desired location and features.
Other important thing is install launcher for the all user must be checked.
• Here, we get the message "Hello World !" printed on the console.
print ("hello world"); #here, we have used print() function to print the message on the
console.
• To run this file named as hello.py, we need to run the following command on the
terminal.
Step - 1: Open the Python interactive shell, and click "File" then choose "New", it will open a
new blank script in which we can write our code.
Step -2: Now, write the code and press "Ctrl+S" to save the file.
Step - 3: After saving the code, we can run it by clicking "Run" or "Run Module". It will
display the output to the shell.
Step - 4: Apart from that, we can also run the file using the operating system terminal. But, we
should be aware of the path of the directory where we have saved our file.
• Open the command line prompt and navigate to the directory.
• We need to type the python keyword, followed by the file name and hit enter to run the
Python file.
Keywords/Reserved Words
• Python has a set of keywords that are reserved words that cannot be used as variable
names, function names, or any other identifiers:
• All the Python keywords contain lowercase letters only.
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
With Used to simplify exception handling
Yield To end a function, returns a generator
Python Variables
• Variable is a name that is used to refer to memory location.
• Python variable is also known as an identifier and used to hold value.
• In Python, we don't need to specify the type of variable because Python is a infer
language and smart enough to get variable type.
• Variable names can be a group of both the letters and digits, but they have to begin with
a letter or an underscore.
• It is recommended to use lowercase letters for the variable name.
• Rahul and rahul both are two different variables.
• Variables are nothing but reserved memory locations to store values.
• This means that when you create a variable you reserve some space in 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 variables, you can store integers,
decimals or characters in these variables.
Identifier Naming:
• Variables are the example of identifiers.
• An Identifier is used to identify the literals used in the program.
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 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 variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
1. Local Variable:
• Local variables are the variables that declared inside the function and have scope within
the function.
• Let's understand the following example.
Example:
# Declaring a function
def add ():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c=a+b
print("The sum is:", c)
# Calling a function
add ()
Output:
The sum is: 50
Explanation:
• In the above code, we declared a function named add () and assigned a few variables
within the function.
• These variables will be referred to as the local variables which have scope only inside
the function.
• If we try to use them outside the function, we get a following error.
add ()
# Accessing local variable outside the function
print (a)
Output:
The sum is: 50
print(a)
NameError: name ‘a’ is not defined
• We tried to use local variable outside their scope; it threw the NameError.
2. Global Variables:
• Global variables can be used throughout the program, and its scope is in the entire
program.
• We can use global variables inside or outside the function.
• A variable declared outside the function is the global variable by default.
• Python provides the global keyword to use global variable inside the function.
• If we don't use the global keyword, the function treats it as a local variable.
Example:
# Declare a variable and initialize it
x = 101
# Global variable in function
def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To python'
print(x)
mainFunction()
print(x)
Output:
101
Welcome To python
Welcome To python
Explanation:
• In the above code, we declare a global variable x and assign a value to it.
• Next, we defined a function and accessed the declared variable using
the global keyword inside the function.
• Now we can modify its value.
• Then, we assigned a new string value to the variable x.
• Now, we called the function and proceeded to print x.
• It printed the as newly assigned value of x.
• When you call a function, the variables declared inside it are brought into scope.
Output:
<type 'int'>
<type 'str'>
<type 'float'>
1. 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;
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
Output:
The type of a <class 'int'>
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.
2. 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.
• String handling in Python is a straightforward task since Python provides built-in
functions and operators to perform operations in the string.
• In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
• The operator * is known as a repetition operator as the operation "Python" *2 returns
'Python Python'.
• The following example illustrates the string in Python.
Example 1:
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)
Output:
string using double quotes
A multiline
string
Example – 2
str1 = 'hello python' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
Output:
he
o
hello python hello python
hello python 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.
• Consider the following example.
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
Output:
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
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.
• Let's see a simple example of the tuple.
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))
# Tuple slicing
print (tup[1:])
print (tup[0:1])
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
3. Dictionary:
• Dictionary is an unordered set of a key-value pair of items.
• It is like an associative array or a hash table where each key stores a specific value.
• Key can hold any primitive data type, whereas value is an arbitrary Python object.
• The items in the dictionary are separated with the comma (,) and enclosed in the curly
braces {}.
• Consider the following example.
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
# Printing dictionary
print (d)
print (d.keys())
print (d.values())
Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
4. 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.
# Python program to check the boolean type
print(type(True))
print(type(False))
print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
5. 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.
# Creating Empty set
set1 = set()
set2.add(10)
print(set2)
Output:
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}
Type Casting:
• We come across different kinds of arithmetic operations in which multiple data types
are involved and then results are obtained accordingly.
• Here we will discuss both,
1. Implicit type conversion
2. Explicit type conversion
Output:
10
The type of a is <class 'int'>
4.5
The type of b is <class 'float'>
4.0
The type of c is <class 'float'>
5.0
The type of d is <class 'float'>
The product of a and b is 45.0
The addition of c and d is 9.0
a=10.6
print("The type of 'a' before typecasting is ",type(a))
print(int(a))
print("The type of 'a' after typecasting is",type(a))
#initializing the value of b
b=8.3
print("The type of 'b' before typecasting is ",type(b))
print(int(b))
print("The type of 'b' after typecasting is",type(b))
#initializing the value of c
c=7
print("The type of 'c' before typecasting is ",type(c))
print(float(c))
print("The type of 'c' after typecasting is",type(c))
Output:
The type of 'a' before typecasting is <class 'float'>
10
The type of 'a' after typecasting is <class 'float'>
The type of 'b' before typecasting is <class 'float'>
8
The type of 'b' after typecasting is <class 'float'>
The type of 'c' before typecasting is <class 'int'>
7.0
The type of 'c' after typecasting is <class 'int'>
• Where, prompt is a string that is displayed on the string at the time of taking input.
Example 1: Taking input from the user with a message.
# Taking input from the user
name = input("Enter your name: ")
# Output
print("Hello, " + name)
Output:
Enter your name: Krishna
Hello, Krishna
Example 2:
By default input() function takes the user’s input in a string. So, to take the input in the form of
int, you need to use int() along with input function.
add = num + 1
# Output
print(add)
Output:
Enter a number: 25
26
2. Displaying Output(Print()):
• Python provides the print() function to display output to the console.
Syntax:
print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
Parameter Description
value(s) Any value, and as many as you like. Will be converted to string before
printed
sep=’separator’ (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’ (Optional) Specify what to print at the end.Default : ‘\n’
Example:
# Python program to demonstrate
# print() method
print("GFG")
Output:
GFG
GFG
Python@Welcome
Operators:
• The operator can be defined as a symbol which is responsible for a particular operation
between two operands.
• Operators are the pillars of a program on which the logic is built in a specific
programming language.
• Python provides a variety of operators, which are described as follows.
1. Arithmetic operators
2. Comparison operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators:
• Arithmetic operators are used to perform arithmetic operations between two operands.
• It includes + (addition), - (subtraction), *(multiplication), /(divide), %(reminder),
//(floor division), and exponent (**) operators.
• Consider the following table for a detailed explanation of arithmetic operators.
division) produced by dividing the two operands. 11//3 = -4, -11.0//3 = -4.0
2. Comparison Operator:
• Comparison operators are used to comparing the value of the two operands and returns
Boolean true or false accordingly.
• The comparison operators are described in the following table.
• Assume variable a holds 10 and variable b holds 20, then −
3. Assignment Operators:
• The assignment operators are used to assign the value of the right expression to the left
operand.
• The assignment operators are described in the following table.
4. Bitwise Operators:
• The bitwise operators perform bit by bit operation on the values of the two operands.
• Bitwise operator works on bits and performs bit by bit operation.
• Assume if a = 60; and b = 13; Now in the binary format their values will be 0011 1100
and 0000 1101 respectively.
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
• Following table lists out the bitwise operators supported by Python language with an
example each in those, we use the above two variables (a and b) as operands:
5. Logical Operators:
• The logical operators are used primarily in the expression evaluation to make a
decision.
• Python supports the following logical operators.
Operator Description
and If both the expression are true, then the condition will be true. If
a and b are the two expressions, a → true, b → true => a and b
→ true.
or If one of the expressions is true, then the condition will be true. If
a and b are the two expressions, a → true, b → false => a or b →
true.
not If an expression a is true, then not (a) will be false and vice
versa.
6. Membership Operators:
• Python membership operators are used to check the membership of value inside a
Python data structure.
• If the value is present in the data structure, then the resulting value is true otherwise it
returns false.
7. Identity Operators:
• The identity operators are used to decide whether an element certain class or type.
Comments:
• Python Comment is an essential tool for the programmers.
• Comments are generally used to explain the code.
• We can easily understand the code if it has a proper explanation.
• A good programmer must use the comments because in the future anyone wants to
modify the code as well as implement the new module; then, it can be done easily.
• In the other programming language such as C++, It provides the // for single-lined
comment and /*.... */ for multiple-lined comment, but Python provides the single-lined
Python comment.
• To apply the comment in the code we use the hash(#) at the beginning of the statement
or code.
• Let's understand the following example.
• Here we have written comment over the print statement using the hash(#).
• It will not affect our print statement.
Example:
# Variable a holds value 5
# Variable b holds value 10
# Variable c holds sum of a and b
# Print the result
a=5
b = 10
c = a+b
print("The sum is:", c)
Output:
The sum is: 15
• The above code is very readable even the absolute beginners can under that what is
happening in each line of the code.
• This is the advantage of using comments in code.
• We can also use the triple quotes ('''''') for multiline comment.
• The triple quotes are also used to string formatting.
Example:
def intro():
"""
This function prints Hello Joseph
"""
print("Hello Joseph")
intro()
Output:
Hello Joseph