Introduction to Python:
Python is a widely used general-purpose, high level programming language. It
was initially designed by Guido van Rossum in 1991 and developed by Python
Software Foundation. It was mainly developed for emphasis on code
readability, and its syntax allows programmers to express concepts in fewer
lines of code.
Python is a programming language that lets you work quickly and integrate
systems more efficiently.
There are two major Python versions- Python 2 and Python 3.
• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and
includes new features.
Why to use Python:
The following are the primary factors to use python in day-to-day life:
1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and
multiple inheritance.
2. Indentation
Indentation is one of the greatest feature in python
3. It’s free (open source)
Downloading python and installing python is free and easy
4. It’s Powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (e.g. Numeric, NumPy, sciPy)
Automatic memory management
5. It’s Portable
Python runs virtually every major platform used today
As long as you have a compaitable python interpreter installed, python
programs will run in exactly the same manner, irrespective of platform.
6. It’s easy to use and learn
No intermediate compile
Python Programs are compiled automatically to an intermediate form called
byte code, which the interpreter then reads.
This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages.
Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language Python is processed at runtime by python Interpreter
8. Interactive Programming Language Users can interact with the python
interpreter directly for writing the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward which also
makes it popular.
Data types:
The data stored in memory can be of many types. For example, a student roll
number is stored as a numeric value and his or her address is stored as
alphanumeric characters.
Python has various standard data types that are used to define the operations
possible on them and the storage method for each of them.
Int:
Int, or integer, is a whole number, positive or negative,without decimals, of
umlimited length.
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
2
>>> a=10
>>> print(a)
10
# To verify the type of any object in Python, use the type()
function:
>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>
Float:
Float, or "floating point number" is a number, positive or negative, containing
one or more decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8
>>> y
2.8
>>> y=2.8
>>> print(type(y))
<class 'float'>
>>> type(.4)
<class 'float'>
>>> 2.
2.0
Example:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
String:
1. Strings in Python are identified as a contiguous set of characters represented
in the quotation marks. Python allows for either pairs of single or double
quotes.
• 'hello' is the same as "hello".
• Strings can be output to screen using the print function.
For example: print("hello").
>>> print("RGUKT college")
RGUKT college
>>> type("RGUKT college")
<class 'str'>
>>> print('RGUKT college')
RGUKT college
>>> " "
''
If you want to include either type of quote character within the string, the
simplest way is to delimit the string with the other type. If a string is to contain
a single quote, delimit it with double quotes and vice versa:
>>> print("RGUKT is a (') university")
RGUKT is a (') university
>>> print('RGUKT is a (') university')
RGUKT is a (') university
List:
It is a general purpose most widely used in data structures
List is a collection which is ordered and changeable and allows duplicate
members.
(Grow and shrink as needed, sequence type, sortable).
To use a list, you must declare it first. Do this using square brackets and
separate
values with commas.
We can construct / create list in many ways.
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
>>> x=list()
>>> x
[]
--------------------------
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
Variables:
Variables are nothing but reserved memory locations to store values. This
means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables,you can store integers, decimals or characters in
these variables.
Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9,
and _ )
• Variable names are case-sensitive (age, Age and AGE are three different
variables)
Assigning Values to Variables:
Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The
equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable.
For example −
a= 100
# An integer assignment
b = 1000.0
c = "John"
# A floating point
# A string
print (a)
print (b)
print (c)
This produces the following result −
100
1000.0
John
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously.
For example :
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are
assigned to the same memory location. You can also assign multiple objects to
multiple variables.
For example −
a,b,c = 1,2,"john“
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively,
and one string object with the value "john" is assigned to the variable c.
Output Variables:
The Python print statement is often used to output variables.
Variables do not need to be declared with any particular type and can even
change type after they have been set.
x=5
x = "RGUKT"
print(x)
# x is of type int
# x is now of type str
Output: RGUKT
To combine both text and a variable, Python uses the “+” character:
Example
x = "awesome"
print("Python is " + x)
Output
Python is awesome
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z=x+y
print(z)
Output:
Python is awesome
Expressions:
An expression is a combination of values, variables, and operators. An
expression is evaluated using assignment operator.
Examples: Y=x + 17
>>> x=10
>>> z=x+20
>>> z
30
>>> x=10
>>> y=20
>>> c=x+y
>>> c
30
A value all by itself is a simple expression, and so is a variable.
>>> y=20
>>> y
20
Python also defines expressions only contain identifiers, literals, and operators.
So,
Identifiers: Any name that is used to define a class, function, variable
module, or object is an identifier.
Literals: These are language-independent terms in Python and should exist
independently in any programming language. In Python, there are the string
literals, byte literals, integer literals, floating point literals, and imaginary
literals.
Operators: In Python you can implement the following operations using the
corresponding tokens.
OPERATOR TOKEN
add +
subtract -
multiply *
Integer Division /
remainder %
Binary left shift <<
Binary right shift >>
and &
or |
Less than <
Greater than >
Less than or equal to <=
Greater than or equal to >=
Cheak equality =
Conditional (if):
The if statement contains a logical expression using which data is compared and
a decision is made based on the result of the comparison.
Syntax:
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s)
inside the if statement is executed. If boolean expression evaluates to FALSE,
then the first set of code after the end of the if statement(s) is executed.
if statement flowchart:
Fig: Operation of if statement
Example: Python if Statement
a=3
if a > 2:
print(a, "is greater")
print("done")
a = -1
if a < 0:
print(a, "a is smaller")
print("Finish")
Output:
3 is greater
done
-1 a is smaller
Finish
--------------------------------
a=10
if a>9:
print("A is Greater than 9")
Output:
A is Greater than 9
Alternative if (If-Else):
An else statement can be combined with an if statement. An else statement
contains the block of code (false block) that executes if the conditional expression in
the if statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else
Statement following if.
Syntax of if - else :
if test expression:
Body of if stmts
else:
Body of else stmts
Flowchart of if – elif – else:
Example of if - elif – else:
a=int(input('enter the number'))
b=int(input('enter the number'))
c=int(input('enter the number'))
if a>b:
print("a is greater")
elif b>c:
print("b is greater")
else:
print("c is greater")
Output:
enter the number5
enter the number2
enter the number9
a is greater
>>>
enter the number2
enter the number5
enter the number9
c is greater
Iteration:
A loop statement allows us to execute a statement or group of statements
multiple times as long as the condition is true. Repeated execution of a set of
statements with the help of loops is called iteration.
Loops statements are used when we need to run same code again and again,
each time with a different value.
Statements:
In Python Iteration (Loops) statements are of three types:
1. While Loop
2. For Loop
3. Nested For Loops
While loop:
Loops are either infinite or conditional. Python while loop keeps reiterating a
block of code defined inside it until the desired condition is met.
The while loop contains a boolean expression and the code inside the loop is
repeatedly executed as long as the boolean expression is true.
The statements that are executed inside while can be a single line of code or
a block of multiple statements.
Syntax:
while(expression):
Statement(s)
Example Programs:
1. --------------------------------------
i=1
while i<=6:
print("Rgukt")
i=i+1
output:
rgukt
rgukt
rgukt
rgukt
rgukt
rgukt
2.
-----------------------------------------------------
i=1
while i<=3:
print("RGUKT",end=" ")
j=1
while j<=1:
print("CSE DEPT",end="")
j=j+1
i=i+1
print()
Output:
RGUKT CSE DEPT
RGUKT CSE DEPT
RGUKT CSE DEPT
For loop:
Python for loop is used for repeated execution of a group of statements for the
desired number of times. It iterates over the items of lists, tuples, strings, the
dictionaries and other iterable objects
Syntax: for var in sequence:
Statement(s)
Sample Program:
numbers = [1, 2, 4, 6, 11, 20]
seq=0
for val in numbers:
seq=val*val
print(seq)
Output:
1
4
16
36
121
400
Iterating over a list:
#list of items
list = ['R','G','U,'K','T']
i=1
#Iterating over the list
for item in list:
print ('college ',i,' is ',item)
i = i+1
Output:
college 1 is R
college 2 is G
college 3 is U
college 4 is K
college 5 is T
Iterating over a Tuple:
tuple = (2,3,5,7)
print ('These are the first four prime numbers ')
#Iterating over the tuple
for a in tuple:
print (a)
Output:
These are the first four prime numbers
2
3
5
7
Iterating over a dictionary:
#creating a dictionary
college = {"ces":"block1","it":"block2","ece":"block3"}
#Iterating over the dictionary to print keys
print ('Keys are:')
for keys in college:
print (keys)
#Iterating over the dictionary to print values
print ('Values are:')
for blocks in [Link]():
print(blocks)
Output:
Keys are:
ces
it
ece
Values are:
block1
block2
block3
Iterating over a String:
#declare a string to iterate over
college = 'RGUKT'
#Iterating over the string
for name in college:
print (name)
Output:
R
G
U
K
T
Nested For loop:
When one Loop defined within another Loop is called Nested Loops.
Syntax:
for val in sequence:
for val in sequence:
statements
statements
# Example of Nested For Loops
for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')
Output:
1
22
333
4444
55555
--------------------------
Strings:
A string is a group a sequence of characters. Since Python has no provision for
arrays,we simply use strings. This is how we declare a string. We can use a pair
of single or double quotes. Every string object is of the type ‘str’.
>>> type("name")
<class 'str'>
>>> name=str()
>>> name
''
>>> a=str('rgukt')
>>> a
'rgukt'
>>> a=str(rgukt)
>>> a[2]
'u'
>>> fruit = 'banana'
>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to
letter. The
expression in brackets is called an index. The index indicates which character in
the sequence we want
String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a
character:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the string and working their way from -1 at the
end.
Slice out substrings, sub lists, sub Tuples using index.
Syntax: [Start: stop: steps]
• Slicing will start from index and will go up to stop in step of steps.
• Default value of start is 0,
• Stop is last index of list
• And for step default is 1
For example 1−
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character print
str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[Link]
'opt'
>>> x[3:]
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'
String functions and methods:
There are many methods to operate on String.
Note:
All the string methods will be returning either true or false as the result
1. isalnum():
Isalnum() method returns true if string has at least 1 character and all characters
are alphanumeric and false otherwise.
Syntax:
[Link]()
Example:
>>> string="123alpha"
>>> [Link]() True
2. isalpha():
isalpha() method returns true if string has at least 1 character and all characters
are alphabetic and false otherwise.
Syntax:
[Link]()
Example:
>>> string="nikhil"
>>> [Link]()
True
3. isdigit():
isdigit() returns true if string contains only digits and false otherwise.
Syntax:
[Link]()
Example:
>>> string="123456789"
>>> [Link]()
True
4. islower():
Islower() returns true if string has characters that are in lowercase and false
otherwise.
Syntax:
[Link]()
Example:
>>> string="nikhil"
>>> [Link]()
True
5. isnumeric():
isnumeric() method returns true if a string contains only numeric characters and
false otherwise.
Syntax:
[Link]()
Example:
>>> string="123456789"
>>> [Link]()
True
6. isspace():
isspace() returns true if string contains only whitespace characters and false
otherwise.
Syntax:
[Link]()
Example:
>>> string=" "
>>> [Link]()
True
7. istitle()
istitle() method returns true if string is properly “titlecased”(starting letter of
each word is capital) and false otherwise
Syntax:
[Link]()
Example:
>>> string="Nikhil Is Learning"
>>> [Link]()
True
8. isupper()
isupper() returns true if string has characters that are in uppercase and false
otherwise.
Syntax:
[Link]()
Example:
>>> string="HELLO"
>>> [Link]()
True
9. replace()
replace() method replaces all occurrences of old in string with new or at most
max occurrences if max given.
Syntax:
[Link]()
Example:
>>> string="Nikhil Is Learning"
>>> [Link]('Nikhil','Neha')
'Neha Is Learning'
10. split()
split() method splits the string according to delimiter str (space if not provided)
Syntax:
[Link]()
Example:
>>> string="Nikhil Is Learning"
>>> [Link]()
['Nikhil', 'Is', 'Learning']
11. count()
count() method counts the occurrence of a string in another string Syntax:
[Link]()
Example:
>>> string='Nikhil Is Learning'
>>> [Link]('i')
3
12. find()
Find() method is used for finding the index of the first occurrence of a string in
another string
Syntax:
[Link](„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> [Link]('k')
2
13. swapcase()
converts lowercase letters in a string to uppercase and viceversa
Syntax:
[Link](„string‟)
Example:
>>> string="HELLO"
>>> [Link]()
'hello'
14. startswith()
Determines if string or a substring of string (if starting index beg and ending
index end are given) starts with substring str; returns true if so and false
otherwise.
Syntax:
[Link](„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> [Link]('N')
True
15. endswith()
Determines if string or a substring of string (if starting index beg and ending
index end are given) ends with substring str; returns true if so and false
otherwise.
Syntax:
[Link](„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> [Link]('g')
True
String module:
This module contains a number of functions to process standard Python strings.
In recent versions, most functions are available as string methods as well.
It’s a built-in module and we have to import it before using any of its constants
and classes
Syntax: import string
Note:
help(string) --- gives the information about all the variables ,functions,
attributes and classes
to be used in string module.
Example:
import string
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print([Link])
print([Link])
#print([Link])
print([Link])
Output:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Lists, Tuples, Dictionaries:
List:
It is a general purpose most widely used in data structures
List is a collection which is ordered and changeable and allows duplicate
members.
(Grow and shrink as needed, sequence type, sortable).
To use a list, you must declare it first. Do this using square brackets and
separate
values with commas.
We can construct / create list in many ways.
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
----------------------
>>> x=list()
>>> x
[]
--------------------------
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
List operations:
These operations include indexing, slicing, adding, multiplying, and checking
for membership
List slices:
>>> list1=range(1,6)
>>> list1
range(1, 6)
>>> print(list1)
range(1, 6)
>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list1[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[:1]
[1]
>>> list1[2:5]
[3, 4, 5]
>>> list1[:6]
[1, 2, 3, 4, 5, 6]
>>> list1[Link]
[2]
>>> list1[Link]
[2, 4, 6, 8]
List methods:
The list data type has some more methods. Here are all of the methods of list
objects:
• Del()
• Append()
• Extend()
• Insert()
• Pop()
• Remove()
• Reverse()
• Sort()
Delete: Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1])
#deletes the index position 1 in a list
>>> x
[5, 8, 6]
------------
>>> del(x)
>>> x
# complete list gets deleted
Append: Append an item to a list
>>> x=[1,5,8,4]
>>> [Link](10)
>>> x
[1, 5, 8, 4, 10]
Extend: Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> [Link](y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]
Insert: To add an item at the specified index, use the insert () method:
>>> x=[1,2,4,6,7]
>>> [Link](2,10) #insert(index no, item to be inserted)
>>> x
[1, 2, 10, 4, 6, 7]
-------------------------
>>> [Link](4,['a',11])
>>> x
[1, 2, 10, 4, ['a', 11], 6, 7]
Pop: The pop() method removes the specified index, (or the last item if index is
not
specified) or simply pops the last item of list and returns the item.
>>> x=[1, 2, 10, 4, 6, 7]
>>> [Link]()
7
>>> x
[1, 2, 10, 4, 6]
-----------------------------------
>>> x=[1, 2, 10, 4, 6]
>>> [Link](2)
10
>>> x
[1, 2, 4, 6]
Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> [Link](33)
>>> x
[1, 2, 10, 6]
Reverse: Reverse the order of a given list.
>>> x=[1,2,3,4,5,6,7]
>>> [Link]()
>>> x
[7, 6, 5, 4, 3, 2, 1]
Sort: Sorts the elements in ascending order
>>> x=[7, 6, 5, 4, 3, 2, 1]
>>> [Link]()
>>> x
[1, 2, 3, 4, 5, 6, 7]
-----------------------
>>> x=[10,1,5,3,8,7]
>>> [Link]()
>>> x
[1, 3, 5, 7, 8, 10]
List comprehension:
List comprehensions provide a concise way to create lists. Common
applications are to make new lists where each element is the result of some
operations applied to each member of another sequence or iterable, or to create
a subsequence of those elements that satisfy a certain condition.
For example, assume we want to create a list of squares, like:
>>> list1=[]
>>> for x in range(10):
[Link](x**2)
>>> list1
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
(or)
This is also equivalent to
>>> list1=list(map(lambda x:x**2, range(10)))
>>> list1
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
(or)
Which is more concise and redable.
>>> list1=[x**2 for x in range(10)]
>>> list1
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Similarily some examples:
>>> x=[m for m in range(8)]
>>> print(x)
[0, 1, 2, 3, 4, 5, 6, 7]
>>> x=[z**2 for z in range(10) if z>4]
>>> print(x)
[25, 36, 49, 64, 81]
>>> x=[x ** 2 for x in range (1, 11) if x % 2 == 1]
>>> print(x)
[1, 9, 25, 49, 81]
>>> a=5
>>> table = [[a, b, a * b] for b in range(1, 11)]
>>> for i in table:
print(i)
[5, 1, 5]
[5, 2, 10]
[5, 3, 15]
[5, 4, 20]
[5, 5, 25]
[5, 6, 30]
[5, 7, 35]
[5, 8, 40]
[5, 9, 45]
[5, 10, 50]
Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.
• Supports all operations for sequences.
• Immutable, but member objects may be mutable.
• If the contents of a list shouldn’t change, use a tuple to prevent items from
accidently being added, changed, or deleted.
• Tuples are more efficient than list due to python’s implementation.
We can construct tuple in many ways:
X=() #no item tuple
X=(1,2,3)
X=tuple(list1)
X=1,2,3,4
Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x
(1, 2, 3)
-----------------------
>>> x=()
>>> x
()
----------------------------
>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)
-----------------------------
>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)
Some of the operations of tuple are:
• Access tuple items
• Change tuple items
• Loop through a tuple
• Count()
• Index()
• Length()
Access tuple items: Access tuple items by referring to the index number, inside
square
brackets
>>> x=('a','b','c','g')
>>> print(x[2])
c
Change tuple items: Once a tuple is created, you cannot change its values.
Tuples are unchangeable.
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same
Loop through a tuple: We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)
4
5
6
7
2
aa
Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> [Link](2)
4
Index (): Searches the tuple for a specified value and returns the position of
where it was found
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> [Link](2)
1
(Or)
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=[Link](2)
>>> print(y)
1
Length (): To know the number of items or values present in a tuple, we use
len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
12
Tuple comprehension:
Tuple Comprehensions are special: The result of a tuple comprehension is
special. You might expect it to produce a tuple, but what it does is produce a
special "generator" object that we can iterate over.
For example:
>>> x = (i for i in 'abc') #tuple comprehension
>>> x
<generator object <genexpr> at 0x033EEC30>
>>> print(x)
<generator object <genexpr> at 0x033EEC30>
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object
<genexpr>
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is
actually a generator. The only thing that you need to know now about a
generator now is that youcan iterate over it, but ONLY ONCE.
So, given the code
>>> x = (i for i in 'abc')
>>> for i in x:
print(i)
a
b
c
Set:
Similarly to list comprehensions, set comprehensions are also supported:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
>>> x={3*x for x in range(10) if x>5}
>>> x
{24, 18, 27, 21}
Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In
Python dictionaries are written with curly brackets, and they have keys and
values.
Key-value pairs
Unordered
We can construct or create dictionary like:
X={1:’A’,2:’B’,3:’c’}
X=dict([(‘a’,3) (‘b’,4)]
X=dict(‘A’=1,’B’ =2)
Example:
>>> dict1 = {"brand":"rgukt","model":"university","year":2004}
>>> dict1
{'brand': 'rgukt', 'model': 'university', 'year': 2004}
Below are some dictionary operations:
To access keys and values and items of dictionary:
>>> dict1 = {"brand":"rgukt","model":"university","year":2004}
>>> [Link]()
dict_keys(['brand', 'model', 'year'])
>>> [Link]()
dict_values(['rgukt', 'university’, 2004])
>>> [Link]()
dict_items([('brand', 'rgukt'), ('model', 'university'), ('year', 2004)])
-----------------------------------------------
>>> for items in [Link]():
print(items)
rgukt
university
2004
>>> for items in [Link]():
print(items)
brand
model
year
>>> for i in [Link]():
print(i)
('brand', 'rgukt')
('model', 'university')
('year', 2004)
Some more operations like:
Add/change
Remove
Length
Delete
Add/change values: You can change the value of a specific item by referring to
its key name
>>> dict1 = {"brand":"rgukt","model":"university","year":2004}
>>> dict1["year"]=2005
>>> dict1
{'brand': 'rgukt', 'model': 'university', 'year': 2005}
Remove(): It removes or pop the specific item of dictionary.
>>> dict1 = {"brand":"rgukt","model":"university","year":2004}
>>> print([Link]("model"))
university
>>> dict1
{'brand': 'rgukt', 'year': 2005}
Delete: Deletes a particular item.
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> del x[5]
>>> x
Length: we use len() method to get the length of dictionary.
>>>{1: 1, 2: 4, 3: 9, 4: 16}
{1: 1, 2: 4, 3: 9, 4: 16}
>>> y=len(x)
>>> y
4 Iterating over (key, value) pairs:
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> for key in x:
print(key, x[key])
11
24
39
4 16
5 25
>>> for k,v in [Link]():
print(k,v)
11
24
39
4 16
5 25
Comprehension:
Dictionary comprehensions can be used to create dictionaries from arbitrary key
and value expressions:
>>> z={x: x**2 for x in (2,4,6)}
>>> z
{2: 4, 4: 16, 6: 36}
>>> dict11 = {x: x*x for x in range(6)}
>>> dict11
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Python Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function to
print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Arguments are often shortened to args in Python documentations.
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information
that are passed into a function.
From a function's perspective:A parameter is the variable listed inside the
parentheses in the function [Link] argument is the value that is sent to the
function when it is called.
Classes and Objects in Python
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the keyword class:
Example
Create a class named MyClass, with a property named x:
class MyClass:
x = 5
output:<class '__main__.MyClass'>
Create Object
Now we can use the class named MyClass to create objects:
Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
OUTPUT: 5
The __init__() Function
The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.
To understand the meaning of classes we have to understand the built-in __init__()
function.
All classes have a function called __init__(), which is always executed when the
class is being initiated.
Use the __init__() function to assign values to object properties, or other operations
that are necessary to do when the object is being created:
Example
Create a class named Person, use the __init__() function to assign values for name
and age:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
p1 = Person("John", 36)
print([Link])
print([Link]
Note: The __init__()
OUTPUT :John
36
The __str__() Function
The __str__() function controls what should be returned when the class object is
represented as a string.
If the __str__() function is not set, the string representation of the object is
returned:
Example
The string representation of an object WITHOUT the __str__() function:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
p1 = Person("John", 36)
print(p1)
OUTPUT:<__main__.Person object at 0x15039e602100>
Example
The string representation of an object WITH the __str__() function:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def __str__(self):
return f"{[Link]}({[Link]})"
p1 = Person("John", 36)
print(p1)
OUTPUT:john(36)
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to
the object.
Let us create a method in the Person class:
Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
[Link]()
OUTPUT:Hello my name is John
Note: The self parameter is a reference to the current instance of the class, and is
used to access variables that belong to the class.
The self Parameter
The self parameter is a reference to the current instance of the class, and is used
to access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to
be the first parameter of any function in the class:
Example
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
[Link] = name
[Link] = age
def myfunc(abc):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
[Link]()
OUTPUT:Hello my name is John
Modify Object Properties
You can modify properties on objects like this:
Example
Set the age of p1 to 40:
[Link] = 40
OUTPUT:40
Delete Object Properties
You can delete properties on objects by using the del keyword:
Example
Delete the age property from the p1 object:
del [Link]
Delete Objects
You can delete objects by using the del keyword:
Example
Delete the p1 object:
del p1
The pass Statement
class definitions cannot be empty, but if you for some reason have
a class definition with no content, put in the pass statement to avoid getting an
error.
Example
class Person:
pass
function is called automatically every time the class is being used to create a
new object.
[Link] = age
p1 = Person("John", 36)
print(p1)
THE END