Python
Python
QED LEARNINGS
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
C/Java/Python
WAP to print your name.
C
#include<stdio.h>
#include<conio.h>
Void main()
{
Printf(“SOFCON”);
}
3
Java
class Name
{
Public static void main(String args[])
{
System.out.println(“SOFCON”);
}
}
4
Python
Print(“SOFCON”);
5
Compiling and interpreting
interpret
source code output
Hello.py
6
Expressions
expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
42
Arithmetic operators we will use:
+ - * / addition, subtraction/negation, multiplication,
division
% modulus, a.k.a. remainder
** exponentiation
7
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
Examples: x = 5
gpa = 3.14
x 5 gpa 3.14
A variable that has been given a value can be used in expressions.
x + 4 is 9
9
Variable
10
Memory Representation of
variable
11
Example
12
print
print : Produces text output on the console.
Syntax:
print "Message"
print Expression
Prints the given text message or expression value on the console, and
moves the cursor down to the next line.
Examples:
print "Hello, world!"
age = 45
print "You have", 65 - age, "years until retirement"
Output:
Hello, world!
You have 20 years until retirement
13
input
input : Reads a number from user input.
You can assign (store) the result of input into a variable.
Example:
age = input("How old are you? ")
print "Your age is", age
print "You have", 65 - age, "years until retirement"
Output:
How old are you? 53
Your age is 53
You have 12 years until retirement
14
Comments
Comment procedure is so simple in python.
Two ways of comments-
Single Line
Multi Line
15
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
16
Strings
string: A sequence of text characters in a program.
Strings start and end with quotation mark " or apostrophe ' characters.
Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."
17
String properties
len(string) - number of characters in a string
(including spaces)
str.lower(string) - lowercase version of a string
str.upper(string) - uppercase version of a string
Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = str.upper(name)
print big_name, "has", length, "characters"
Output:
MARTIN DOUGLAS STEPP has 20 characters
18
Example
19
Slicing
You can take a shorter substring inside a longer strings.
Name[Starting point : Ending point]
name=“SAM”
print(name[0:1]);
20
Concatenation
Combine two string.
msg=“Hello”+”Have”+”a”+”Nice”+”Day”
print(msg);
21
Functions
Way of wrap your code.
def hi():
print(“hello”);
hi();
def add(a,b):
c=a+b;
print(c)
add(a,b);
22
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."
23
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."
Example:
for x in range(1, 6):
print x, "square is", x * x
Output:
1 square is 1
2 square is 4
3 square is 9
4 square is 16
5 square is 25
25
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!
Exercise: How would we print the "99 Bottles of Beer" song?
26
While Loop
i =0;
While i <5:
print(i)
i =i+1
27
List
List is an ordered set of values enclosed in square brackets[].
We can use index in square brackets[]
myEmptyList=[]
myIntegerList =[9,4,3,2,8]
myFloatList =[2.0,9.1,5.9,8.123432]
myCharList =['p','y','t','h','o','n']
myStringList =["Hello","Python","Ok done!"]
28
Deriving from another List
myList1 =['first','second','third','fourth','fifth']
myList2 =myList1
myList2 =myList1[0:3]
29
Appending to a List
emptyList =[]
emptyList.append('The Big Bang Theory')
emptyList.append('F.R.I.E.N.D.S')
emptyList.append('Seinfeld')
print(emptyList)
30
Indexing of elements
fruitsList=["Orange","Mango","Banana","Cherry","Blackberry","Avoc
ado","Apple"]
print(len(fruitsList));
31
Using Loops with List
myList =['Last Of Us','Doom','Dota','Halo',' ']
For x in myList:
print(x)
Last Of Us
Doom
Dota
Halo
32
Deleting an element from List
pop( )function:
myList.pop(4)
_____________________________________________________
Del keyword:
del myList[4]
del myList[3:7]
_____________________________________________________
remove( )function:
myList =['Apple','Orange','Apple','Guava']
myList.remove('Apple')
Print(myList)
33
More functions for Lists
1. insert(int, item)
myList=['Python','C++','Java','Ruby','Perl']
myList.insert(1,'JavaScript')
printmyList
2.reverse()
myList.reverse()
3.sort()
myList.sort()
4.myList.sort()
myList.reverse()
34
Dictionaries
Dictionaries are much like lists with an extra parameter called
keys.
Creating a Dictionary
Key Value
Key-1 Element-1
Key-2 Element-2
Key-3 Element-3
Key-4 Element-4
Key-5 Element-5
Syntax
myDictionary ={'Key-1':'Element-1','Key-2':'Element-2','Key-
3':'Element-3','Key-4':'Element-4'}
myDictionary['Key-3']
35
Dictionary with integer keys
integerDictionary={10:"C+
+",20:"Java",30:"Python",40:"Ruby",50:"C#",60:"Perl"}
integerDictionary[30]
36
Dictionary with string as keys
identity={"name":"StudyTonight","type":"Educational","link":"https:
//studytonight.com","tag":"Best place to learn"}
Print(identity['name']+": "+identity['tag'])
37
Accessing elements
For i in myDictionary:
print("Key: "+i +" and Element: "+myDictionary[i])
38
Deleting element(s)
identity={"name":"StudyTonight","type":"Educational","link":"http:/
/studytonight.com","tag":"Best place to learn"}
del identity["link"]
print(identity)
39
Appending element(s)
identity["email":"[email protected]"]
identity
40
Updating existing element(s)
courseAvail ={"Java":"Full-course","C/C++":"Full-
course","DBMS":"Full-course"}
identity.update(courseAvail)
41
Dictionary Functions
len()
len(myDictionary)
____________________________________________________
clear()
myDictionary.clear()
Print(myDictionary)
____________________________________________________
values()
myDictionary.values()
____________________________________________________
keys()
myDictionary.keys()
____________________________________________________
42
Dictionary Functions
items()
myDictionary.items()
________________________________________________
has_key()
myDictionary.has_key("Key-2")
myDictionary.has_key("Key-6")
________________________________________________
cmp()
x ={1:1,2:2,3:3}
y ={1:1,2:2,3:3}
cmp(x,y)
________________________________________________
43
Tuples
A tuple is a sequence of data
To define a tuple, we just have to assign a single variable with
print(myTuple)
secondTuple =1,2,"python",4
print(secondTuple)
44
empty tuple
An empty tuple can be created using the tuple()function or by just
using an empty bracket()
emptyTuple =()
anotherEmptyTuple =tuple()
45
Indexing
example ="apple","orange","banana","berry","mango“
example[0]
46
Adding Elements to a Tuple
t =(1,2,3,4,5)
t =t +(7,)
print(t)
47
Deleting a Tuple
In order to delete a tuple, thedelkeyword is used.
del myTuple
48
Slicing in Tuples
t =(1,2,3,4)
t[2:4]
49
Basic Functions
Multiplication
t =(2,5)
print(t*3)
________________________________________________
Addition
t =(2,5,0)+(1,3)+(4,)
print(t)
________________________________________________
in keyword
t =(1,2,3,6,7,8)
print(2int)
________________________________________________
50
Basic Functions
len()function
t =1,2,3
print(len(t));
______________________________________________
max() and min() function
t =(1,4,2,7,3,9)
print(max(t))
Print(min(t))
51
Modules
A module is a file containing python definitions and statement.
>> Write a program for calculator using module.
52
File Handling
Access Mode
r
W
a
53
Exceptions
ZeroDivisionError: Occurs when a number is divided by zero.
NameError: It occurs when a name is not found. It may be local or
global.
IndentationError: If incorrect indentation is given.
IOError: It occurs when Input Output operation fails.
EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.
54
Without Exception
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print(c)
#other code:
print("Hi I am other part of the program")
55
Syntax
56
With Exception
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except Exception:
print("can't divide by zero")
else:
print("Hi I am else block")
57
Try with multiple except
try:
logic
except Exception:
print()
except Exception:
print()
except Exception:
print()
except Exception:
print()
except Exception:
print()
58
finally block
59
try:
logic;
except:
print("Error")
finally:
print("file closed")
60
OOPs Concepts
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
61
Class
class Employee:
id = 10;
name = "ayush"
def display (self):
print(self.id,self.name)
62
Object
class Employee:
id = 10;
name = "John"
def display (self):
print(self.id,self.name)
emp = Employee()
emp.display()
63
Constructor
A constructor is a special type of method (function) which is used to
initialize the instance members of the class.
Constructors can be of two types.
Parameterized Constructor
Non-parameterized Constructor
64
Creating the constructor
class Employee:
def __init__(self,name,id):
self.id = id;
self.name = name;
def display (self):
print(self.id,self.name)
emp1 = Employee("John",101)
emp2 = Employee("David",102)
emp1.display();
emp2.display();
65
Thank You………..
Have
a
Nice
Day………………….
66