Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Unit 1 and Unit 2 PPT

The document is an introduction to programming with Python, covering fundamental concepts such as code, syntax, and output. It highlights Python's features, including its ease of use, expressiveness, and high-level nature, while also discussing its limitations like speed and mobile computing. Additionally, it explains data types, variable declaration, type conversions, and various operators in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Unit 1 and Unit 2 PPT

The document is an introduction to programming with Python, covering fundamental concepts such as code, syntax, and output. It highlights Python's features, including its ease of use, expressiveness, and high-level nature, while also discussing its limitations like speed and mobile computing. Additionally, it explains data types, variable declaration, type conversions, and various operators in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 63

Introduction to Programming

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.

 console: The text box onto which output is printed.


 Some source code editors pop up the console as an external window,
and others contain their own console window.

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

 Python is instead directly interpreted into machine instructions.

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

don’t need to remember the system architecture. Nor do we need


to manage the memory. This makes it more programmer-
friendly and is one of the key python features. 7
Features of python
 6. Interpreted
 If you’re familiar with any languages like C++ or Java, you must first
compile it, and then run it. But in Python, there is no need to compile
it. Internally, its source code is converted into an immediate form
called bytecode. So, all you need to do is to run your Python code
without worrying about linking to libraries, and a few other things.
 7. Object-Oriented
 A programming language that can model the real world is said to be
object-oriented. It focuses on objects and combines data and
functions. Contrarily, a procedure-oriented language revolves around
functions, which are code that can be reused. Python supports
both procedure-oriented and object-oriented programming which
is one of the key python features. It also supports multiple
inheritances, unlike Java. A class is a blueprint for such an object. It is
an abstract data type and holds no values.

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.

Weak in Mobile Computing


Python has made its presence on many desktop and server
platforms, but it is seen as a weak language for mobile computing.
This is the reason very few mobile applications are built in it like
Carbonnelle.

Gets Slow in Speed


Python executes with the help of an interpreter instead of the
compiler, which causes it to slow down because compilation and
execution help it to work normally. On the other hand, it can be seen
that it is fast for many web applications too.
11
Limitations of Python
Underdeveloped Database Access Layers
As compared to the popular technologies like JDBC and ODBC, the
Python’s database access layer is found to be bit underdeveloped
and primitive. However, it cannot be applied in the enterprises that
need smooth interaction of complex legacy data.

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:

 Lowercase English letters: a through z


 Uppercase English letters: A through Z
 Some punctuation and symbols: "$" and "!", to name a couple
 Whitespace characters: an actual space (" "), as well as a newline,
carriage return, horizontal tab, vertical tab, and a few others
 Some non-printable characters: characters such as backspace, "\b",
that can’t be printed literally in the way that the letter A can

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"

#Illegal variable names:


2myvar = "John"
my-var = "John“, my var = "John" 19
s
Declaring Variables
 Python does not bound us to declare variable before using in the
application. It allows us to create variable at required time.

 We don't need to declare explicitly variable in Python.

 When we assign any value to the variable that variable is declared


automatically

 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.

 Python is a dynamically typed language hence we need not define


the type of the variable while declaring it.

 The interpreter implicitly binds the value with its 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.

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.

 Implicit Type Conversion


 Explicit 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 = num_int + num_flo

 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.

 This type of conversion is also called typecasting because the user


casts (changes) the data type of the objects.

 <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

python types of operators are-


Uniary operators
Binary operators
Based on functionality operators are-
i. Arithmetic operators.
ii. Assignment operators.
iii. Bitwise operators.
iv. Comparison operators.
v. Identity operators.
vi. Logical operators.
vii. Membership operators.
27
Arithmetic operators

Operator Operation Example

+ 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

< Less Than 3 < 5 gives us True

Greater Than or 3 >= 5 give us


>=
Equal To False

Less Than or Equal 3 <= 5 gives us


