1.
Introduction
2. Features
3. IDLE python interpreter
4. Writing and Executing Scripts
5. Basics(Comments, Identifiers, Keywords, Variables, Data types etc.)
6. Operators, & Statements
7. Ifs, Loops, & Nesting
8. Functions In Detail (User defined, Built in and Parameters)
9. Strings and String Functions
[Link]
[Link]
[Link]
[Link]
[Link] We Play a Game?
[Link] ?
1. Introduction
• Guido van Rossum began working on Python in the late 1980s, as a
successor to the ABC programming language, and first released it in 1991
as Python 0.9.0.
• Python is a general-purpose object-oriented programming language with
high-level programming capabilities.
• It has become famous because of its apparent and easily understandable
syntax, portability and easy to learn.
• Python is a programming language that includes features of C and Java.
1. Introduction
• Python is Interpreted − Python is processed at runtime by the interpreter.
You do not need to compile your program before executing it. This is
similar to PERL and PHP.
• Python is Interactive − You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
• Python is Object-Oriented − Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
• Python is a Beginner's Language − Python is a great language for the
beginner-level programmers and supports the development of a wide
range of applications from simple text processing to WWW browsers to
games.
2. Features
• Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain − Python's source code is fairly easy-to-maintain.
• A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which
allows interactive testing and debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has
the same interface on all platforms.
2. Features
• 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.
3. IDLE Interpreter
• IDLE (short for Integrated Development and Learning Environment) is
an integrated development environment for Python, which has been
bundled with the default implementation of the language.
• IDLE is intended to be a simple IDE and suitable for beginners, especially in
an educational environment.
4. Writing and Executing Scripts
• A plain text file containing Python code that is intended to be directly
executed by the user is usually called script, which is an informal term that
means top-level program file.
• On the other hand, a plain text file, which contains Python code that is
designed to be imported and used from another Python file, is
called module.
• Run from Command Line & IDE
• Write code as and save with a file name and extension [Link]
4. Writing and Executing Scripts
Command Line
4. Writing and Executing Scripts
Interactive
5. Basics > Comments
• Comments in Python starts with the hash sign (#).
• Every character in that line after the hash sign is considered as the
comment and will not be executed by Interpreter.
• Two Type of Comments
• 1. Single Line Comments #this is a comment
• 2. Multiline Comments
"""
This is a comment
written in
more than just one line
"""
5. Basics > Identifiers
• Identifiers are names used for identifying functions, classes, modules or
variables.
• They can start with an underscore or with letter (uppercase or lowercase).
Can be followed by numbers, letters or underscores, but can’t be followed
by special characters (@, $, %).
• You can’t use reserved words as an identifier
• Case sensitive
• Valid Names -> abc, _abc, ABC, a123, my_variable
• Invalid Names -> 1A4, ab$,
5. Basics > Identifiers
• identifiers that start with underscore usually have special meaning:
1. one single leading underscore (_name) - identifier is meant to be private
2. two leading underscores (__name) - identifier is private and you can’t call it
from outside of the class
3. two leading and two ending underscores (__name__) - identifier is
reserved for special use in the language.
Example : __init__ is for object constructors
5. Basics > Keywords
• Reserved Words must not be used as identifier.
• Used by the interpreter.
• Holds Special Meaning
and, as, assert, break, class, continue, def, del, elif, else, except, exec,
finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, print,
raise, return, try, while, with, yield.
5. Basics > Variables
• Python supports different types of variables (datatypes) such as whole
numbers, floating point numbers and text.
• You do not need to specify the datatype of a variable, you can simply
assign any value to a variable.
eg:
x = 3 # a whole number
f = 3.1415926 # a floating point number
name = "Python" # a string
5. Basics > Data Types
Divided into following categories
1. Numeric
2. Sequence Types
3. Boolean
4. Set
5. Dictionary
5. Basics > Data Types> Numeric
• In Python, numeric data type represent the data which has numeric value.
Numeric value can be integer, floating number or even complex numbers. These
values are defined as int, float and complex class in Python.
• Integers – This value is represented by int class. It contains positive or negative
whole numbers (without fraction or decimal). In Python there is no limit to how
long an integer value can be.
• Float – This value is represented by float class. It is a real number with floating
point representation. It is specified by a decimal point. Optionally, the character e
or E followed by a positive or negative integer may be appended to specify
scientific notation.
• Complex Numbers – Complex number is represented by complex class. It is
specified as (real part) + (imaginary part)j. For example – 2+3j
5. Basics > Data Types> Numeric
Output
5. Basics > Data Types> Sequence Types
• In Python, sequence is the ordered collection of similar or different data
types. Sequences allows to store multiple values in an organized and
efficient fashion. There are several sequence types in Python –
1. String
2. List
3. Tuple
5. Basics > Data Types> Sequence Types
String
• In Python, Strings are arrays of bytes representing Unicode characters. A
string is a collection of one or more characters put in a single quote,
double-quote or triple quote. In python there is no character data type, a
character is a string of length one. It is represented by str class.
• a = ‘ single quote’
• b = “ double quote ”
• C = ‘’’ multi
line
string ‘’’
5. Basics > Data Types> Sequence Types
List
• Lists are just like the arrays, declared in other languages which is an
ordered collection of data.
• It is very flexible as the items in a list do not need to be of the same type.
• List = [] #creates a blank list
• List =[1,’a’,3.14]
5. Basics > Data Types> Sequence Types
Tuple
• Just like list, tuple is also an ordered collection of Python objects. The only
difference between type and list is that tuples are immutable i.e. tuples
cannot be modified after it is created. It is represented by tuple class.
• Tuple1 = ()
• Tuple1 = (0, 1, 2, 3)
• Tuple2 = ('python', ‘wizard')
• Tuple3 = (Tuple1, Tuple2) # ((0,1,2,3),(python, wizard))
5. Basics > Data Types> Boolean
• Data type with one of the two built-in values, True or False.
• It is denoted by the class bool.
a= True
b= False
5. Basics > Data Types> Set
• In Python, Set is an unordered collection of data type that is iterable,
mutable and has no duplicate elements.
• The order of elements in a set is undefined though it may consist of various
elements.
a={1,2,4,3}
b={True,False,1,2,4,’hello’}
5. Basics > Data Types> Dictionary
• Dictionary in Python is an unordered collection of data values, used to
store data values like a map, which unlike other Data Types that hold only
single value as an element, Dictionary holds key : value pair.
• Key-value is provided in the dictionary to make it more optimized.
• Each key-value pair in a Dictionary is separated by a colon :, whereas each
key is separated by a ‘comma’.
a = {1: ‘Hello', 2: ‘Python', 3: ‘Wizard'}
B = {‘a’:1,’b’:2,’c’:3}
6. Operators & Statements
Operators
• Operators in general are used to perform operations on values and variables in
Python.
• These are standard symbols used for the purpose of logical and arithmetic
operations.
Types of Operations
1. Arithmetic (+,-,*,/,//,%,**)
2. Relational (<,>,<=,>=,==,!=)
3. Logical (and, or, not)
4. Bitwise ( &,|,~,^,>>,<<)
5. Assignment (=,+=,-=,*=,/=,//=,**=,&=,|=,^=,>>=,<<=)
6. Special (identity[is, is not],membership[in, not in])
6. Operators & Statements
1. Arithmetic Operators
6. Operators & Statements
2. Relational Operators
6. Operators & Statements
3. logical Operators
6. Operators & Statements
4. Bitwise Operators
6. Operators & Statements
5. Assignment Operators
6. Operators & Statements
5. Assignment Operators
6. Operators & Statements
6. Special Operators
i) Identity operators-
is and is not are the identity operators both are used to check if two values
are located on the same part of the memory. Two variables that are equal
does not imply that they are identical.
6. Operators & Statements
6. Special Operators
ii) Membership operators-
in and not in are the membership operators; used to test whether a value or
variable is in a sequence.
6. Operators & Statements
Operator Precedence
• This is used in an expression with more than one operator with different
precedence to determine which operation to perform first.
6. Operators & Statements
6. Operators & Statements
Operator Associativity: If an expression contains two or more operators with
the same precedence then Operator Associativity is used to determine which
operation is to be calculated first. It can either be Left to Right or from Right
to Left.
6. Operators & Statements
6. Operators & Statements
Statements
• Instructions written in the source code for execution are called statements.
• There are different types of statements in the Python programming
language like Assignment statements, Conditional statements, Looping
statements, etc.
• Multi-Line Statements: Statements in Python can be extended to one or
more lines using parentheses (), braces {}, square brackets [], semi-colon
(;), continuation character slash (\).
• When the programmer needs to do long calculations and cannot fit his
statements into one line, one can make use of these characters.
7. Ifs, Loops,
If- else example
if expression: if a > b:
statements print(‘a is greater ’)
else: else:
statements print(‘b is greater ’)
7. Ifs, Loops,
elif example
if expression: a=100
statements b=110
elif expression: if a >b:
statements print('a is greater')
elif expression: elif a==b:
statements print('a and b are equal')
... else :
else: print('b is greater')
statements
7. Ifs, Loops,
Nested If example
if expression: x = 41
if expression2:
statements if x > 10:
else: print("Above ten,")
if x > 20:
statements
print("and also above 20!")
else: else:
statements print("but not above 20.")
7. Ifs, Loops,
For Loop Example
for i in range(1,11):
for i in s: print(i)
statements
S must me iterable such as
lists, tuples, strings
7. Ifs, Loops,
Case 1: If the elements used in iteration are sequences of identical size,
you can unpack their values into individual iteration variables
for x,y,z in s: >>> s=[[1,3,5],[7,9,11]]
statements >>> for x,y,z in s:
... print x,y,z
Output:
1, 3, 5
7, 9, 11
7. Ifs, Loops,
Case 2: Numerical index in addition to the data values
i=0 for i,x in enumerate(s):
for x in s: statements
statements
i += 1 (0, s[0]) , (1, s[1]) , (2, s[2])
7. Ifs, Loops,
Case 3: To break out of a loop, use the break statement , to skip to next
iteration use continue.
for i in range(1,500): for i in range(1,21):
if(i ==20): if(i%2==0):
break continue
print(i) print(i)
7. Ifs, Loops,
Case 4: You can also attach the else statement to loop Constructs.
for i in range(1, 4): for i in range(1, 4):
print(i) print(i)
else: break
print("No Break") else:
print("No Break")
#executes print
# doesn’t execute print
7. Ifs, Loops,
While Loop Example
while expression: a=0
statements while a<10:
print(a)
a+=1
8. Functions
• Substantial programs are broken up into functions for better modularity
and ease of maintenance.
• Python makes it easy to define functions but also incorporates a surprising
number of features from functional programming languages
• Functions are defined with the def statement:
8. Functions
def add(x,y):
return x + y
The body of a function is simply a sequence of statements that
execute when the function is called
invoke a function by writing the function name followed by a tuple of function
arguments, such as
a = add(3,4)
8. Functions
• Two Types of Functions user defined and built in
def add(x,y):
return x + y
add is a user defined function with two parameters
print, type, range, enumerate etc. are built in functions
8. Functions
Examples
a=range(1,11)=>[1,2,3,4,5,6,7,8,9,10]
s=sum(a) => 55
min(a) => 1
max(a) => 10
len(a) => 10
type(True) => <class 'bool'>
res=input(‘enter value’) returns string entered by the user
eval(‘print(5)’) => 5
8. Functions
Mathematical Functions
1. ceil() :- This function returns the smallest integral value greater than the
number. If number is already integer, same number is returned.
[Link](2.3) => 3
2. floor() :- This function returns the greatest integral value smaller than the
number. If number is already integer, same number is returned.
[Link](2.3) => 2
3. fabs() :- This function returns the absolute value of the number.
[Link](-5) => 5.0
8. Functions
Mathematical Functions
4. factorial() :- This function returns the factorial of the number. An error
message is displayed if number is not integral.
[Link](5) => 120
5. copysign(a, b) :- This function returns the number with the value of ‘a’ but
with the sign of ‘b’. The returned value is float type.
[Link](5.5, -10) => -5.5
6. gcd() :- This function is used to compute the greatest common divisor of 2
numbers mentioned in its arguments.
[Link](5,13)
8. Functions
Date and Time
from datetime import date, time, datetime
d= date(year=2020, month=1, day=31)
t = time(hour=13, minute=14, second=31)
dt= datetime(year=2020, month=1, day=31, hour=13, minute=14, second=31)
current_date =[Link]()
current_datetime = [Link]()
8. Functions
Random Numbers
import random
1. choice() is an inbuilt function in the Python programming language that
returns a random item from a list, tuple, or string.
Eg: list1 = [1, 2, 3, 4, 5, 6]
print([Link](list1))
string = “python"
print([Link](string))
8. Functions
Random Numbers
import random
2. randrange(): The random module offers a function that can generate
random numbers from a specified range
Eg: print([Link](20, 50)
3. random():- This method is used to generate a float random number less
than 1 and greater or equal to 0.
print([Link]()) => 0.3015705138740721
8. Functions
Function Composition
Function composition is the way of combining two or more functions in such a
way that the output of one function becomes the input of the second
function and so on.
def add(x): c=composite(add,mul)
return x+2 print(c(10))
def mul(x):
return x * 2
def composite(f,g):
return lambda x:f(g(x))
8. Functions
Parameter and Arguments
A parameter is the variable defined within the parentheses during function
definition. Simply they are written when we declare a function.
# Here a,b are the parameters
def sum(a,b):
print(a+b)
sum(1,2)
8. Functions
Parameter and Arguments
An argument is a value that is passed to a function when it is called. It might
be a variable, value or object passed to a function or method as input. They
are written when we are calling the function.
# Here a,b are the parameters
def sum(a,b):
print(a+b)
# here 1 and 2 are arguments
sum(1,2)
8. Functions
Types of arguments in python:
Python functions can contain two types of arguments:
• Positional Arguments
• Keyword Arguments
Positional Arguments are needed to be included in proper order i.e the first
argument is always listed first when the function is called, second argument
needs to be called second and so on.
Eg:
def add(first,second):
return first+second
add(1,2) 1 and 2 are positional arguments
8. Functions
Keyword Arguments is an argument passed to a function or method which is
preceded by a keyword and an equal to sign. The order of keyword argument
with respect to another keyword argument does not matter because the
values are being explicitly assigned.
Eg:
def add(first,second):
return first+second
add(second=2,first=1) keyword arguments
8. Functions
Default Arguments
Python allows function arguments to have default values. If the function is
called without the argument, the argument gets its default value.
Eg:
def add(first,second=2):
return first+second
add(1)
only first argument is passed , second argument takes default value
8. Functions
Arbitrary Arguments
Sometimes, we do not know in advance the number of arguments that will be
passed into a function. Python allows us to handle this kind of situation
through function calls with an arbitrary number of arguments.
def many(*args):
x=0;
for i in args:
x+=i
return x
s=many(1,2,3,4,5,6,7,8,9,10)
8. Functions
Variables that are created outside of a function are known as global variables.
Global variables can be used by everyone, both inside of functions and
outside.
x = "awesome"
def myfunc():
#global x
x= "fantastic"
myfunc()
print("Python is " + x)
8. Functions
Recursion
it is a process in which a function calls itself directly or indirectly.
def factorial(n):
if n <= 1: return 1
else: return n * factorial(n - 1)
9. Strings and String Functions
String is a sequence of characters.
Python has a set of built-in methods that you can use on strings.
1. capitalize() method returns a string where the first character is upper
case.
2. casefold() method returns a string where all the characters are lower
case.
3. center() method will center align the string, using a specified character
(space is default) as the fill character.
4. count() method returns the number of times a specified value appears in
the string.
5. title() method returns a string where the first character in every word is
upper case. Like a header, or a title.
9. Strings and String Functions
6. upper() method returns a string where all characters are in upper case.
7. lower() method returns a string where all characters are lower case.
8. endswith() method returns True if the string ends with the specified value,
otherwise False.
9. startswith() method returns True if the string starts with the specified
value, otherwise False.
10. split() method splits a string into a list.
11. swapcase() method returns a string where all the upper case letters are
lower case and vice versa.
12. replace() method replaces a specified phrase with another specified
phrase.
10. Lists
• Lists are sequences of arbitrary objects.
• You create a list by enclosing values in square brackets or with list()
• lists are mutable
• Elements can be reassigned or removed, and new elements can be
inserted
• eg: mylist = [1,2,3,4,’hello’,True,False]
• List Functions
1. [Link](‘item’) ->adds an item to end of the list
2. [Link](2,’third item’)
3. [Link]() sorts list item in ascending order
4. [Link](1) removes item 1
10. Lists
List Functions
letters = [‘a’,’b’,’c’,’d’,’e’,’f’]
b = letters[0:2] #returns [‘a’,’b’]
c= letters [2:] #returns [‘c’,’d’,’e’,’f’]
d = letters[1] #d=b
letters[0]=‘z’ #replaces a with z
Add two lists a=[1,2,3,4,5] b=[6,7,8,9,10]
c=a+b #[1,2,3,4,5,6,7,8,9,10]
11. Tuples
• used to store multiple items in a single ordered set.
• However, unlike lists, tuples are immutable -they can't be changed after
they're created
• To create a tuple, you place one or more comma separated elements in
parentheses or with tuple()
• myTuple = (3, 2.7, 'Thursday')
• Functions
• len(myTuple) #returns length of the tuple ie 3
• [Link](1) #returns index of item here 0
• a=myTuple[0] #a=1
• [Link](1) # returns number of occurrence of 1 in the tuple
12. Sets
• set is a collection which is unordered and un indexed.
• In Python sets are written with curly brackets
• Eg: mySet = {5,1,8,4}
• Unlike lists and tuples, sets are unordered and cannot be indexed by
numbers.
• Also we can write mySet=set([5,1,8,4])
Functions
New items can be added to a set using add() or update()
[Link](9) # Add a single item
[Link]([10,37,42]) # Adds multiple items to s
[Link](4)
12. Sets
• t={1,2,3,4,5}
• S={5,6,7,8,9,10}
• a = t | s # Union of t and s
• b = t & s # Intersection of t and s
• c = t – s # Set difference (items in t, but not in s)
• d = t ^ s # Symmetric difference (items in t or s, but not both)
13. Dictionary
• d={'name':'Arun','age':20,'gender':'male','phone':'9995559990'}
Questions ..
76