0% found this document useful (0 votes)
0 views

Python

Python is a high-level, object-oriented, interpreted programming language created by Guido Van Rossum in 1991, with the latest version being 3.7. It features standard data types such as numbers, strings, lists, tuples, and dictionaries, and supports various programming paradigms including procedural, functional, and object-oriented programming. The document also covers basic syntax, control statements, loops, functions, modules, packages, file handling, exception handling, and multithreading.

Uploaded by

Nida Choudhary
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Python

Python is a high-level, object-oriented, interpreted programming language created by Guido Van Rossum in 1991, with the latest version being 3.7. It features standard data types such as numbers, strings, lists, tuples, and dictionaries, and supports various programming paradigms including procedural, functional, and object-oriented programming. The document also covers basic syntax, control statements, loops, functions, modules, packages, file handling, exception handling, and multithreading.

Uploaded by

Nida Choudhary
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Python programming

Python is a easy, high level and object oriented


programming language. Python is interpreted language it
means the code will be compiled line by line.

Founder for python language is Guido Van Rossum and the


first released in 1991 and latest ver. is : 3.7

Feature of python
Python is object oriented language.
Python is interpreted language.
Python is open sources language.
Cross platform language.
Basic syntax in python

print(“hello to python”)
num=10

print(num)
print(“num is : ”,c, end=‘’)

Input from user


2.x python: raw_input() always return string but input()
return the same type which we have give like int, string.
3.x python: raw_input is not support there is only input()
function that always return string only and we have to
convert in desired type like int, double.
Standard data types

Python has five standard data types :


Numbers (it will be store numeric values.)

String (it will be store string values)

List (it will be store values of different types.)

Tuple (it will store values like list but we can not change after declare the
tuple)

Dictionary (it will be values in the format of key - values)


Operator in python

Some operator are:

Arithmetic : +, -, *, / (decimal),// (quotient), %

Logical : and, or, not

Relational : >, <, >=, <=

Comparison : ==

Conditional(Ternary) : min = a if a < b else b


Control statements

Types of if statements Syntax of elif


If
If-else if num==10:
elif print(“one”)
Nested if elif num==20:
print(“two”)
Syntax: else:
print(“not done.”)
If num==10:
print(‘done’)
else:
print(“not done”)
Loops

Loops are used to repeat the statement.


Types of loop:
for loop
while loop
do-while (not in python)
foreach

-- for loop

for i in range(1,11):
print(i, end=‘’)
Loops

while loop

i=1
while i<=10:
print(i, end=‘’)
i=i+1
String’s

String is important data types in python.

str=“python”

print(type(str)) // to show data types

str[:] -- python
str[0:] -- python
str[:5] -- python
str[:2] -- py
str[1:3] -- yt
note: python always consider last range as n-1.
List

List is used to store different types of data. In list we


use (,) for separate item in list. List always enclosed
with [] (square brackets)

lst=[101,”ankit”,”account”]
lst=[10,20,30,40,50]

note: python is support backward direction indexing and


start always from -1,-2,-3,-4,-5 till first elements.

10 20 30 40 50
-5 -4 -3 -2 -1
Tuple

Tuple is also similar to List in python but it will be used


to store immutable python objects. In tuple collection of
item is separated by comma(,) and enclosed by parentheses.

tpl=(101,”ankit”,”account”)
tpl=(10,20,30,40,50)

note: python is support backward direction indexing and


start always from -1 to -2,-3,-4,-5 till first elements.

10 20 30 40 50
-5 -4 -3 -2 -1
List v/s Tuple

List is enclosed by [] Tuple is enclosed by ()

List is mutable Tuple is immutable

List has a variable Tuple has a fixed length.


length.

List has more Tuple has less


functionality then tuple functionality then list
Dictionary

In python, dictionary is combination of key-value pair.


Value can be any python object but key is immutable like
tuple. Key and value is separated by colon(:) and item is
separated by comma(,) and dictionary is enclosed by curly
braces like : {}

dict={“id”:101, “name”:”ankit”}

