Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Basics

Download as pdf or txt
Download as pdf or txt
You are on page 1of 75
At a glance
Powered by AI
Python is a high-level, interpreted, general-purpose programming language. It supports object-oriented, imperative and functional programming styles.

The standard data types in Python are numeric, string, list, tuple, dictionary and boolean.

String operations include slicing, concatenation, repetition etc.

Chapter-01

Python Basics
Contents
•Data types in python •Dictionaries
•Operators in python Exception
•Input & Output •Introduction to OOP
•Control statement •Classes
•Arrays in python •Objects
•Strings and characters in python •Interfaces
•Functions •Inheritance
•List and tuples
How to write , save and run first python program?

•Versions: python 2.0 to python 3.6.1


•Features of python: Simple, Open source, Interpreted,
high level, object oriented & procedure oriented.
•Installation
•Running python
–Python interpreter
–Python IDLE(integrated development learning
environment)
How to write , save and run first python program?

•Versions: python 2.0 to python 3.6.1


•Features of python: Simple, Open source, Interpreted,
high level, object oriented & procedure oriented.
•Installation
•Running python
–Python interpreter
–Python IDLE(integrated development learning
environment)
•Interactive python
–print(“hello”)
–2+4
–2*4
–4-2
–4/2
Data types in python

1. Comments
–By #
–>>> 8+9 # Addition
–>>>17
2. Python identifiers
•Identifiers – name given to a variable
•Not accept- @,$,% as identifiers
•Case sensitive
Hello & hello both are different identifiers.
•Class name always start with capital letter
Examples:
Valid identifiers Invalid Identifiers
Myname My Name(space not allowed)
My_name 3dfig( can not start with digit)
Your_name Your#name(#not allowed)
3. Reserve Words
l Python has a list of reserved words known as keywords.
l and,del,from,none,as,elif,global,nonlocal,assert,else,if,not,b
reak,except,import,or,class,false,
in,pass,continue,finally,is,raise,def,for,lambda, return
4. Variables:
Declaring a variable:
•A variable holds a value that may change
•The process of writing the variable name is called
“Declaring the variable”
•Initializing a variable:
lvariable=expression
For ex:
>>>Year=2018
>>>name=‘SPB’
>>>year
>>>name
Data Types
Standard Data Types

•6 data types
1.Numeric
2.String
3.List
4.Tuple
5.Dictionary
6.Boolean
1. Numeric
1. Numeric : integers & real numbers(fractional
numbers)

>>>num1=5 #integer number


>>>num2=2.5 #real number(float)
>>>num1
>>>num2
>>>5/2 (output:2) clash removes fractional part
>>>5.0/2 (output:2.5)
2. Strings
Strings

•Used to represent string- double quote/ single quote


>>>samplestring=“hello”
>>>samplestring
l Operations on string:
l Slice([] & [:]) : subset of string
Concatenation (+) :combine 2 or more strings
Repetition(*): repeat the same string several times
>>>samplestring+”world”
>>>samplestring*3
>>>samplestring
HelloWorld
>>>samplestring[1]
‘e’
>>>samplestring[0:2]
‘He’
>>>samplestring=“HelloWorld”
>>>Samplestring[1:8:2] #display all the alternate character
between index 1 to 8 i.e. 1,3,5,7
Output: ‘elwr’
Built-in String Methods Python

•It includes the following built – in methods to manipulate strings


•-In Python 3 , all strings are represented in Unicode. In Python 2
are stored internally as 8 bit ASCII, hence it is required to attach
'u' to make it Unicode.
1. capitalize()
Capitalizes first letter of string

txt = "hello, and welcome to my world."

x = txt.capitalize()

print (x)

Output:
Hello, and welcome to my world
2. casefold():Converts string into lower case

txt = "Hello, And Welcome To My World!“


x = txt.casefold()
print(x)

Output:
hello, and welcome to my world!
3. center():Returns a centered string

txt = ”spb"

x = txt.center(20)

print(x)

Output:
spb
4. count():Returns the number of times a specified value occurs
in a string

txt = “ A C Patil COE , ACP COE"

