You are on page 1of 51

1

PYTHON
PROGRAMMING
WORKSHOP
ORGANIZED BY,
DEPT. OF ETC AND MECH OF
SHRI TULJA BHAVANI
COLLEGE OF ENGINEERING,
TULJAPUR

08/03/2023
08/03/2023

Python Overview
2

 Python is a high-level, interpreted, interactive and


object oriented-scripting language.

 Python was designed to be highly readable which


uses English keywords frequently where as other
languages use punctuation and it has fewer
syntactical constructions than other languages.
08/03/2023

 Python is Interpreted: This means that it is processed at runtime


by the interpreter and you do not need to compile your program
before executing it. This is similar to PERL and PHP.
 Python is Interactive: This means that you can actually sit at a
Python prompt and interact with the interpreter directly to write
your programs.
 Python is Object-Oriented: This means that Python supports
Object-Oriented style or technique of programming that
encapsulates code within objects.
 Python is Beginner's Language: Python is a great language for the
beginner programmers and supports the development of a wide
range of applications, from simple text processing to WWW
browsers to games.
08/03/2023

Compiling and interpreting


4

 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
 Python is instead directly interpreted into machine instructions.
source code output
Hello.py
08/03/2023

History of Python:
5

 Python was developed by Guido van Rossum in the late


eighties and early nineties at the National Research Institute
for Mathematics and Computer Science in the Netherlands.
 Python is derived from many other languages, including
ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix
shell and other scripting languages.
 Python is copyrighted, Like Perl, Python source code is now
available under the GNU General Public License (GPL).
 Python is now maintained by a core development team at
the institute, although Guido van Rossum still holds a vital
role in directing it's progress.
08/03/2023

Python Features
6

 Easy-to-learn: Python has relatively few keywords, simple


structure, and a clearly defined syntax.
 Easy-to-read: Python code is much more clearly defined and
visible to the eyes.
 Easy-to-maintain: Python's success is that its source code is
fairly easy-to-maintain.
 A broad standard library: One of Python's greatest strengths
is the bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
 Interactive Mode: Support for an interactive mode in which
you can enter results from a terminal right to the language,
allowing interactive testing and debugging of snippets of
code.
08/03/2023

Python Features (cont’d)


7

 Portable: Python can run on a wide variety of hardware platforms and


has the same interface on all platforms.
 Extendable: You can add low-level modules to the Python interpreter.
These modules enable programmers to add to or customize their tools
to be more efficient.
 Databases: Python provides interfaces to all major commercial
databases.
 GUI Programming: Python supports GUI applications that can be
created and ported to many system calls, libraries, and windows
systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
 Scalable: Python provides a better structure and support for large
programs than shell scripting.
08/03/2023

Python Environment
8

 Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX etc.)


 Win 9x/NT/2000
 Macintosh (PPC, 68K)
 OS/2
 DOS (multiple versions)
 PalmOS
 Nokia mobile phones
 Windows CE
 Acorn/RISC OS
 BeOS
 Amiga
 VMS/OpenVMS
 QNX
 VxWorks
 Psion
 Python has also been ported to the Java and .NET virtual machines.
08/03/2023

Python - Basic Syntax


9

 Interactive Mode Programming:


>>> print "Hello, Python!";
Hello, Python!
>>> 3+4*5;
23
08/03/2023

10

 Script Mode Programming :


Invoking the interpreter with a script parameter begins execution of the
script and continues until the script is finished. When the script is finished,
the interpreter is no longer active.

For example, put the following in one test.py, and run,


print "Hello, Python!";
print "I love COMP3050!";

The output will be:


Hello, Python!
I love COMP3050!
08/03/2023

Python Identifiers:
11

 A Python identifier is a name used to identify a


variable, function, class, module, or other object. An
identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters,
underscores, and digits (0 to 9).
 Python does not allow punctuation characters such as