print(type(dict))
print(“----- output -----”)
print(dict)
Date time

In

di
Function

Function are the group of statements that can be bind into


a single unit that’s called function name. in python we
will be use “def” keyword to define the function.
Type of function
Simple function
Parameterize function
Call by references function

def myfun():
print(“hello to function”)
Calling:
myfun()
Function

def sum(x, y):


return x+y
sum(10,20)

Call by reference:
In python if we pass simply variable then it behaves like
call by value but when we pass object then python behave
like call by references.
def change(x): def mylst(lst):
x=x+30 lst.append(“hello”)
num=100
change(num) //100 // call by references
Function

Types of arguments
Required
Keyword
Default
Variable-length argument

Required args.: it will required argument which you have


define in function.

keyword args.: In this name of argument is treated as


keyword so in python we can call function with keyword.
Function

Keyword argument

def sum(x, y):


return x+y

sum(x=10, y=20)
sum(y=20, x=10)

Note: the order of argument does not matter.


Function

default argument function: python allow us to define the


value of argument at function definition.(first args can’t
be set as a defualt.)
def sum(x, y=20)
return x+y

sum(10)
sum(10,20)
Variable length argument: in this when we don’t know the
number of argument in advance then python provide the
flexibility to provide the comma separated values which is
internally treated as tuple.
Function

Example of variable length argument.

def display(*employees):
for name in employees:
print(name)

display(“ankit”,”neha”,”sonu”)
Modules

In python we can define our code in separate file


(mycode.py) that’s called module and we can use that code
in another python program by import the specific module.

1. Firstly create mycode.py python file and after that


define your logic or code or statements.
2. def mymsg(employee):
print(“hello dear : ”+employee)

Loading modules in program


 Import statement
 from-import statement
Modules

import statement

import mycode

mycode.mymsg(“ankit”)

import-from statement (when we have multiple function then


we want to call any specific.)

from mycode import mymsg

mymsg(“ankit”) // not need to call module name


Modules

import all attribute from module.

--from mycode import*

Rename the module

import mycode as m

m.mymsg(“ankit”)

dir() function: it will return sorted list of sub-module,


variables and function in given module.
Modules

reload() function: when a module is imported then the code


in top-level portion of the module is executed only once.
If we want to reload that then we will be used “relaod”
function.

--reload(mycode)
Packages

Python provide the feature of hierarchical directory


structure where a package contains sub-package, modules and
sub-modules.
These are following step to define a package.

 Create a directory with name “student”


 Create a CS_student.py file under above directory
 Create a another IT_student.py file under above
directory
 Now to change that director into a python package create
a file with name _init_.py and this is file will be
empty.
Packages

CS_student.py _init_.py
no code here
def CS_Name():
lst=[“ankit”,”sonu”,”amit”] Calling package:
return lst test.py
from student import
IT_student.py CS_student

def IT_Name(): print(CS_student.CS_Name())


lst=[“neha”,”soni”,”preeti”]
return lst
File handling

File handling we can write the data in text file and also
read the data text file in python program.

Syntax for create file:


myfile = open(“test.txt”,”w”) // creating file

Myfile.close() // close file in memory

w: it will create or over write file every time.


r: it will read the data in existing file.
a: it will append data in existing file if file is not
exist then it will be create new file.
Exception handling

By the exception handling we can manage runtime error’s.


We will be use following keyword/block…

 try
 except
 else
 finally
 raise
Object Oriented Programming

Python, like another high programming language is also


Object oriented programming language. And python is follow
the given oop’s concept.

 class
 Object
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
Object Oriented Programming

class: class is a user define data type that contains


attributes and methods.

object: by the object we can use/access class’s attributes,


method etc.

abstraction: it means to hide internal detail and show only


necessary detail / functionality.

encapsulation: in this we can wrapped code, data and


methods within the class.
Object Oriented Programming

inheritance: by the inheritance a class can acquire the


properties of another class.

polymorphism: it means to have multiple form’s.


