2.fundamentals of Python
2.fundamentals of Python
Python
Variables in Python:
Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.
Memory
A=10
B=20.05 Memory
C=“Python”
Memory
In Python you don’t need to declare variables before using it, unlike other languages
like Java, C etc.
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module
or other object. An identifier starts with a letter A to Z or a to z or an underscore
(_) followed by zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within
identifiers. Python is a case sensitive programming language.
Thus, Manpower and manpower are two different identifiers in Python.
Reserved words
The list shows the Python keywords. and exec not
These are reserved words and you assert finally or
cannot use them as constant or break for pass
variable or any other identifier names. class from print
All the Python keywords contain continue global raise
lowercase letters only.
def if return
del import try
elif in while
else is with
except lambda yield
Assigning values to a variable:
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. Consider the below example:
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example −
You can also assign multiple objects to multiple variables. For example −
DATA STRUCTURE IN PYTHON
Data Types in Python:
Python supports various data types, these data types defines the operations
possible on the variables and the storage method.
Example:
>>> my_list=['p','r','o','g','r','a','m']
>>> print(my_list[2])
>>> n_list=["Happy",2,0,1,8]
>>> print(n_list[0][2])
>>> print(n_list[1][0])
>>> m_list=["Happy",[2,3]]
>>> print(m_list[1][1])
Accessing from list by negative indexing:
Example:
>>> my_list=[1,2,3,4,5]
>>> print(my_list[-1])
5
>>> print(my_list[-4])
2
Accessing from list by slice lists:
Example: >>> my_list=['p','r','o','g','r','a','m']
>>> print(my_list[2:5])
>>> print(my_list[:-5])
>>> print(my_list[5:])
>>> print(my_list[:])
p r o g r a m
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1
Changing elements in list:
Example:
>>> odd=[2,4,6,8]
>>> odd[0]=1
>>> print(odd)
[1, 4, 6, 8]
>>> odd[1:4]=[3,5,7]
>>> print(odd)
[1, 3, 5, 7]
append and extend function:
append() joins only one
>>> odd=[1,3,5,7]
element to the end of the list,
whereas extend() join as many >>> odd.append(9)
>>> print(odd)
[1, 3, 5, 7, 9]
>>> odd.extend([11,13])
>>> print(odd)
[1, 3, 5, 7, 9, 11, 13]
Mutation of the list
Python can also use “+” operator to combine lists.
The “*” operator repeats a list for the given number of times.
Python can insert one item at a desired location by using method insert().
Example:
>>> my_list=['p','r','o','g','r','a','m']
>>> print('p' in my_list)
True
>>> print('b' in my_list)
False
>>> print('c' not in my_list)
True
Functions of list:
Function Description
all() Returns True if all values are true
any() Returns True if any of the elements is true else returns False
len() Returns the length of the list
list() Convert an iterable(string, tuple, set, dic) into list
max() Returns the largest number
min() Returns the smallest number
sorted() Returns a new sorted list
sum() Returns the sum of all the elements in the list
3.Tuples:
A Tuple is a sequence of immutable Python objects. Tuples are sequences, just
like Lists. The differences between tuples and lists are:
• Tuples cannot be changed unlike lists
• Tuples use parentheses, whereas lists use square brackets. Consider the
example below:
Why use Tuples when we have Lists?
So the simple answer would be, Tuples are faster than Lists. If you’re defining a
constant set of values which you just want to iterate, then use Tuple instead of a
List.
All Tuple operations are similar to Lists, but you cannot update, delete or add an
element to a Tuple.
Accessing elements in a Tuple by indexing:
Example:
>>> my_tuple=('p','e','r','m’,’i’,'t')
>>> print(my_tuple [0]) Output:
>>> n_tuple=("mouse",[8,4,6],(1,2,3)) ‘p’
‘s’
>>> print(n_tuple [0][3])
Accessing elements in a Tuple by negative indexing:
Example:
>>> my_tuple=('p','e','r','m','i','t')
>>> print(my_tuple[-1])
t
Accessing Tuple by slicing:
Python can be able to use a range of elements in a tuple by means of the slicing
operator- colon “:”
Example:
>>> my_tuple=('p','e','r','m','i','t')
>>> print(my_tuple[1:4])
('e', 'r', 'm')
>>> print(my_tuple[:-4])
('p', 'e')
>>> print(my_tuple[3:])
('m', 'i', 't')
>>> print(my_tuple[:])
('p', 'e', 'r', 'm', 'i', 't')
Changing a Tuple
Example:
>>> my_tuple=(4,2,3,[6,5])
>>> my_tuple[3][0]=7
>>> print(my_tuple)
(4, 2, 3, [6, 5])
Deleting a Tuple:
Deleting a tuple wholly is possible using the keyword del.
Example:
>>> my_tuple=('p','e','r','m','i','t')
>>> del my_tuple
>>> my_tuple
NameError: name 'my_tuple' is not defined
Tuple methods:
Example:
>>> my_tuple=('b','a','n','a','n','a') Output:
>>> print(my_tuple.count('n')) 2
>>> print(my_tuple.index('a')) 1
print(String_name[Start:Stop]) Slicing
print(String_name[::-1]) Reverse a string
print(String_name.upper()) Convert the letters in a string to upper-case
print(String_name.lower()) Convert the letters in a string to lower-case
Accessing characters in a string
Example: >>> str="program"
>>> print(str[0])
>>> print(str[-1])
>>> print(str[1:5])
>>> print(str[:-2])
>>> print(str[-2:])
>>> print(str[:5])
>>> print(str[5:])
Deleting a string
>>> str="program"
>>> my_string[5]='a'
TypeError: 'str' object does not support item assignment
>>> my_string="Python"
>>> del my_string[1]
TypeError: 'str' object doesn't support item deletion
>>> del my_string
>>> my_string
NameError: name 'my_string' is not defined
Concatenation of two or more strings
>>> str1="Hello"
>>> str2="World!"
>>> print(str1+str2) #using +
HelloWorld!
>>> print(str1*3) #using *
HelloHelloHello
>>> print(str1+" "+str2)
Hello World!
String Membership Test
User can test if a sub string exist within a string or not, by means of the keyword
in.
>>> str="program"
>>> 'a' in str
True
>>> 'ge' in str
False
>>> 'am' not in str
False
String Formatting-Escape Sequence
#initialize a with {}
>>> a = {}
>>> print(type(a))
##OUTPUT: <class ‘dict’>
Example:
#removing elements from a set
>>> my_set = {1,3,4,5,6}
>>> my_set.discard(4)
>>> print(my_set)
>>> my_set.remove(6)
>>> print(my_set)
Let’s look at some Set operations:
Union:
Union of A and B is a set of all the elements from both sets.
Union is performed using | operator.
Consider the below example:
>>> A={1,2,3,4}
>>>B ={3,4,5,6}
>>> print(A|B)
>>> A.union(B)
>>> B.union(A)
Intersection:
Intersection of A and B is a set of elements that are common in both sets.
Intersection is performed using & operator.
Consider the example below:
>>> A={1,2,3,4}
>>>B ={3,4,5,6}
>>> print(A&B)
>>> A.intersection(B)
>>> B.intersection(A)
Difference:
Difference of A and B (A – B) is a set of elements that are only in A but not in B.
Similarly, B – A is a set of element in B but not in A.
Consider the example below:
>>> A={1,2,3,4}
>>>B ={3,4,5,6}
>>> print(A-B)
>>> A.difference(B)
>>> print(B-A)
>>> B.difference(A)
Symmetric Difference:
Symmetric Difference of A and B is a set of elements in both A and B except
those that are common in both. Symmetric difference is performed using ^
operator. Consider the example below:
>>> A={1,2,3,4}
>>>B ={3,4,5,6}
>>> print(A^B)
>>> A.symmetric_difference(B)
>>> B.symmetric_difference(A)
Other set operations– Set Membership Test
Here can be able to test if an item exist in a set or not, using keyword in.
Example:
#initialize my_set
>>> my_set= set(“apple”)
>>> print(‘a’ in my_set)
True
>>> print(‘p’ not in my_set)
False
6.Dictionary
Dictionaries contains the ‘Key Value’ pairs enclosed within curly braces and Keys
and values are separated with ‘:’.
Consider the below example:
Create a dictionary using curly braces{} or dict()
#empty dictionary
>>> my_dict={}
>>> my_dict = {1:’apple’, 2:’ball’}
>>>my_dict={‘name’:’Aadhitya’,1:[1,2,3,4]}
>>> my_dict =dict({1:’apple’,2:’ball’})
>>> my_dict =dict([(1:’apple’),(2:’ball’)])
Dictionary operations:
•Access elements from a dictionary:
•Our existing dictionary "Dict" does not have the name “Ruby"
•We use the method Dict.update to add Ruby to our existing dictionary
•Now run the code, it adds Ruby to our existing dictionary
Adding elements in a dictionary