Python Unit 1 and Unit 2 PPT
Python Unit 1 and Unit 2 PPT
with Python
Ajay Kumar
Assistant Professor, Information Technology
MIET, Meerut
1
Programming basics
code or source code: The sequence of instructions in a program.
syntax: The set of legal structures and commands that can be
used in a particular programming language.
output: The messages printed to the user by a program.
2
Compiling and interpreting
Many languages require you to compile (translate) your program
into a form that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class
interpret
source code output
Hello.py
3
Brief History of Python
Introduction to python
5
Features of Python
1. Easy
When we say the word ‘easy’, we mean it in different contexts.
a. Easy to Code
As we have seen in earlier lessons, Python is very easy to code.
Compared to other popular languages like Java and C++, it is easier to
code in Python. Anyone can learn Python syntax in just a few hours.
Though sure, mastering Python requires learning about all its advanced
concepts and packages and modules. That takes time. Thus, it is
programmer-friendly.
b. Easy to Read
Being a high-level language, Python code is quite like English. Looking
at it, you can tell what the code is supposed to do. Also, since it is
dynamically-typed, it mandates indentation. This aids readability.
6
Features of python
2. Expressive
First, let’s learn about expressiveness. Suppose we have two
languages A and B, and all programs that can be made in A can
be made in B using local transformations. However, there are
some programs that can be made in B, but not in A, using local
transformations. Then, B is said to be more expressive than A.
Python provides us with a myriad of constructs that help us focus
on the solution rather than on the syntax. This is one of the
outstanding python features that tell you why you should learn
Python.
3. Free and Open-Source
Firstly, Python is freely available. You can download it from the
Python Website.
4. High-Level
it is a high-level language. This means that as programmers, we
8
Features of python
8. Extensible
If needed, you can write some of your Python code in other languages
like C++. This makes Python an extensible language, meaning that it
can be extended to other languages.
9. Embeddable
We just saw that we can put code in other languages in our Python
source code. However, it is also possible to put our Python code in a
source code in a different language like C++. This allows us to
integrate scripting capabilities into our program of the other language.
10. Large Standard Library
Python downloads with a large library that you can use so you don’t
have to write your own code for every single thing. There are libraries
for regular expressions, documentation-generation, unit-testing, web
browsers, threading, databases, CGI, email, image manipulation, and a
lot of other functionality.
9
Features of python
11. GUI Programming
A software is not user-friendly until its GUI is made. A user can easily
interact with the software with a GUI. Python offers various libraries for
making Graphical user interface for your applications. For this, you can
use Tkinter, wxPython or JPython. These toolkits allow you for easy and
fast development of GUI.
12. Dynamically Typed
Python is dynamically-typed. This means that the type for a value is
decided at runtime, not in advance. This is why we don’t need to
specify the type of data while declaring it.
10
Limitations of Python
Difficulty in Using Other Languages
The Python lovers become so accustomed to its features and its
extensive libraries, so they face problem in learning or working on
other programming languages.
12
Application of Python
13
Character Set
Python uses the traditional ASCII character set. The latest version
(3.8) also recognizes the Unicode character set. The ASCII character
set is a subset of the Unicode character set.
It encompasses the following:
14
Data Types
Python support deals with following types of Data Types
15
Numeric Datatype
Numeric data can be broadly divided into integers and real
numbers (i.e., fractional numbers). Integers can be positive or
negative.
The real numbers or fractional numbers are called, floating point
numbers in programming languages. Such floating point numbers
contain a decimal and a fractional part.
For example :
>>> num1 = 2 # integer number
>>>num2 = 2.5 # real number (float)
>>>print(num1)
2 # Output
>>>print(num2)
2.5 # Output
16
Boolean Datatype
In a programming language, mostly data is stored in the form of
alphanumeric but sometimes we need to store the data in the form
of ‘Yes’ or ‘No’.
In terms of programming language, Yes is similar to True and No is
similar to False. This True and False data is known as Boolean data
and the data types which stores this Boolean data are known as
Boolean data types.
For example :
>>> a = True
>>> type (a)
<type ‘bool’>
17
Cont.
18
Identifier
Variables are containers for storing data values.
A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume). Rules for Python
variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different
variables)
There is no length limit for python identifiers. But not recommended to
use too lengthy identifiers
#Legal variable names:
myvar = "John"
my_Var2 = "John"
Multiple Assignment
Python allows us to assign a value to multiple variables in a single
statement which is also known as multiple assignment.
Assigning single value to multiple variables
x=y=z=50
Assigning multiple values to multiple variable
a,b,c=5,13,34
20
Cont.
Variables can hold values of different data types.
21
Cont.
A=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type ‘int’>
<type ‘str’>
<type ‘float’>
22
Keyword
Keyword will be not used for identifier.
23
Type Conversions
The process of converting the value of one data type
(integer, string, float, etc.) to another data type is called
type conversion. Python has two types of type conversion.
24
Implicit Type Conversion
In Implicit type conversion, Python automatically converts one data
type to another data type. This process doesn't need any user
involvement.
For Example
num_int = 123
num_flo = 1.23
Num_new=124.23
25
Explicit Type Conversion
Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an
object to required data type. We use the predefined functions like
int(), float(), str(), etc to perform explicit type conversion.
<required_datatype>(expression)
num_int = 123
num_str = "456“
num_str = int(num_str)
num_sum = num_int + num_str
26
OPERATORS
An operator is a symbol that represents an operation that may be
performed on one or more operands.
Operators are constructs used to modify the values of operands. In
+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2*3=6
/ Division 4/2=2
// Floor Division 10 // 3 = 3
% Modulo 5%2=1
** Power 4 ** 2 = 16
28
Operator
Operator Name
Name Example
Example
=
= Assignment
Assignment Operator
Operator a
a==7
7
+=
+= Addition
Addition Assignment
Assignment a
a +=
+= 1
1##a
a==a
a++1
1
Subtraction
Subtraction
-=
-= a
a -=
-= 3
3##a
a==a
a -- 3
3
Assignment
Assignment
Multiplication
Multiplication
*=
*= a
a *=
*= 4
4##a
a==a
a ** 4
4
Assignment
Assignment
/=
/= Division
Division Assignment
Assignment a
a /=
/= 3
3##a
a==a
a // 3
3
%=
%= Remainder
Remainder Assignment
Assignment a
a %=
%= 10
10 #
#aa=
=aa%
% 10
10
**=
**= Exponent
Exponent Assignment
Assignment a
a **=
**= 10
10 #
#aa=
=aa **
** 10
10
29
Comparison Operators
Operator Meaning Example
3 == 5 gives us
== Is Equal To
False
3 != 5 gives us
!= Not Equal To
True
3 > 5 gives us
> Greater Than
False
Logical AND:
True only if both
and a and b
the operands are
True
Logical OR:
True if at least one
or a or b
of the operands is
True
Logical NOT:
True if the operand
not not a
is False and vice-
versa.
31
Bitwise Operators
Operator Meaning Example
x & y = 0 (0000
& Bitwise AND
0000)
x | y = 14 (0000
| Bitwise OR
1110)
~x = -11 (1111
~ Bitwise NOT
0101)
x ^ y = 14 (0000
^ Bitwise XOR
1110)
x >> 2 = 2 (0000
>> Bitwise right shift
0010)
32
Identity Operators
33
Membership Operators
True if
value/variable is
in 5 in x
found in the
sequence
True if
value/variable is
not in 5 not in x
not found in the
sequence
34
Expressions
expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
13
Arithmetic operators we will use:
+ - * / addition, subtraction/negation, multiplication,
division
% modulus, a.k.a. remainder
** exponentiation
35
Python Operators Precedence
Operator Description
** Exponentiation (raise to the power)
>>> 8 + 9 # addition
17 # Output
38
PROGRAMMING CYCLE FOR PYTHON
The Python programming life cycle is comparatively shorter and
easier than the life cycles of traditional programming languages.
Python is an interpreted language i.e. it executes the program line
by line and stops at the first place it finds an error. Hence, it is easy
to debug code. There are no compile or link steps.
39
PROGRAMMING CYCLE
40
IDE
IDE stands for Integrated Development Environment is software
that facilitates the programmers to develop applications. It provides
a bundle of functionalities like writing the code, highlighting the
errors, debugging, testing the code, etc.
IDEs integrate many tools that are designed for SDLC.
IDEs were introduced to diminish the coding and typing errors.
Some of the Python IDEs are :
1. PyCharm
2. Spyder
3. PyDev
4. IDLE
5. Visual studio
41
PyCharm
PyCharm assists the developers to be more productive and
provides smart suggestions. It saves time by taking care of routine
tasks, hence increases productivity.
Features of PyCharm :
i. It has smart code navigation, good code editor, a function for
quick refactoring.
ii. The integrated activities with PyCharm are profiling, testing,
debugging, remote development, and deployments.
iii. PyCharm supports Python web development frameworks Angular
JS, JavaScript, CSS, HTML and live editing functions.
42
Spyder
Spyder is widely used for data science works. It is mostly used to
create a secure and scientific environment for Python.
Spyder Python uses PyQt (Python plug-in) which a developer can
add as an extension.
Features of Spyder :
i. It has good syntax highlighting and auto code completion
features.
ii. Spyder Python explores and edits variables directly from GUI.
iii. It performs very well in multi-language editor.
43
IDLE
IDLE is a basic IDE mainly used by beginner level developer.
i. IDLE Python is a cross-platform IDE, hence it increases the
flexibility for users.
ii. It is developed only in Python in collaboration with Tkinter
GUI toolkit.
iii. The feature of multi-window text editor in IDLE has some
great functions like smart indentation, call tips, Python colorizing, and
undo option.
iv. It also comes with a strong debugger along with continuous
breakpoints, local spaces, and global view.
v. It supports browsers, editable configurations, and dialog boxes.
44
Visual Studio
It enables development for various platforms and has its own
marketplace for extensions.
45
Math commands
Python has useful commands for performing calculations.
Command name Description Constant Description
abs(value) absolute value e 2.7182818...
ceil(value) rounds up pi 3.1415926...
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
47
Control Statements
Example:
for x in range(1, 6):
print(x, "squared is", x * x)
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
49
Conti.
Str=“python”
For i in Str:
print(i)
O/P:
p
y
t
h
o
n
50
range
The range function specifies a range of integers:
range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
It can also accept a third value specifying the change between values.
range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step
Example:
for x in range(5, 0, -1):
print x
print "Blastoff!"
Output:
5
4
3
2
1
Blastoff!
51
Cumulative loops
Some loops incrementally compute a value that is initialized outside
the loop. This is sometimes called a cumulative sum.
sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print "sum of first 10 squares is", sum
Output:
sum of first 10 squares is 385
52
For Loop and Range() Function
The range() function is a built-in function in Python that is used to iterate over a
sequence of numbers. The syntax of range() is range(beg, end, [step])
The range() produces a sequence of numbers starting with beg (inclusive) and ending
with one less than the number end. The step argument is option (that is why it is
placed in brackets). By default, every number in the range is incremented by 1 but we
can specify a different increment using step. It can be both negative and positive,
but not zero.
Examples:
if
if statement: Executes a group of statements only if a certain
condition is true. Otherwise, the statements are skipped.
Syntax:
if condition:
statements
Example:
gpa = 3.4
if(gpa > 2.0):
print("Your application is accepted.“)
54
if/else
if/else statement: Executes one block of statements if a certain
condition is True, and a second block of statements if it is False.
Syntax:
if condition:
statements
else:
statements
Example:
gpa = 1.4
if gpa > 2.0:
print "Welcome to Mars University!"
else:
print "Your application is denied."
56
while
while loop: Executes a group of statements as long as a condition is True.
good for indefinite loops (repeat an unknown number of times)
Syntax:
while condition:
statements
Example:
number = 1
while number < 200:
print number,
number = number * 2
Output:
1 2 4 8 16 32 64 128
57
Logic
Many logical expressions use relational operators:
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
Example:
The Continue Statement
Like the break statement, the continue statement can only appear in the body of a
loop. When the compiler encounters a continue statement then the rest of the
statements in the loop are skipped and the control is unconditionally transferred to
the loop-continuation portion of the nearest enclosing loop.
Example:
60
The Break Statement
The break statement is used to terminate the execution of the nearest enclosing
loop in which it appears. The break statement is widely used with for loop and while
loop. When compiler encounters a break statement, the control passes to the
statement that follows the loop in which the break statement appears.
Example:
Condition-controlled and Counter-
controlled Loops
Thank you
63