Access modifier in python

public: All members in a Python class are public by


default

private: a prefix (__) double underscore prefixed to a


variable makes it private.

protected : to make a variable protected is to add a


prefix _ (single underscore) to it.
Constructor in python

Constructor’s are the special type of method/function which


called automatically when we create instance/object of the
class.

Types of constructor

non-parameterized constructor (default)


Parameterized constructor

inbuild: to make a variable protected is to add a prefix


_ (single underscore) to it.
Constructor (in-built function)

in-build class function

getattr(obj,name,default): It is used to access the


attribute of the object.

setattr(obj, name,value) : It is used to set a particular


value to the specific attribute of an object.

delattr(obj, name) : It is used to delete a specific


attribute.
hasattr(obj, name) : It returns true if the object
contains some specific attribute.
Inheritance in python

Inheritance is a mechanism by which a class can acquire


the properties/attributes from another class.

Types of inheritance

single inheritance
multi-level inheritance
multiple inheritance
Regular Expressions

Regular expression is sequence of special character which


used to search or find in a given string.
module re // used to support regex in python.
import re

Regex function in python:


Match() : it will find the match object in beginning of
string only.
Search():it will find the match object in given
string.(return only first occurrence for pattern/string)

Match object method (used with match and search only)


Regular Expressions

span(): it will return tuple containing the starting and


end position of match.
string(): it will return string passed into the
function.(used with only match object)
group(): it will return match part of the string.

Findall(): it will return a list contains all matches.

Split(): it will return a list in which string has been


split in each match.

Sub():it will replace one or many matches in the string.


Meta characters

S.No. Meta character Working Example


1 . Any character (except newline character) "he..o"
2 ^ Starts with "^hello"
Signals a special sequence (can also be used to escape
3 \ "\d"
special characters)
4 [] A set of characters "[a-m]"
5 () Capture and group
6 $ Ends with "world$"
7 * Zero or more occurrences "aix*"
8 + One or more occurrences "aix+"
9 {} Exactly the specified number of occurrences "al{2}"
10 | Either or "falls|stays"
Special sequences

S.No. Meta Working Example


Character
1 \A Returns a match if the specified characters are at the beginning of the string "\AThe"
Returns a match where the specified characters are at the beginning or at the end r"\bain"
2 \b
of a word r"ain\b"
Returns a match where the specified characters are present, but NOT at the r"\Bain"
3 \B
beginning (or at the end) of a word r"ain\B"
4 \d Returns a match where the string contains digits (numbers from 0-9) "\d"
5 \D Returns a match where the string DOES NOT contain digits "\D"
6 \s Returns a match where the string contains a white space character "\s"
7 \S Returns a match where the string DOES NOT contain a white space character "\S"
Returns a match where the string contains any word characters (characters from a
8 \w "\w"
to Z, digits from 0-9, and the underscore _ character)
9 \W Returns a match where the string DOES NOT contain any word characters "\W"
10 \Z Returns a match if the specified characters are at the end of the string "Spain\Z"
Multithreading

By multithreading we can run multi thread instead of


multiples different program.

Advantage of multithreading:
Multiple thread share same data space with main thread.
Thread also called light-weighted process because they
are not required much more memory.
We can also put the thread on hold(sleep) while other
thread are still running and that called yielding.
It can be pre-empted.
Multithreading

import threading
import time

Create thread

thread.start_new_thread(“method name”)
time.sleep(5) //seconds

threading modules:

threading.activeCount() − Returns the number of thread


objects that are active.
Multithreading

threading.currentThread() − Returns the number of thread


objects in the caller's thread control.

threading.enumerate() − Returns a list of all thread


objects that are currently active.

run() − The run() method is the entry point for a thread.

start() − The start() method starts a thread by calling the


run method.

join([time]) − The join() waits for threads to terminate.


Multithreading

isAlive() − The isAlive() method checks whether a thread is


still executing.

getName() − The getName() method returns the name of a


thread.

setName() − The setName() method sets the name of a thread.

You might also like