SlideShare una empresa de Scribd logo
1 de 43
GE8151 - Problem Solving and Python Programming
Important University Questions and Answers
Prepared By
B.Muthukrishna Vinayagam, Assistant Professor/CSE
Tower of Hanoi
The print Statement
>>> print ('hello‘)
hello
>>> print ( 'hello', 'there‘ )
hello there
>>>a=15
>>>print(“The value of a is %d.” %(a) )
•Elements separated by commas
print with a space between them
•A comma at the end of the
statement (print ‘hello’,) will not print
a newline character
Interactive Mode Script Mode - filename.py
print (‘hello’)
Run: python filename.py
Output: hello
Variables
• Are not declared, just assigned
• The variable is created the first time you assign it
a value
• Are references to objects
• Type information is with the object, not the
reference
• Everything in Python is an object
Object Pooling
c=a
id(a)
id(b)
Id( c )
Beginners' Python 8
Built-in Object Types (Data Types)
Type Ordered Mutable Examples
Numbers N/A No 3.14, 123, 99L, 1-2j, 071, 0x0a
Strings Yes No 'A string', "A double ed string"
Lists Yes Yes [1, [2, 'three'], [5E-1, 10e3], -8L]
Dictionaries No Yes {‘key':‘value', ‘b':'ball'}
Tuples Yes No (1, 'two', -3j, 04, 0x55, 6L)
Can be changed in place?
Can be indexed/sliced?
Operator
Functions, Procedures A function is a group of
statements that together perform a task.
def name(arg1, arg2, ...):
"""documentation""" # optional doc string
statements
return # from procedure
return expression # from function
Function Basics
def max(x,y) :
if x < y :
return x
else :
return y
>>> import functionbasics
>>> max(3,5)
5
>>> max('hello', 'there')
'there'
>>> max(3, 'hello')
'hello'
functionbasics.py
Anonymous Functions
• A lambda
expression returns a
function object
• The body can only
be a simple
expression, not
complex statements
>>> f = lambda x,y : x + y
>>> f(2,3)
5
>>> lst = ['one', lambda x : x * x, 3]
>>> lst[1](4)
16
Duck Typing
• Function Overloading: achieved polymorphism
#function definition
def add(x,y,z):
return x+y+z
#function calling Output
add(10,20,30) #60
add('muthu',"krishna","vinayagam") #muthukrishnavinayagam
add(5.5,4.5,15.5) #25.5
Example Function
" " " greatest common divisor" " "
def gcd(a, b):
while a != 0:
a, b = b%a, a # parallel assignment
return b
>>> gcd.__doc__
'greatest common divisor'
>>> gcd(12, 20)
4
Required argument
def fun(a,b):
#statement
fun(10) #throws error
Keyword argument
def fun(a,b):
#statement
fun(b=10, a=”Python”)
Default argument with value
def fun(a, b=20):
#statement
fun(10)
Variable length argument
def fun(*var):
#statement
fun(10,20,30)
def foo(x, y):
global a
a = 42
x,y = y,x
b = 33
b = 17
c = 100
print(a,b,x,y)
a, b, x, y = 1, 15, 3,4 foo(17, 4)
print(a, b, x, y)
Global and Local Variable
The output looks like this:
42 17 4 17
42 15 3 4
Strings & its operation
It is collection of characters enclosed by
single/double/triple quotes
Example: 'single quotes' """triple quotes""" r"raw strings"
• "hello"+"world" "helloworld" # concatenation
• "hello"*3 "hellohellohello" # repetition
• "hello"[0] "h" # indexing
• "hello"[-1] "o" # (from end)
• "hello"[1:4] "ell" # slicing
• len("hello") 5 # size
• "hello" < "jello" 1 # comparison
• "e" in "hello" True # search
• "hello“[::-1] “olleh” #reverse
• "escapes: n etc, 033 etc, tif etc“ #display escape sequence
capitalize() Converts first character to Capital Letter
center() Pads string with specified character
count() returns occurrences of substring in string
endswith() Checks if String Ends with the Specified Suffix
encode() returns encoded string of given string
find() Returns the Highest Index of Substring
format() formats string into nicer output
index() Returns Index of Substring
isalnum() Checks Alphanumeric Character
isalpha() Checks if All Characters are Alphabets
Conditional Statements
if condition:
#stm
elif condition:
#stm
else:
#stm
if condition:
#stm
No Switch Statement:
print({1:”one”,2:”Two”,3:”Three”}.get(1,”Invalid”))
if condition:
#stm
else:
#stm
While loop
Syntax
while condition:
#stms
Example:
i=1
While i<=5:
print(i)
i=i+1
Output: 1 2 3 4 5
For Loops
• Similar to perl for loops, iterating through a list of values
~: python forloop1.py
1
7
13
2
for x in [1,7,13,2] :
print xforloop1.py
~: python forloop2.py
0
1
2
3
4
for x in range(5) :
print xforloop2.py
range(N) generates a list of numbers [0,1, …, n-1]
Loop Control Statements
break Jumps out of the closest
enclosing loop
continue Jumps to the top of the closest
enclosing loop
pass Does nothing, empty statement
placeholder
Linear Search
Binary Search
Search 20
List Operations & its methods
>>> a=[1,5,10] # List creation
>>> a = range(5) # [0,1,2,3,4]
>>> a.append(5) # [0,1,2,3,4,5]
>>> a.pop() # [0,1,2,3,4]
5
>>> a.insert(0, 42) # [42,0,1,2,3,4]
>>> a.pop(0) # [0,1,2,3,4]
42
>>> a.reverse() # [4,3,2,1,0]
>>> a.sort() # [0,1,2,3,4]
>>>print(len(a)) #5
Methods Functions
append() to add element to the end of the list
extend() to extend all elements of a list to the another list
insert() to insert an element at the another index
remove() to remove an element from the list
pop() to remove elements return element at the given index
clear() to remove all elements from the list
index() to return the index of the first matched element
count() to count of number of elements passed as an argument
sort() to sort the elements in ascending order by default
reverse() to reverse order element in a list
copy() to return a copy of elements in a list
Tuples
• key = (lastname, firstname)
• point = x, y, z # parentheses optional
• x, y, z = point # unpack
• lastname = key[0]
• singleton = (1,) # trailing comma!!!
• empty = () # parentheses!
Python Expression Results Operation
len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('Hi!',) * 4
('Hi!', 'Hi!', 'Hi!',
'Hi!')
Repetition
3 in (1, 2, 3) True Membership
for x in (1, 2, 3): print x, 1 2 3 Iteration
Tuple and its Operations
tuple=(10,20,20,40)
len(tuple) -> Gives the total length of the tuple.
max(tuple) -> Returns item from the tuple with max value.
min(tuple) -> Returns item from the tuple with min value.
tuple(seq) -> Converts a list into tuple.
tuple1=(10,20,20,40)
tuple2=(20,20,20,40)
cmp(tuple1, tuple2) -> Compares elements of both tuples.
Dictionaries
• Hash tables, "associative arrays"
• d = {"duck": "eend", "water": "water"}
• Lookup:
• d["duck"] #eend
• d["back"] # raises KeyError exception
• Delete, insert, overwrite:
• d["back"] = "rug" # {"duck": "eend", "water": "water“,"back": "rug"}
• del d["water"] # {"duck": "eend", "back": "rug"}
• d["duck"] = "duik" # {"duck": "duik", "back": "rug"}
•Keys, values, items:
d.keys() -> ["duck", "back"]
d.values() -> ["duik", "rug"]
d.items() -> [("duck","duik"), ("back","rug")]
Dictionaries & its Operation & Methods:
len(dict) -> Gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.
str(dict) -> Produces a printable string representation of a dictionary
type(variable) -> Returns the type of the passed variable. If passed variable is dictionary,
then it would return a dictionary type.
cmp(dict1, dict2) -> Compares elements of both dict.
Accessing Values in Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print (dict['Name'])
Updating Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8 # update existing entry
dict['School'] = "DPS School" # Add new entry
print (dict['School'])
Delete Dictionary Elements
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
Five methods are used to delete the elements from the dictionary:
pop(), popitem(), clear(), del(), update(d)
Selection sort
Insertion sort
Mergesort
File operation:
Step1: Open a file object in read or write or append mode
Step2: Read or write the file contents using read() or write()
methods
or
Read or write entire line of file using readline() or
writelines() methods
Step3: Close file object close() method
Example
f=open("sample.txt","r")
print(f.read())
f.close()
File operation
fobj.read(7); # read only 5th bytes
fobj.tell(); #tell the current position
fobj.seek(5); #move to the 5th byte location
import os
os.rename(“old.txt”, “new.txt”)
os.remove(“file.txt”)
File Copy
1)
from shutil import copyfile
copyfile('test.py', 'abc.py')
2)
f1=open(“t.txt","r")
f2=open(“d.txt",“w")
c=f1.read()
f2.write(c)
f1.close()
f2.close()
An exception is an event, which occurs during the execution
of a program that disrupts the normal flow of the program's
instructions.
Need of Exception Handling:
• An exception is an error that happens during execution of a
program. When that error
occurs, Python generate an exception that can be handled,
which avoids your program
to crash.
• Need graceful exit that is save all works and close it.
Syntax:
try:
# Suspected Code
except:
# Remedial Action
Exception: To handle Abnormal
program termination, gracefully exit
while True:
try:
n = int(input("Please enter an integer: "))
break
except ValueError:
print("No valid integer! Please try again ...")
finally:
print("Great, you successfully entered an integer!")
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
Note: if try block doesn’t raise the exception then
else block is executed.
Finally block is always executed or clean up process
User Exception
class MyException(Exception):
#pass
Code snippet
while True:
try:
n = int(input("Please enter an integer: "))
raise MyException("An exception doesn't always prove the rule!")
except ValueError:
print("No valid integer! Please try again ...")
finally:
print("Great, you successfully entered an integer!")
Module: Python has a way to put definitions in a file and use them in a
script or in an interactive instance of the interpreter. Such a file is
called a module; definitions from a module can be imported into other
modules or into the main module
fibo.py
def fib1(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
>>>import fibo or >>>from fibo import fib2
>>>fibo.fib1(5) # 1 1 2 3 5
Package
New directory: demopack
• First.py
• Second.py
• __init__.py
Use Package
Test.py
from demopack import First
from demopack import Second
First.display()
Second.show()

Más contenido relacionado

La actualidad más candente

Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CSowmya Jyothi
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in pythonKarin Lagesen
 
Simple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladderSimple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladderMoni Adhikary
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract classAmit Trivedi
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and PackagesDamian T. Gordon
 
programming in C++ report
programming in C++ reportprogramming in C++ report
programming in C++ reportvikram mahendra
 
Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfixSelf-Employed
 
Call by value
Call by valueCall by value
Call by valueDharani G
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 

La actualidad más candente (20)

Stack using Array
Stack using ArrayStack using Array
Stack using Array
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Python functions
Python functionsPython functions
Python functions
 
Simple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladderSimple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladder
 
Strings in C
Strings in CStrings in C
Strings in C
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
programming in C++ report
programming in C++ reportprogramming in C++ report
programming in C++ report
 
Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfix
 
Python Manuel-R2021.pdf
Python Manuel-R2021.pdfPython Manuel-R2021.pdf
Python Manuel-R2021.pdf
 
Python basic
Python basicPython basic
Python basic
 
Call by value
Call by valueCall by value
Call by value
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 

Similar a GE8151 Problem Solving and Python Programming

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonakaptur
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Chapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptxChapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptxSovannDoeur
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#bleis tift
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184Mahmoud Samir Fayed
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, pythonRobert Lujo
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181Mahmoud Samir Fayed
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1Giovanni Della Lunga
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 

Similar a GE8151 Problem Solving and Python Programming (20)

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Chapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptxChapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptx
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
python codes
python codespython codes
python codes
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181The Ring programming language version 1.5.2 book - Part 26 of 181
The Ring programming language version 1.5.2 book - Part 26 of 181
 
PythonOOP
PythonOOPPythonOOP
PythonOOP
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1
 
Five
FiveFive
Five
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 

Último

HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxruthvilladarez
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 

Último (20)

HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 

GE8151 Problem Solving and Python Programming

  • 1. GE8151 - Problem Solving and Python Programming Important University Questions and Answers Prepared By B.Muthukrishna Vinayagam, Assistant Professor/CSE
  • 2.
  • 4. The print Statement >>> print ('hello‘) hello >>> print ( 'hello', 'there‘ ) hello there >>>a=15 >>>print(“The value of a is %d.” %(a) ) •Elements separated by commas print with a space between them •A comma at the end of the statement (print ‘hello’,) will not print a newline character Interactive Mode Script Mode - filename.py print (‘hello’) Run: python filename.py Output: hello
  • 5. Variables • Are not declared, just assigned • The variable is created the first time you assign it a value • Are references to objects • Type information is with the object, not the reference • Everything in Python is an object
  • 6.
  • 8. Beginners' Python 8 Built-in Object Types (Data Types) Type Ordered Mutable Examples Numbers N/A No 3.14, 123, 99L, 1-2j, 071, 0x0a Strings Yes No 'A string', "A double ed string" Lists Yes Yes [1, [2, 'three'], [5E-1, 10e3], -8L] Dictionaries No Yes {‘key':‘value', ‘b':'ball'} Tuples Yes No (1, 'two', -3j, 04, 0x55, 6L) Can be changed in place? Can be indexed/sliced?
  • 10. Functions, Procedures A function is a group of statements that together perform a task. def name(arg1, arg2, ...): """documentation""" # optional doc string statements return # from procedure return expression # from function
  • 11. Function Basics def max(x,y) : if x < y : return x else : return y >>> import functionbasics >>> max(3,5) 5 >>> max('hello', 'there') 'there' >>> max(3, 'hello') 'hello' functionbasics.py
  • 12. Anonymous Functions • A lambda expression returns a function object • The body can only be a simple expression, not complex statements >>> f = lambda x,y : x + y >>> f(2,3) 5 >>> lst = ['one', lambda x : x * x, 3] >>> lst[1](4) 16
  • 13. Duck Typing • Function Overloading: achieved polymorphism #function definition def add(x,y,z): return x+y+z #function calling Output add(10,20,30) #60 add('muthu',"krishna","vinayagam") #muthukrishnavinayagam add(5.5,4.5,15.5) #25.5
  • 14. Example Function " " " greatest common divisor" " " def gcd(a, b): while a != 0: a, b = b%a, a # parallel assignment return b >>> gcd.__doc__ 'greatest common divisor' >>> gcd(12, 20) 4
  • 15. Required argument def fun(a,b): #statement fun(10) #throws error Keyword argument def fun(a,b): #statement fun(b=10, a=”Python”) Default argument with value def fun(a, b=20): #statement fun(10) Variable length argument def fun(*var): #statement fun(10,20,30)
  • 16. def foo(x, y): global a a = 42 x,y = y,x b = 33 b = 17 c = 100 print(a,b,x,y) a, b, x, y = 1, 15, 3,4 foo(17, 4) print(a, b, x, y) Global and Local Variable The output looks like this: 42 17 4 17 42 15 3 4
  • 17. Strings & its operation It is collection of characters enclosed by single/double/triple quotes Example: 'single quotes' """triple quotes""" r"raw strings" • "hello"+"world" "helloworld" # concatenation • "hello"*3 "hellohellohello" # repetition • "hello"[0] "h" # indexing • "hello"[-1] "o" # (from end) • "hello"[1:4] "ell" # slicing • len("hello") 5 # size • "hello" < "jello" 1 # comparison • "e" in "hello" True # search • "hello“[::-1] “olleh” #reverse • "escapes: n etc, 033 etc, tif etc“ #display escape sequence
  • 18. capitalize() Converts first character to Capital Letter center() Pads string with specified character count() returns occurrences of substring in string endswith() Checks if String Ends with the Specified Suffix encode() returns encoded string of given string find() Returns the Highest Index of Substring format() formats string into nicer output index() Returns Index of Substring isalnum() Checks Alphanumeric Character isalpha() Checks if All Characters are Alphabets
  • 19. Conditional Statements if condition: #stm elif condition: #stm else: #stm if condition: #stm No Switch Statement: print({1:”one”,2:”Two”,3:”Three”}.get(1,”Invalid”)) if condition: #stm else: #stm
  • 20. While loop Syntax while condition: #stms Example: i=1 While i<=5: print(i) i=i+1 Output: 1 2 3 4 5
  • 21. For Loops • Similar to perl for loops, iterating through a list of values ~: python forloop1.py 1 7 13 2 for x in [1,7,13,2] : print xforloop1.py ~: python forloop2.py 0 1 2 3 4 for x in range(5) : print xforloop2.py range(N) generates a list of numbers [0,1, …, n-1]
  • 22. Loop Control Statements break Jumps out of the closest enclosing loop continue Jumps to the top of the closest enclosing loop pass Does nothing, empty statement placeholder
  • 25. List Operations & its methods >>> a=[1,5,10] # List creation >>> a = range(5) # [0,1,2,3,4] >>> a.append(5) # [0,1,2,3,4,5] >>> a.pop() # [0,1,2,3,4] 5 >>> a.insert(0, 42) # [42,0,1,2,3,4] >>> a.pop(0) # [0,1,2,3,4] 42 >>> a.reverse() # [4,3,2,1,0] >>> a.sort() # [0,1,2,3,4] >>>print(len(a)) #5
  • 26. Methods Functions append() to add element to the end of the list extend() to extend all elements of a list to the another list insert() to insert an element at the another index remove() to remove an element from the list pop() to remove elements return element at the given index clear() to remove all elements from the list index() to return the index of the first matched element count() to count of number of elements passed as an argument sort() to sort the elements in ascending order by default reverse() to reverse order element in a list copy() to return a copy of elements in a list
  • 27.
  • 28. Tuples • key = (lastname, firstname) • point = x, y, z # parentheses optional • x, y, z = point # unpack • lastname = key[0] • singleton = (1,) # trailing comma!!! • empty = () # parentheses!
  • 29. Python Expression Results Operation len((1, 2, 3)) 3 Length (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation ('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition 3 in (1, 2, 3) True Membership for x in (1, 2, 3): print x, 1 2 3 Iteration Tuple and its Operations tuple=(10,20,20,40) len(tuple) -> Gives the total length of the tuple. max(tuple) -> Returns item from the tuple with max value. min(tuple) -> Returns item from the tuple with min value. tuple(seq) -> Converts a list into tuple. tuple1=(10,20,20,40) tuple2=(20,20,20,40) cmp(tuple1, tuple2) -> Compares elements of both tuples.
  • 30. Dictionaries • Hash tables, "associative arrays" • d = {"duck": "eend", "water": "water"} • Lookup: • d["duck"] #eend • d["back"] # raises KeyError exception • Delete, insert, overwrite: • d["back"] = "rug" # {"duck": "eend", "water": "water“,"back": "rug"} • del d["water"] # {"duck": "eend", "back": "rug"} • d["duck"] = "duik" # {"duck": "duik", "back": "rug"} •Keys, values, items: d.keys() -> ["duck", "back"] d.values() -> ["duik", "rug"] d.items() -> [("duck","duik"), ("back","rug")]
  • 31. Dictionaries & its Operation & Methods: len(dict) -> Gives the total length of the dictionary. This would be equal to the number of items in the dictionary. str(dict) -> Produces a printable string representation of a dictionary type(variable) -> Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type. cmp(dict1, dict2) -> Compares elements of both dict. Accessing Values in Dictionary dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print (dict['Name']) Updating Dictionary dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; dict['Age'] = 8 # update existing entry dict['School'] = "DPS School" # Add new entry print (dict['School']) Delete Dictionary Elements dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; del dict['Name']; # remove entry with key 'Name' dict.clear(); # remove all entries in dict del dict ; # delete entire dictionary Five methods are used to delete the elements from the dictionary: pop(), popitem(), clear(), del(), update(d)
  • 35. File operation: Step1: Open a file object in read or write or append mode Step2: Read or write the file contents using read() or write() methods or Read or write entire line of file using readline() or writelines() methods Step3: Close file object close() method Example f=open("sample.txt","r") print(f.read()) f.close()
  • 36. File operation fobj.read(7); # read only 5th bytes fobj.tell(); #tell the current position fobj.seek(5); #move to the 5th byte location import os os.rename(“old.txt”, “new.txt”) os.remove(“file.txt”)
  • 37. File Copy 1) from shutil import copyfile copyfile('test.py', 'abc.py') 2) f1=open(“t.txt","r") f2=open(“d.txt",“w") c=f1.read() f2.write(c) f1.close() f2.close()
  • 38. An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. Need of Exception Handling: • An exception is an error that happens during execution of a program. When that error occurs, Python generate an exception that can be handled, which avoids your program to crash. • Need graceful exit that is save all works and close it. Syntax: try: # Suspected Code except: # Remedial Action
  • 39. Exception: To handle Abnormal program termination, gracefully exit while True: try: n = int(input("Please enter an integer: ")) break except ValueError: print("No valid integer! Please try again ...") finally: print("Great, you successfully entered an integer!")
  • 40. def divide(x, y): try: result = x / y except ZeroDivisionError: print("division by zero!") else: print("result is", result) finally: print("executing finally clause") Note: if try block doesn’t raise the exception then else block is executed. Finally block is always executed or clean up process
  • 41. User Exception class MyException(Exception): #pass Code snippet while True: try: n = int(input("Please enter an integer: ")) raise MyException("An exception doesn't always prove the rule!") except ValueError: print("No valid integer! Please try again ...") finally: print("Great, you successfully entered an integer!")
  • 42. Module: Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module fibo.py def fib1(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print() def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result >>>import fibo or >>>from fibo import fib2 >>>fibo.fib1(5) # 1 1 2 3 5
  • 43. Package New directory: demopack • First.py • Second.py • __init__.py Use Package Test.py from demopack import First from demopack import Second First.display() Second.show()