@, $, and % within identifiers. Python is a case
sensitive programming language. Thus Manpower
and manpower are two different identifiers in
Python.
08/03/2023

Python Identifiers (cont’d)


12

 Here are following identifier naming convention for Python:


 Class names start with an uppercase letter and all other
identifiers with a lowercase letter.
 Starting an identifier with a single leading underscore
indicates by convention that the identifier is meant to be
private.
 Starting an identifier with two leading underscores
indicates a strongly private identifier.
 If the identifier also ends with two trailing underscores, the
identifier is a language-defined special name.
08/03/2023

Reserved Words:
13

Keywords contain lowercase letters only.


and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
08/03/2023

Lines and Indentation:


14

 One of the first caveats programmers encounter when learning Python is


the fact that there are no braces to indicate blocks of code for class and
function definitions or flow control. Blocks of code are denoted by line
indentation, which is rigidly enforced.
 The number of spaces in the indentation is variable, but all statements
within the block must be indented the same amount. Both blocks in this
example are fine:
if True:
print "Answer“;
print "True" ;
else:
print "Answer“;
print "False"
08/03/2023

Multi-Line Statements:
15

 Statements in Python typically end with a new line. Python does, however,
allow the use of the line continuation character (\) to denote that the line
should continue. For example:
total = item_one + \
item_two + \
item_three
 Statements contained within the [], {}, or () brackets do not need to use the
line continuation character. For example:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
08/03/2023

