You are on page 1of 64

Fundamentals of

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.

Numeric List Tuple String Set Dictionary


1.Numeric:
Just as expected Numeric data types store numeric values. They are immutable data
types, this means that you cannot change it’s value. Python supports three different
Numeric data types:
Integer type: It holds all the integer values i.e. all the positive and negative whole
numbers, example – 10.
Float type: It holds the real numbers and are represented by decimal and
sometimes even scientific notations with E or e indicating the power of 10 (2.5e2 =
2.5 x 102 = 250), example – 10.24.
Complex type: These are of the form a + bj, where a and b are floats and J
represents the square root of -1 (which is an imaginary number), example – 10+6j.
Now you can even perform type conversion. For example, you can convert the
integer value to a float value and vice-versa. Consider the example below:

Similarly you can convert a float value to integer type:


2.List:
List is the most versatile datatype available in Python which can be written as a
list of comma-separated values (items) between square brackets (you can store
elements of different types). Consider the example below:
Let’s look at few operations that you can perform with Lists:
Syntax Result Description
List[0] Python This will give the index 0 value
from the List.
List[0:2] Python,3.7 This will give the index values
from 0 to 2, but it won’t include
index 2 from the List.
List[2]=“Hello” [‘Python’, 3.7, ‘Hello’] It will update the List and replace
at index 2.
del List[2] [‘Python’,3.7] This will delete index 2 value.
len(List) 3 This will return the length of the
List.
List*2 [‘Python’, 3.7, 2, ‘Python’, 3.7, 2] This will repeat the List twice.
List[::-1] [2, 3.7, ’Python’] This will reverse the List.
Accessing from list by index value:

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: >>> odd=[1,9]


>>> odd.insert(1,3)
>>> odd=[1,3,5] >>> print(odd)
>>> print(odd+[9,7,5]) [1, 3, 9]
[1, 3, 5, 9, 7, 5] >>> odd[2:2]=[5,7]
>>> print(["re"]*3) >>> print(odd)
['re', 're', 're'] [1, 3, 5, 7, 9]
Deleting elements from list:
Python can delete one or more items from a list using the keyword del. It can
even delete the list entirely.
Example: >>> my_list=['p','r','o','b','l','e','m']
>>> del my_list[2]
>>> print(my_list)
['p', 'r', 'b', 'l', 'e', 'm']
>>> del my_list[1:5]
>>> print(my_list)
['p', 'm']
>>> del my_list
>>> print(my_list)
remove(), pop() and clear()
Example: >>> print(my_list.pop(1))
o
>>> my_list=['p','r','o','g','r','a','m'] >>> print(my_list)
['r', 'g', 'r', 'a', 'm']
>>> my_list.remove('p')
>>> print(my_list.pop())
>>> print(my_list) m
['r', 'o', 'g', 'r', 'a', 'm'] >>> print(my_list)
['r', 'g', 'r', 'a']
>>> my_list.clear()
>>> print(my_list)
[]
Methods of list:
Example:
>>> my_list=[3,8,1,6] index(): returns the index of
the item
>>> print(my_list.index(8)) count(): returns the number
of times the item is
>>> print(my_list.count(8)) repeated in the list
>>> print(my_list.sort()) sort(): returns the sorted list
reverse(): returns the
>>> print(my_list.reverse()) reverse of the list
Other list operations:
Python can be able to test if an item exists in a list or not, using the keyword “in”.

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

Tuple membership test- using “in” keyword


Output:
>>> print('a' in my_tuple)
True
>>> print('n' not in my_tuple)
False
4.Strings:
Strings can be created simply by enclosing characters in quotes. Python treats
single and double quotes in exactly the same fashion. Consider the example
below:
Let’s look at few operations that you can perform with Strings.
Syntax Operation
print(len(String_name)) String length
print(String_name.index(“char”)) Locate a char in string
print(String_name.count(“char”)) Count the number of times a char is repeated in a
string

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

>>> print(“He said, “Hye!"")


SyntaxError: invalid syntax
>>> print("He said,'Hye!'") #similarly using triple quotes
>>> print('He said, "What's this?”’)
SyntaxError: invalid syntax
>>> print('He said, "what\'s this?"') #escaping using \
>>> print("He said, \"What's this?\"")
The format() method for formatting strings
#default(implicit) order
>>> default_order="{},{} and {}".format(‘C++’,’JAVA’,’PYTHON’)
>>> print(default_order)
#order using positional arguments
>>> positional_order=“{1},{0}and {2}”.format(‘C++’,’JAVA’,’PYTHON’)
>>>print(positional_order)
#order using keyword arguments
>>>keyword_order=“{s},{b} and {j}”.format(j=‘JAVA’,s=‘C++’,b=‘PYTHON’)
>>>print(keyword_order)
5.Set:
•A Set is an unordered collection of items. Every element is unique and has to be
immutable.
•A Set is created by placing all the items (elements) inside curly braces {},
separated by comma. Consider the example below:

In Sets, every element has to be unique.


Note: it is unordered
collection thus when
values are inserted
randomly, default sorting
is done.
Examples:
#set of mixed datatypes
>>> my_set = {1.0,”Hello”,(1,2,3)}

#we can have a mutable list in a set


>>> my_set = {1,2,[3,4]}

#we can make set from a list


>>> my_set = set([1,2,3,4])
Create an empty set
Example:

#initialize a with {}
>>> a = {}
>>> print(type(a))
##OUTPUT: <class ‘dict’>

#initialize a with set()