<=
To True
30
Logical Operators
Operator Example Meaning

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)

<< Bitwise left shift x 0010 1000)

32
Identity Operators

Operator Meaning Example

True if the operands


is are identical (refer x is True
to the same object)

True if the operands


are not identical (do
is not x is not True
not refer to the
same object)

33
Membership Operators

Operator Meaning Example

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

 precedence: Order in which operations are computed.


 * / % ** have a higher precedence than + -
1 + 3 * 4 is 13
 Parentheses can be used to force a certain order of evaluation.
(1 + 3) * 4 is 16

35
Python Operators Precedence
Operator Description
** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names for


the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction


>> << Right and left bitwise shift

& Bitwise 'AND'


^| Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators


<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators

is, is not Identity operators


in, not in Membership operators
not, or, and Logical operators 36
Associativity
 whenever two or more operators have the same precedence, then
associativity defines the order of operations.
 The associativity is the order in which Python evaluates an
expression containing multiple operators of the same precedence.
 Almost all operators except the exponent (**) support the left-to-
right associativity.
 Example 1:
 print(4 * 7 % 3)
 o/p ((4*7)%3)
 (28%3)
 1
Example 2: Right to left
 print(2 ** 3 ** 2)
 print(2 ** (3 ** 2))
 print(2** 9)
 512
37
COMMENTS
 Single-line comments begins with a hash(#) symbol.
A Multi line comment is useful when we need to comment on many

lines. In python, triple double quote(“ “ “) and single quote(‘ ‘ ‘)are


used for multi-line commenting.
 Python allows us to add comments in the code.

Comments are used by the programmer to explain the piece of code

to be understood by other programmer in a simple language. Every


programming language makes use of some character for
commenting. In python
 Comments do not affect the programming part and the Python

interpreter does not display any error message for comments.


For example : Commenting using hash mark (#)

>>> 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.

Steps involved in programming cycle


1. Identify the problem and start building the solution.
2. Test the code..
3. Editing the source code if any error.
4. The program is ready. We can update it from time to time.

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.

 Features of visual studio :


i. It supports Python coding in visual studio, debugging, and other
activities.
ii. It has both paid and free versions in the market with great
features.

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

 To use many of these commands, you must write the following at


the top of your Python program:
from math import *
46
Repetition (loops)
and Selection (if/else)

47
Control Statements

A control statement is a statement that determines the control flow of a set of


instructions, i.e., it decides the sequence in which the instructions in a program
are to be executed.

Types of Control Statements —


•Sequential Control: A Python program is executed sequentially from the first line
of the program to its last line.
•Selection Control: To execute only a selected set of statements.
•Iterative Control: To execute a set of statements repeatedly.
The for loop
 for loop: Repeats a set of statements over a group of values.
 Syntax:
for variable name in sequence:
statements

We indent the statements to be repeated with tabs or spaces.

Variable name gives a name to each value, so you can refer to it in the statements.

Sequence can be any list,tuple or range of integers, specified with the range()
function.

 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

 Exercise: Write a Python program that computes the factorial of an


integer.

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."

 Multiple conditions can be chained with elif ("else if"):


if condition:
statements
elif condition:
statements
else:
statements
55
Ternary Operator

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

 Logical expressions can be combined with logical operators:


Operator Example Result
and 9 != 6 and 2 < 3 True
or 2 == 3 or -1 < 5 True
not not 7 > 0 False

 Exercise: Write code to display and count the factors of a number.


58
The Pass Statement
Pass statement is used when a statement is required syntactically but no command
or code has to be executed. It specified a null operation or simply No Operation
(NOP) statement. Nothing happens when the pass statement is executed.
Difference between comment and pass statements In Python programming, pass is a
null statement. The difference between a comment and pass statement is that while
the interpreter ignores a comment entirely, pass is not ignored. Comment is not
executed but pass statement is executed but nothing happens.

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

You might also like