UNIT -1
Python and its History
● Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
OR
● Python is an interpreted, object-oriented, high-level programming language
with dynamic semantics developed by Guido van Rossum.
● It was originally released in 1991.
● Python has a reputation as a beginner-friendly language, replacing Java as
the most widely used introductory language because it handles much of the
complexity for the user, allowing beginners to focus on fully grasping
programming concepts rather than minute details.
● Python laid its foundation in the late 1980s.
● The implementation of Python was started in December 1989 by Guido Van
Rossum at CWI in Netherland.
● In February 1991, Guido Van Rossum published the code (labeled
version0.9.0) to [Link].
● In 1994, Python 1.0 was released with new features like lambda,
map, filter, and reduce.
● Python 2.0 added new features such as list comprehensions,
garbage collection systems.
● On December 3, 2008, Python 3.0 (also called "Py3K") was released.
It was designed to rectify the fundamental flaw of the language.
Where It is used for?
● web development (server-side),
● software development,
● mathematics,
● system scripting.
● Processing
● Fast prototyping
● Developing production-ready software
Why Python?
● Python works on different platforms (Windows, Mac, Linux, Raspberry
Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
● Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be
very quick.
● Python can be treated in a procedural way, an object-oriented way or a
functional way.
Python Install
● Many PCs and Macs will have python already installed.
● To check if you have python installed on a Windows PC, search in the start
bar for Python or run the following on the Command Line ([Link]):
C:\Users\Your Name>python –version
● If you find that you do not have Python installed on your computer, then
you can download it for free from the following website:
website: [Link]
Features and Benefits of Python
● Compatible with a variety of platforms including Windows, Mac, Linux,
Raspberry Pi, and others.
● Uses a simple syntax comparable to the English language that lets
developers use fewer lines than other programming languages.
● Operates on an interpreter system that allows code to be executed
immediately, fast-tracking prototyping.
● Can be handled in a procedural, object-orientated, or functional way.
Python Identifiers
Identifiers are the name given to variables, classes, methods, functions etc. For
example-
language = “Python”
Here, language is a variable (an identifier) which holds the value 'Python'.
We cannot use keywords as variable names as they are reserved names that
are built-in to Python. For example,
continue = 'Python
The above code is wrong because we have used continue as a variable name.
(CONTINUE IS KEYWORD)
Rules for Naming an Identifier:
● Identifiers cannot be a keyword.
● Identifiers are case-sensitive.
● It can have a sequence of letters and digits. However, it must begin with a
letter or _. The first letter of an identifier cannot be a digit.
● It's a convention to start an identifier with a letter rather _.
● Whitespaces are not allowed.
● We cannot use special symbols like !, @, #, $, and so on.
Some Valid and Invalid Identifiers in Python
Valid Identifiers InvalidIdentifiers
_score @core
Return_value return
highest_score highest score
name1 1name
convert_to_string convert to_string
Important Points-
● 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 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.
PYTHON FEATURES
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. There is no use of the
semicolon or curly-bracket, the indentation defines the code block. It is the
recommended programming language for beginners.
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.
5) Free and Open Source
Python is freely available for everyone. It is freely available on its official website
[Link]. It has a large community across the world that is dedicatedly
working towards make new python modules and functions. Anyone can contribute
to the Python community. The open-source means, "Anyone can download its
source code without paying any penny."
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) Dynamic Memory Allocation
In Python, we don't need to specify the data-type of the variable. When we assign
some value to the variable, it automatically allocates the memory to the variable at
run time. Suppose we are assigned integer value 15 to x, then we don't need to
write int x = 15. Just write x = 15.
8) 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.
9) 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.
PYTHON APPLICATIONS
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,
beautiful Soup, Feedparser, etc. One of Python web-framework named Django is
used on Instagram.
2) Desktop GUI Applications
The GUI stands for the Graphical User Interface, which provides a smooth
interaction to any application. Python provides a Tk GUI library to develop a user
interface. Some popular GUI libraries are given below.
Tkinter or Tk
wxWidgetM
Kivy (used for writing multitouch applications )
PyQt or Pyside
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.
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.
5) Scientific and Numeric
This is the era of Artificial intelligence where the machine can perform the task the
same as the human. Python language is the most suitable language for Artificial
intelligence or machine learning. It consists of many scientific and mathematical
libraries, which makes easy to solve complex calculations.
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.
7) Audio or Video-based Applications
Python is flexible to perform multiple tasks and can be used to create multimedia
applications. Some multimedia applications which are made by using Python are
TimPlayer, cplay, etc.
PYTHON CHARACTER SET
Character set is a set of valid characters that a language can recognize. A character
represents any letter, digit or any other symbol. Python supports Unicode encoding
standard. That means, Python has the following character set :
Letters : A-Z, a-z
Digits : 0-9
Special symbols : space +-/*\() [] {} // = != == <, > . '"'"",;:%!& # <= >=
@_(underscore)
Whitespaces
Blank space, tabs (→), carriage return (), newline,
formfeed.
Other characters Python can process all ASCII and Unicode
characters as part of data or literals
IDENTIFIERS
IDENTIFIERS ARE FUNDAMENTAL BUILDING BLOCKS OF A PROGRAM AND ARE USED
AS THE GENERAL TERMINOLOGY FOR THE NAMES GIVEN TO DIFFERENT PARTS OF
THE PROGRAM VIZ. VARIABLES, OBJECTS, CLASSES, FUNCTIONS, LISTS,
DICTIONARIES ETC. IDENTIFIER FORMING.
RULES OF PYTHON ARE BEING SPECIFIED BELOW:
● An identifier is an arbitrarily long sequence of letters and digits.
● The first character must be a letter; the underscore (_) counts as a letter.
● Upper and lower-case letters are different.
● All characters are significant.
● The digits 0 through 9 can be part of the identifier except for the first
character.
● Identifiers are unlimited in length. Case is significant i.e., Python is case
sensitive as it treats upper and lower-case characters differently.
● An identifier cannot contain any special character except for underscore (_).
● An identifier must not be a keyword of python.
KEYWORDS IN PYTHON
Keywords are the reserved words in Python. We cannot use a keyword as
a variable name, function name or any other identifier. Here's a list of all
keywords in Python Programming:
False,await ,else,import,pass,None , break,true
,class,finally,is,return,and,continue,for,lambda,try,as,def,from,nonlocal,while
,assert,del,global,not,with,async,elif,if,or.
STATEMENTS IN PYTHON
Statement is an instruction that a Python interpreter can execute. So, in simple
words, we can say anything written in Python is a statement.
For example, a = 10 is an assignment statement. where a is a variable name and 10
is its value. There are mainly four types of statements in Python
● Print statements,
● Assignment statements,
● Conditional statements,
● Looping statements,
● Return statements,
MULTI-LINE STATEMENTS
Python statement ends with the token NEWLINE character. But we can
extend the statement over multiple lines using line continuation character (\).
This is known as an explicit continuation.
Example
>>addition = 10 + 20 + \
30 + 40 + \
50 + 60 + 70
>>print(addition)
# Output: 280
Implicit continuation:
We can use parentheses () to write a multi-line statement. We can add a line
continuation statement inside it. Whatever we add inside a parentheses () will
treat as a single statement even it is placed on multiple lines.
Example:
addition = (10 + 20 + 30 + 40 +
50 + 60 + 70)
print(addition)
# Output: 280
PYTHON VARIABLES
Variables are identifiers of a physical memory location, which is used to hold
values temporarily during program execution. Python interpreter allocates
memory based on the values(letter or a number) data type of variable,
different data types like integers, decimals, characters, etc. can be stored in
these variables.
Python Variable Declaration
In Python, like many other programming languages, there is no need to define
variables in advance. As soon as a value is assigned to a variable, it is
automatically declared. This is why Python is called a dynamically typed
language.
The syntax for creating variables in Python is given below:
<variable-name> = <value>
ASSIGNING VALUE TO VARIABLES
Python interpreter can determine what type of data is stored, so before
assigning a value, variables do not need to be declared. Usually, in all
programming languages, equal sign = is used to assign values to a variable. It
assigns the values of the right side operand to the left side operand.
The left side operand of = operator is the name of a variable, and the right
side operand is value.
name = "Packing box" # A string
height = 10 # An integer assignment
width = 20.5 # A floating point
print (name)
print (height)
print (width)
Example:
OUTPUT
Packing box
10
20.5
Common Rules for Naming Variables in Python
Python has some variable related rules that must be
followed:
● Variable names are case-sensitive.
● Variable names must begin with a letter or underscore.
● A variable name can only contain alphanumeric
● characters and underscore, such as (a-z, A-Z, 0-9, and_ ).
● A variable name can not contents space.
● Reserved words cannot be used as a variable name.
Example
This will create two variables:
a=4
A = "Sally"
#A will not overwrite a
DATA TYPES
Python offers following built-in core data types :
[Link] - immutable(cannot be changed/modified)
[Link] - immutable(cannot be changed/modified)
[Link] - mutable(changed/modified)
[Link] - immutable(cannot be changed/modified)
[Link] - mutable(changed/modified)
1. NUMBERS
Numeric values are stored in numbers. The whole number, float, and complex
qualities have a place with a Python Numbers data type. Python offers the
type() function to determine a variable's data type. The instance () capability
is utilized to check whether an item has a place with a specific class.
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'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
PYTHON SUPPORTS THREE KINDS OF
NUMERICAL DATA.
Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, -
150, and so on. An integer can be any length you want in Python. Its
worth has a place with int.
Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be
accurate to within 15 decimal places.
Complex: An intricate number is in the form A+Bi where i is the imaginary
number, equal to the sqare root of -1 i.e., √-1, that is 12 The complex numbers
like 2.14j, 2.0 + 2.3j, etc.
SEQUENCE TYPE OR STRING TYPE
● The sequence of characters in the quotation marks can be used to
describe the string.
● A string can be defined in Python using single, double, or triple quotes.
● String dealing with Python is a direct undertaking since Python gives
worked-in capabilities and administrators to perform tasks in the
string.
● When dealing with strings, the operation "hello"+" python" returns
"hello python," and the operator + is used to combine two strings. Because the
operation "Python" *2 returns "Python," the operator * is
referred to as a repetition operator.
Example
str1 = 'hello javatpoint' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2
LIST
● Lists in Python are like arrays in C, but lists can contain data of
different types.
● The things put away in the rundown are isolated with a comma (,) and
encased inside square sections [].
● To gain access to the list's data, we can use slice [:] operators. Like
how they worked with strings, the list is handled by the concatenation
operator (+) and the repetition operator (*).
Example:
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))
#Printing the list1
print (list1)
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
# List Concatenation using + operator
print (list1 + list1)
# List repetation using * operator
print (list1 * 3)
Output:
<Class “List”>
[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
● In many ways, a tuple is like a list.
● Tuples, like lists, also contain a collection of items from various data
types.
● A parenthetical space () separates the tuple's components from one
another. Because we cannot alter the size or value of the items in a tuple,
it is a read-only data structure.
Example
up = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))
#Printing the tuple
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
# Tuple concatenation using + operator
print (tup + tup)
# Tuple repatation using * operator
print (tup * 3)
# Adding value to tup. It will throw an error.
t[2] = "hi"
Out put
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2,
'hi', 'Python', 2)
Traceback (most recent call last):
File "[Link]", line 14, in
<module> t[2] = "hi";
TypeError: 'tuple' object does not support item assignment.
DICTIONARY
A dictionary is a key-value pair set arranged in any order. It stores a
specific value for each key, like an associative array or a hash table.
Value is any Python object, while the key can hold any primitive data
type.
The comma (,) and the curly braces are used to separate the items in
the dictionary.
Example
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
# Printing dictionary
print (d)
# Accesing value using keys
print("1st name is "+d[1])
print("2nd name is "+ d[4])
print ([Link]())
print ([Link]())
Out Put
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'])
YTHON - OPERATORS
Python operators are the constructs which can manipulate
the value of operands. These are symbols used for the
purpose of logical, arithmetic and various other operations.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are
called operands and + is called operator. In this tutorial,
we will study different types of Python operators.
Types of Python Operators
Python language supports the following types of operators.
● Arithmetic Operators
● Comparison (Relational) Operators
● Assignment Operators
● Logical Operators
● Bitwise Operators
● Membership Operators
PYTHON ARITHMETIC OPERATORS
Python arithmetic operators are used to perform mathematical operations on
numerical values. These operations are Addition, Subtraction, Multiplication,
Division, Modulus, Exponents and Floor Division.
PYTHON COMPARISON OPERATORS
Python comparison operators compare the values on either sides of them and
decide the relation among them. They are also called relational operators.
These operators are equal, not equal, greater than, less than, greater than or
equal to and less than or equal to.
PYTHON ASSIGNMENT OPERATORS
Python assignment operators are used to assign values to variables. These
operators include simple assignment operator, addition assign, subtraction
assign, multiplication assign, division and assign operators etc.
PYTHON BITWISE OPERATORS
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. Following table lists out the bitwise
operators supported by Python language with an example each in those, we
use the above two variables.
PYTHON LOGICAL OPERATORS
The assessment of expressions to make decisions typically makes use of the
logical operators. The following logical operators are supported by Python.
PYTHON MEMBERSHIP OPERATORS
Python’s membership operators test for membership in a sequence, such as
strings, lists, or tuples. There are two membership operators as explained
below:
PYTHON COMMENTS
Comments can be used to explain Python code. Comments can be used to
make the code more readable. Comments can be used to prevent execution
when testing code.
Types of Comments in Python
● Single-Line Comments
● Multi-Line Comments
Single-Line Comments
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.
example
# This code is to show an example of a single
line comment
print( 'This statement does not have a hashtag before it')
Multi-Line Comments
Python does not provide the facility for multi-line comments. However, there
are indeed many ways to create multi-line comments. With Multiple Hashtags
(#)
example
# it is a
# comment
# extending to multiple lines
Using String Literals
Because Python overlooks string expressions that aren't allocated to a
variable, we can utilize them as comments.
example
‘it is a comment extending to multiple lines’
add a multiline string (triple quotes) in your code, and place your comment
inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
TYPE CONVERSION IN PYTHON
Type conversion is the transformation of a Py type of data into another type of
data. In Python, there are two kinds of type conversion:
Explicit Type Conversion-The programmer must perform this task manually.
Implicit Type Conversion-By the Python program automatically.
1. Python Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to
required data type.
We use the built-in functions like int(), float(), str(), etc toperform explicit type
conversion. This type of conversion is also called typecasting because
the user casts (changes) the data type of the objects.
Example explicit conversion
num_string = '12'
num_integer = 23
print("Data type of num_string before Type
Casting:",type(num_string))
# explicit type conversion
num_string = int(num_string)
print("Data type of num_string after Type
Casting:",type(num_string))
num_sum = num_integer + num_string
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Output
Data type of num_string before Type Casting: <class 'str’>
Data type of num_string after Type Casting: <class 'int’>
Sum: 35
Data type of num_sum: <class 'int'>
PYTHON IMPLICIT TYPE CONVERSION
In certain situations, Python automatically converts one data type to
another. This is known as implicit type conversion.
Example 1: Converting integer to float
Let's see an example where Python promotes the conversion of the
lower data type (integer) to the higher data type (float) to avoid data
loss.
Out put
integer_number = 123
float_number = 1.23
new_number = integer_number + float_number # display new
value and resulting data type
print("Value:",new_number)
print("Data Type:",type(new_number))
Value: 124.23
Data Type: <class 'float'>