Quotation in Python:
16

 Python accepts single ('), double (") and triple (''' or """)
quotes to denote string literals, as long as the same type of
quote starts and ends the string.
 The triple quotes can be used to span the string across
multiple lines. For example, all the following are legal:
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and
sentences."""
08/03/2023

Comments in Python:
17

 A hash sign (#) that is not inside a string literal


begins a comment. All characters after the #
and up to the physical line end are part of the
comment, and the Python interpreter ignores
them.
08/03/2023

Using Blank Lines:

18

 A line containing only whitespace, possibly


with a comment, is known as a blank line, and
Python totally ignores it.
 In an interactive interpreter session, you must

enter an empty physical line to terminate a


multiline statement.
08/03/2023

Multiple Statements on a Single Line:


19

 The semicolon ( ; ) allows multiple statements on the


single line given that neither statement starts a new
code block. Here is a sample snip using the
semicolon:
import sys; x = 'foo';
sys.stdout.write(x + '\n')
08/03/2023

Multiple Statement Groups as Suites:


20

 Groups of individual statements making up a single code block are called


suites in Python.
Compound or complex statements, such as if, while, def, and class, are
those which require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a
colon ( : ) and are followed by one or more lines which make up the suite.
if expression :
suite
elif expression :
suite
else :
suite
08/03/2023

Python - Variable Types


21

 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.
08/03/2023

Assigning Values to Variables:


22

 Python variables do not have to be explicitly declared to


reserve memory space. The declaration happens automatically
when you assign a value to a variable. The equal sign (=) is
used to assign values to variables.
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
08/03/2023

Multiple Assignment:
23

 You can also assign a single value to several


variables simultaneously. For example:
a = b = c = 1
a, b, c = 1, 2, "john"
08/03/2023

Standard Data Types:


24

Python has five standard data types:


 Numeric

 Dictionary

 Boolean

 Set

 Sequence type
08/03/2023

Python Numbers:
25

 Number data types store numeric values. They are immutable data types,
which means that changing the value of a number data type results in a
newly allocated object.
 Number objects are created when you assign a value to them. For example:
var1 = 1
var2 = 10
Python supports four different numerical types:
 int (signed integers)
 long (long integers [can also be represented in octal and hexadecimal])
 float (floating point real values)
 complex (complex numbers)
08/03/2023

Number Examples:
26

int long float complex


10 51924361L 0 3.14j
100 -0x19323L 15.2 45.j
-786 0122L -21.9 9.322e-36j
80 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-490 535633629843L -90 -.6545+0J
-0x260 -052318172735L -3.25E+101 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
08/03/2023

Python Strings:
27

 Strings in Python are identified as a contiguous set of


characters in between quotation marks.
 Python allows for either pairs of single or double
quotes. Subsets of strings can be taken using the slice
operator ( [ ] and [ : ] ) with indexes starting at 0 in
the beginning of the string and working their way
from -1 at the end.
 The plus ( + ) sign is the string concatenation
operator, and the asterisk ( * ) is the repetition
operator.
08/03/2023

Example:
28

str = 'Hello World!'


print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 6th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string

Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
08/03/2023

Python Lists:
29
 Lists are the most versatile of Python's compound data types. A list
contains items separated by commas and enclosed within square brackets
([]).
 To some extent, lists are similar to arrays in C. One difference between
them is that all the items belonging to a list can be of different data type.
 The values stored in a list can be accessed using the slice operator ( [ ] and
[ : ] ) with indexes starting at 0 in the beginning of the list and working
their way to end-1.
 The plus ( + ) sign is the list concatenation operator, and the asterisk ( * )
is the repetition operator.
08/03/2023

30

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists

Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
08/03/2023

Python Tuples:
31

 A tuple is another sequence data type that is similar


to the list. A tuple consists of a number of values
separated by commas. Unlike lists, however, tuples
are enclosed within parentheses.
 The main differences between lists and tuples are:
Lists are enclosed in brackets ( [ ] ), and their
elements and size can be changed, while tuples are
enclosed in parentheses ( ( ) ) and cannot be updated.
Tuples can be thought of as read-only lists.
08/03/2023

32

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')

print tuple # Prints complete list


print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists

OUTPUT:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
08/03/2023

Python Dictionary:
33

 Python 's dictionaries are hash table type. They work


like associative arrays or hashes found in Perl and
consist of key-value pairs.
 Keys can be almost any Python type, but are usually
numbers or strings. Values, on the other hand, can be
any arbitrary Python object.
 Dictionaries are enclosed by curly braces ( { } ) and
values can be assigned and accessed using square
braces ( [] ).
08/03/2023

34

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two“
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values

OUTPUT:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
08/03/2023

Data Type Conversion:


35 Function Description
int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
complex(real [,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
08/03/2023

Python Operators
36

 Arithmetic operators
 Comparison operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
08/03/2023

Arithmetic Operators
37

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30

- (Subtraction) It is used to subtract the second operand from the first operand. If the first
operand is less than the second operand, the value results negative. For
example, if a = 20, b = 10 => a - b = 10

/ (divide) It returns the quotient after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b =
(Multiplication) 10 => a * b = 200
% (reminder) It returns the reminder after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a%b = 0
** (Exponent) It is an exponent operator represented as it calculates the first operand power
to the second operand.
//(Floor It gives the floor value of the quotient produced by dividing the two
division) operands.
08/03/2023

Comparison operator
38

Operator Description

== If the value of two operands is equal, then the condition


becomes true.
!= If the value of two operands is not equal, then the condition
becomes true.
<= If the first operand is less than or equal to the second
operand, then the condition becomes true.
>= If the first operand is greater than or equal to the second
operand, then the condition becomes true.
> If the first operand is greater than the second operand, then
the condition becomes true.
< If the first operand is less than the second operand, then the
condition becomes true.
08/03/2023

Assignment Operators
39

Operator Description

= It assigns the value of the right expression to the left operand.


+= It increases the value of the left operand by the value of the right operand and assigns the
modified value back to left operand. For example, if a = 10, b = 20 => a+ = b will be equal to a =
a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assigns the
modified value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to a =
a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and assigns the
modified value back to then the left operand. For example, if a = 10, b = 20 => a* = b will be
equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assigns the reminder
back to the left operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and
therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.
08/03/2023

Bitwise Operators
40
Operator Description

&(binary If both the bits at the same place in two operands are 1,
and) then 1 is copied to the result. Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero;
otherwise, the resulting bit will be 1.
^(binary The resulting bit will be 1 if both the bits are different;
xor) otherwise, the resulting bit will be 0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if
the bit is 0, the resulting bit will be 1 and vice versa.
<<(left The left operand value is moved left by the number of bits
shift) present in the right operand.
>>(right The left operand is moved right by the number of bits
shift) present in the right operand.
08/03/2023

Logical Operators
41

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.
08/03/2023

Membership Operators
42

Operator Description

in It is evaluated to be true if the first operand is found in the second


operand (list, tuple, or dictionary).

not in It is evaluated to be true if the first operand is not found in the


second operand (list, tuple, or dictionary).
08/03/2023

Identity Operators
43

Operator Description
is It is evaluated to be true if the reference present at
both sides point to the same object.
is not It is evaluated to be true if the reference present at
both sides do not point to the same object.
08/03/2023

Python If-else statements


44

Statement Description

If Statement The if statement is used to test a specific condition. If the


condition is true, a block of code (if-block) will be executed.

If - else The if-else statement is similar to if statement except the fact


Statement that, it also provides the block of the code for the false case
of the condition to be checked. If the condition provided in
the if statement is false, then the else statement will be
executed.

Nested if Nested if statements enable us to use if ? else statement inside


Statement an outer if statement.
08/03/2023

The if statement
45

Example:
num = int(input("enter the number?"
)) 
if num%2 == 0:  
    print("Number is even")  

Output:
enter the number?10
Number is even
08/03/2023

The if-else statement


46

Example 1 : Program to check whether a person is eligible to vote or not.


Program:
age = int (input("Enter your age? "))  
if age>=18:  
    print("You are eligible to vote !!");  
else:  
    print("Sorry! you have to wait to vote !!");  
Output:
Enter your age? 90
You are eligible to vote !!
08/03/2023

The elif statement


47

Example 1
Program
number = int(input("Enter the number?"))  
if number==10:  
    print("number is equals to 10")  
elif number==50:  
    print("number is equal to 50");  
elif number==100:  
    print("number is equal to 100");  
else:  
    print("number is not equal to 10, 50 or 100");  
Output:
Enter the number?15
number is not equal to 10, 50 or 100
08/03/2023

Python Loops
48

 Why we use loops in python?


 Simplifies the complex problems
 To alter the flow of the program so
that instead of writing the same
code again and again, we can repeat
the same code for a finite number of
times.
 For example, if we need to print the
first 10 natural numbers then,
instead of using the print statement
10 times, we can print inside a loop
which runs up to 10 iterations
08/03/2023

Loop statements in Python


49

Loop Description
Statement

for loop The for loop is used in the case where we need to execute some part
of the code until the given condition is satisfied. The for loop is also
called as a per-tested loop. It is better to use for loop if the number
of iteration is known in advance.

while loop The while loop is to be used in the scenario where we don't know
the number of iterations in advance. The block of statements is
executed in the while loop until the condition specified in the while
loop is satisfied. It is also called a pre-tested loop.

do-while loop The do-while loop continues until a given condition satisfies. It is
also called post tested loop. It is used when it is necessary to execute
the loop at least once (mostly menu driven programs).
08/03/2023

Python for loop


50

Example: Iterating string using for loop


Program
str = "Python"  
for i in str:  
    print(i)  
Output:
P
y
t
h
o
n
51

Nested for loop in python


For loop Using


Program:
range() function rows = int(input("Enter the rows:"))  
for i in range(0,rows+1):  
Program:     for j in range(i):  
        print("*",end = '')  
for i in range(10):       print()  
Output:
    print(i,end = ' ')   Enter the rows:5

Output: *
**
0123456789 ***
****
*****

08/03/2023

You might also like