>>> a= set()
>>> print(type(a))
##OUTPUT: <class ‘set’>
Changing a set
Example:
#initialize my_set
>>> my_set = {1,3}
>>> print(my_set)
>>> my_set.add(2)
>>> print(my_set)
>>> my_set.update([2,3,4])
>>> print(my_set) Note: it adds and
>>>my_set.update([4,5],{1,6,8}) updates according to
>>> print(my_set) numeric order
Removing elements from a set

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:

>>> my_dict = {“Name” : ”Peter” , ”Location” : ”England”}


>>> my_dict[“Name”]
>>> my_dict.get(“Name”)

•Changing elements in a Dictionary:

>>> my_dict = {“Name” : ”Peter” , ”Location” : ”England”}


>>> my_dict[“Name“] = "Peterson”
>>> my_dict
{Name : Peterson, Location: England}
Update elements in Dictionary
You can also update a dictionary by adding a new entry with a key-value
to an existing. Here in the example we will add another programming
language “Ruby" to our existing dictionary.
Dict = {1: “Python”,2: “Java”, 3: “C++”}
Dict.update({4: “Ruby”})
print(Dict)

•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

>>> my_dict = {“Name” : ”Peter” , ”Location” : ”England”}


>>> my_dict[“Age”] = 10
>>> my_dict
{'Name': 'Peter', 'Location': 'England', 'Age': 10}
Delete or remove elements from a dictionary
>>> squares = {1:1,2:4,3:9,4:16,5:25}
>>> squares.pop(4) ##OUTPUT: 16
>>> squares.popitem() ##OUTPUT: (5,25)
>>> del squares[2]
>>> print(squares) ##OUTPUT: {1:1,3:9}
>>> squares.clear()
>>> print(squares) ##OUTPUT: { }
>>> del squares ##OUTPUT:
>>> print(squares) NameError: name 'squares' is not defined
Other dictionary operations– Dictionary Membership Test
Here can test if a key is in a dictionary or not by the keyword in.
Example:
>>> squares={1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
>>> print(1 in squares)
True
>>> print(2 not in squares)
False
>>> print(49 in squares)
False
Functions with dictionary
Function Description
all() Return True if all keys of the dictionary are true.
any() Return True if any key of the dictionary is true. If the dictionary is
empty, return False.

len() Return the length in the dictionary.


sorted() Return a new sorted list of keys in the dictionary.
OPERATORS IN PYTHON
Basic Operators
Python language supports the following types of operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Membership Operators
• Identity Operators
1. Arithmetic Operators
Operator Description
+ Addition Adds values on either side of the operator.
- Subtraction Subtracts right hand operand from left hand operand.
* Multiplication Multiplies values on either side of the operator
/ Division Divides left hand operand by right hand operand
% Modulus Divides left hand operand by right hand operand and returns
remainder
** Exponent Performs exponential (power) calculation on operators
// Floor Division - The division of operands where the result is the
quotient in which the digits after the decimal point are removed.
But if one of the operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity) −
2. Comparison Operators
Operator Description Example
== If the values of two operands are equal, then the (a == b) is not true.
condition becomes true.
!= If values of two operands are not equal, then condition (a != b) is true.
becomes true.
<> If values of two operands are not equal, then condition (a <> b) is true. This is similar to != operator.
becomes true.
> If the value of left operand is greater than the value of (a > b) is not true.
right operand, then condition becomes true.
< If the value of left operand is less than the value of right (a < b) is true.
operand, then condition becomes true.
>= If the value of left operand is greater than or equal to (a >= b) is not true.
the value of right operand, then condition becomes
true.
<= If the value of left operand is less than or equal to the (a <= b) is true.
value of right operand, then condition becomes true.
3. Assignment Operators
Operator Description Example
= Assigns values from right side operands to left
c = a + b assigns value of a + b into c
side operand
+= Add AND It adds right operand to the left operand and
c += a is equivalent to c = c + a
assign the result to left operand
-= Subtract It subtracts right operand from the left operand
c -= a is equivalent to c = c - a
AND and assign the result to left operand
*= Multiply It multiplies right operand with the left operand
c *= a is equivalent to c = c * a
AND and assign the result to left operand
/= Divide AND It divides left operand with the right operand and c /= a is equivalent to c = c / ac /= a is
assign the result to left operand equivalent to c = c / a
%= Modulus It takes modulus using two operands and assign
c %= a is equivalent to c = c % a
AND the result to left operand
**= Exponent Performs exponential (power) calculation on
c **= a is equivalent to c = c ** a
AND operators and assign value to the left operand
//= Floor It performs floor division on operators and assign
c //= a is equivalent to c = c // a
Division value to the left operand
4. Logical Operators

Assume variable a holds 10 and variable b holds 20 then −

Operator Description Example


and Logical If both the operands are true then (a and b) is true.
AND condition becomes true.
or Logical If any of the two operands are non- (a or b) is true.
OR zero then condition becomes true.
not Logical Used to reverse the logical state of Not(a and b) is false.
NOT its operand.
5. Membership Operators
Python’s membership operators test for membership in a sequence, such as
strings, lists, or tuples. There are two membership operators as explained below −

Operator Description Example


in Evaluates to true if it finds a
x in y, here in results in a 1 if x
variable in the specified sequence
is a member of sequence y.
and false otherwise.
not in Evaluates to true if it does not x not in y, here not in results in
finds a variable in the specified a 1 if x is not a member of
sequence and false otherwise. sequence y.
6. Identity Operators
Identity operators compare the memory locations of two objects. There are two
Identity operators explained below −
Operator Description Example
is Evaluates to true if the variables on
either side of the operator point to x is y, here is results in 1 if id(x)
the same object and false equals id(y).
otherwise.
is not Evaluates to false if the variables
on either side of the operator x is not y, here is not results in
point to the same object and true 1 if id(x) is not equal to id(y).
otherwise.

You might also like