x = txt.count(“COE")

print(x)

Output:
2
5. endswith(): Returns true if the string ends with the specified
value

txt = "Hello world."

x = txt.endswith(".")

print(x)

Output:
True
6. expandtabs(): Sets the tab size of the string

txt = "A\tC\tP\tC\tO\tE"

x = txt.expandtabs(5)

print(x)

Output:
A C P C O E
7. find(): Searches the string for a specified value and returns
the position of where it was found.

txt = "Hello,coe to my coe."

x = txt.find("coe")

print(x)

Output:
6
l 10. isalnum()
l Returns true if string has at least 1 character and
all characters are alphanumeric and false otherwise.
l 11. isalpha()
l Returns true if string has at least 1 character and all
characters are alphabetic and false otherwise.
l 12. isdigit()
l Returns true if the string contains only digits and false
otherwise.
l 13. islower()
l Returns true if string has at least 1 cased character
and all cased characters are in lowercase and false
otherwise.
l 14.isspace()
l Returns true if string contains only whitespace
characters and false other wise.
l16. istitle()
lReturns true if string is properly "titlecased" and false

otherwise.
l17. isupper()

lReturns true if string has at least one cased character and

all cased characters are in uppercase and false otherwise.


l18. join(seq)

lMerges (concatenates) the string representations of

elements in sequence seq into a string, with separator


string.
l19. len(string)

lReturns the length of the string


l

l 20. lower()
l Converts all uppercase letters in string to lowercase.
l
l 24. max(str)
l Returns the max alphabetical character from the string
str.
l 25. min(str)
l Returns the min alphabetical character from the string
str.
l
l 36. title()
l Returns "titlecased" version of string, that is, all words begin
with uppercase and the rest are lowercase.

l 38. upper()
l Converts lowercase letters in string to uppercase.
List

•Contain the same/ different type of items


•A list is a ordered & indexable sequence
Definition: A list is a collection which is ordered and changeable. In Python
lists are written with square brackets.

•Declare list: we need to separates item in a list using


commas(,) and enclosed them within square bracket[].
•Similar to array in C (diff- array contains a same type of
values, list contains different types of values)
•List also has concatenation(+), repetition(*), & slicing[:]
operators
>>> mylist=[1,”two”,3.0,”four”]
>>>mylist1=[“five’,6]
>>>mylist
>>>mylist1
>>>mylist+mylist1
>>>mylist*2
>>>mylist[0:2]
List is a collection which is ordered and changeable. Allows duplicate
members.
Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
Set is a collection which is unordered and unindexed. No duplicate
members.
Dictionary is a collection which is unordered, changeable and indexed.
No duplicate members.
Create a List:

thislist = ["apple", "banana", "cherry"]


print(thislist)

Access Items
You access the list items by referring to the index number:

Print the second item of the list:


thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Negative Indexing
Negative indexing means beginning from the end, -1 refers
to the last item, -2 refers to the second last item etc.

Print the last item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and
where to end the range.

When specifying a range, the return value will be a new list with the
specified items.

Return the third, fourth, and fifth item:


thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

The search will start at index 2 (included) and end at index 5 (not
included).
By leaving out the start value, the range will start at the
first item:

Example
This example returns the items from the beginning to
"orange":

thislist = ["apple", "banana", "cherry", "orange", "kiwi",


"melon", "mango"]
print(thislist[:4])
By leaving out the end value, the range will go on to the
end of the list:

Example
This example returns the items from "cherry" and to the end:

thislist = ["apple", "banana", "cherry", "orange", "kiwi",


"melon", "mango"]
print(thislist[2:])
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of
the list:

Example
This example returns the items from index -4 (included) to index -1
(excluded)

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[-4:-1])
List Length
To determine how many items a list has, use the len()
function:

Example
Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))
Add Items
To add an item to the end of the list, use the append()
method:

Example
Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)
Example
Insert an item as the second position:

thislist = ["apple", "banana", "cherry"]


thislist.insert(1, "orange")
print(thislist)
print(thislist)

The pop() method removes the specified index, (or the last item if index is
not specified):

thislist = ["apple", "banana", "cherry"]


thislist.pop()
print(thislist)

The del keyword removes the specified index:

thislist = ["apple", "banana", "cherry"]


del thislist[0]
print(thislist)
thislist = ["apple", "banana", "cherry"]
del thislist

The clear() method empties the list:

thislist = ["apple", "banana", "cherry"]


thislist.clear()
print(thislist)
There are ways to make a copy, one way is to use the built-in List
method copy().

Example
Make a copy of a list with the copy() method:

thislist = ["apple", "banana", "cherry"]


mylist = thislist.copy()
print(mylist)
Example
Make a copy of a list with the list() method:

thislist = ["apple", "banana", "cherry"]


mylist = list(thislist)
print(mylist)
Join Two Lists
There are several ways to join, or concatenate, two or more
lists in Python.
One of the easiest ways are by using the + operator.
Example
Join two list:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
you can use the extend() method, which purpose is to add elements
from one list to another list:

Example
Use the extend() method to add list2 at the end of list1:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list1.extend(list2)
print(list1)

Return the number of times the value "cherry" appears in the fruits
list:

fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")
Tuple
•Also used to store sequence of items
•A tuple is a collection which is ordered and unchangeable.
•In Python tuples are written with round brackets.

•Items separated by commas, tuples are enclosed with


parenthesis()
•>>>mytuple=(7,”eight”,9,10.2)
•>>>mytuple
Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)
Access Tuple Items
You can access tuple items by referring to the index number,
inside square brackets:
Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Negative Indexing
Negative indexing means beginning from the end, -
1 refers to the last item, -2 refers to the second last
item etc.
Example
Print the last item of the tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple[-1])
Range of Indexes
You can specify a range of indexes by specifying where to
start and where to end the range.

When specifying a range, the return value will be a new tuple


with the specified items.
Example
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango")
print(thistuple[2:5])
Change Tuple Values
Once a tuple is created, you cannot change its values.
Tuples are unchangeable, or immutable as it also is called.

But there is a workaround. You can convert the tuple into a list, change
the list, and convert the list back into a tuple.
Example
Convert the tuple into a list to be able to change it:

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Tuple Length
To determine how many items a tuple has, use the len() method:

Example
Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))
Add Items
Once a tuple is created, you cannot add items to it. Tuples
are unchangeable.

Example
You cannot add items to a tuple:

thistuple = ("apple", "banana", "cherry")


thistuple[3] = "orange" # This will raise an error
print(thistuple)
Create Tuple With One Item
To create a tuple with only one item, you have add a comma after the
item, unless Python will not recognize the variable as a tuple.

Example
One item tuple, remember the commma:

thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Remove Items
Note: You cannot remove items in a tuple.

Tuples are unchangeable, so you cannot remove items from it, but you
can delete the tuple completely:

Example
The del keyword can delete the tuple completely:

thistuple = ("apple", "banana", "cherry")


del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)

Return the number of times the value 5 appears in the tuple:

thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)

x = thistuple.count(5)

print(x)
Difference between List & Tuple

l In list items are enclosed within [] bracket, wherein tuples,


items are enclosed within ().
l Lists are mutuable where tuples are immutable.
l Tuples are read only. Once the items are stored, the tuple
can not be modified.
>>> mylist=[1,2,3]
>>> mylist
[1, 2, 3]
>>> mytuple=(1,2,3)
>>> mytuple
(1, 2, 3)
>>> mylist[0]=["one"]
>>> mylist
[['one'], 2, 3]
>>> mytuple[0]=("one")
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
mytuple[0]=("one")
TypeError: 'tuple' object does not support item
assignment
Boolean

l If we want to store data in the form of 'yes' or 'No'.---


boolean
>>> a=True
>>> type(a)
<type 'bool'>

>>> x=False
>>> type(x)
<type 'bool'>
Dictionaries

l Its just like hash data type


l The order of elements in dictionaries is undefined.
l We can iterate over the following:
lThe keys
lThe values
lThe items(key value pairs)
l Unordered collection of key value pairs
l When we have large amount of data , the dictionary data
type is used.
l Keys and values can be of any type in a dictionary
l Items are enclosed with {} & separated by comma.
l A colon(:) is used to separate key from value.
l A key inside the [] is used for accessing the dictionary
items.
>>> mydict={1:"first",2:"two"}
>>> mydict
{1: 'first', 2: 'two'}
>>> mydict[3]="third"
>>> mydict
{1: 'first', 2: 'two', 3: 'third'}
>>> mydict.keys()
[1, 2, 3]
>>> mydict.values()
['first', 'two', 'third']
>>> mydict={1.2:"one"}
>>> mydict
{1.2: 'one'}
>>> {1.2: 'one'}
{1.2: 'one'}
>>> mydict[2.3]={"teo"}
>>> mydict
{2.3: set(['teo']), 1.2: 'one'}
>>> mydict[s]={"hello"}
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>
mydict[s]={"hello"}
NameError: name 's' is not defined
>>> mydict[2]={22}
>>> mydict
{2.3: set(['teo']), 2: set([22]), 1.2: 'one'}
Sets

l The lists & dictionaries are known as sequence or order


collection of data.
l Set: is an unordered collection of data
l Set does not contain any duplicate values or elements
Operations on sets:

l Union
l Intersection
l Difference
l Symmetric difference
l Union:
l Performed on 2 sets returns all elements from both the sets.
l Its performed by using | operator
>>>set1=set([1,2,3,4,5])
>>> set1
set([1, 2, 3, 4, 5])
>>> set2=set([2,3,4,5,6,7,8])
>>> set2
set([2, 3, 4, 5, 6, 7, 8])
>>> print set1
set([1, 2, 3, 4, 5])
>>> print set2
set([2, 3, 4, 5, 6, 7, 8])
>>> union=set1|set2
>>> union
Set([1, 2, 3, 4, 5, 6, 7, 8])
>>> print union
set([1, 2, 3, 4, 5, 6, 7, 8])
Intersection

l Its performed on 2 sets


l Returns all the elements which are common or in both the sets.
l Its performed by using & operator
>>> intersection=set1&set2
>>> intersection
Set([2, 3, 4, 5])
>>> print intersection
set([2, 3, 4, 5])
Difference
l its performed on 2 sets
l Returns all the elements which are present on set1 but not in
set2.
l Its performed by using – operator
>>> set1
set([1, 2, 3, 4, 5])
>>> set2
set([2, 3, 4, 5, 6, 7, 8])
>>> difference=set1-set2
>>> print difference
Symmetric difference

l its performed on 2 sets


l Returns the elements which are present in either set1 or set2
but not in both.
l Its performed by using ^ operator
>>> print set1
set([1, 2, 3, 4, 5])
>>> print set2
set([2, 3, 4, 5, 6, 7, 8])
>>> symdiff=set1^set2
>>> print symdiff
l Union:
l Performed on 2 sets returns all elements from both the sets.
l Its performed by using | operator
>>>set1=set([1,2,3,4,5])
>>> set1
set([1, 2, 3, 4, 5])
>>> set2=set([2,3,4,5,6,7,8])
>>> set2
set([2, 3, 4, 5, 6, 7, 8])

You might also like