Introduction To Python
Introduction To Python
Object is simply a collection of data (variables) and methods (functions) that act on those
data. And, class is a blueprint for the object.
We can think of class as a sketch (prototype) of a house. It contains all the details about the
floors, doors, windows etc. Based on these descriptions we build the house. House is the
object.
As, many houses can be made from a description, we can create many objects from a class.
An object is also called an instance of a class and the process of creating this object is called
instantiation.
Variables in Python:
You can consider a variable to be a temporary storage space where you can keep changing
values. Let’s take this example to understand variables:
So, let’s say, we have this cart and initially we store an apple in it.
After a while, we take out this apple and replace it with a banana.
So, here this cart acts like a variable, where the values stored in it keep on changing.
Now, that we have understood what a variable is, let’s go ahead and see how can we assign
values to a variable in python.
Assigning values to a variable:
To assign values to a variable in Python, we will use the assignment (=) operator.
Here, initially, we have stored a numeric value -> 10 in the variable ‘a’. After a while, we
have stored a string value -> “sparta” in the same variable. And then, we have stored the
logical value True.
Now, let’s implement the same thing in Spider and look at the result:
Assigning a value 10 to a:
Allocating “sparta” to a:
Assigning True to a:
Going ahead in this Python tutorial, we will learn about data types in Python.
Numbers in Python
Numbers in python could be integers, floating point numbers or complex numbers.
Here, we have assigned the value 100 to num1 and when we check the type of the variable,
we see that it is an integer.
This time, we have assigned the value 13.4 to num2 and checking the type of the variable,
tells us that it is float.
Here, we have assigned the value 10-10j to num3. Now 10-10j comprises two parts-> the
real part and the imaginary part and combining these two gives us the complex number.
Python Strings
Anything written in single or double quotes is treated as a string in Python.
Now, let’s see how can we extract individual characters from a string.
So, I’d want to extract the first two characters from ‘str1’ which I have created above:
Now, similarly, let’s extract the last two characters from str1:
Python Tuples
A python tuple is a collection of immutable Python objects enclosed within parenthesis ().
Elements in a tuple could be of the same data type or of the different data types.
Let’s create a tuple where elements are of the same data type:
Python Lists
Python Lists is an ordered collection of elements.
The below line of code will return the length of the list:
Python Sets
Python sets are a collection of unordered and unindexed items.
Creating a set:
Here, in set ‘Age’, value “22” is appearing twice. Since every element in set is unique, it will
remove the duplicate value.
Operations on Sets:
1.add: This method adds an element to the set if it is not present in it.
Python Dictionary
Python Dictionaries is an unordered collection of data. The data in the dictionary is stored as
a key:value pair where the key should not be mutable and value can be of any type.
Creating a Dictionary:
The problem that arises here is that the 3rd line of the code returns a key error :
The get() method is used to avoid such situations. This method returns the value for the given
key, if present in the dictionary. If not, then it will return None (if get() is used with only one
argument).
Syntax :
Dict.get(key, default=None)
Example:
Output:
1
None
Not Found !
Conditional Statements
We use a conditional statement to run a single line of code or a set of codes if it satisfies
certain conditions. If a condition is true, the code executes, otherwise, control passes to the
next control statement.
There are three types of conditional statements as illustrated in the above example:
1. If statement: Firstly, “if” condition is checked and if it is true the statements under “if”
statements will be executed. If it is false, then the control will be passed on to the next
conditional statements.
2. Elif statement: If the previous condition is false, either it could be “if” condition or “elif”
after “if”, then the control is passed on to the “elif” statements. If it is true then the
statements after the “elif” condition will execute. There can be more than one “elif”
statement.
3. Else statement: When “if” and “elif” conditions are false, then the control is passed on to the
“else” statement and it will execute.
Now, let’s go ahead and learn about loops in this python tutorial.
Loops
If we have a block of code then statements in it will be executed sequentially. But, when we
want a statement or a set of statements to be executed multiple times then we use loops.
Types of loops:
1.While loop: We use this loop when we want a statement or a set of statement to execute as
long as the Boolean condition associated with it satisfies.
In the while loop, the number of iterations depends on the condition which is applied to the
while loop.
2.for loop: Here, we know the number of iterations unlike while loop. This for loop is also
used for iterations of statements or a set of statements multiple times.
3.nested loop: This type of loop consists of a loop inside a loop. It can be for loop or can be
a combination of for and while loop.
User-Defined Function
In any programming language, functions are a better and systematic way of writing.
Functions provide us the liberty to use the code inside it whenever it is needed just by calling
the function by its name.
Syntax: def function()
Problem#1 Write a Python program to print out all even numbers from a given numbers list
in the same order and stop the printing if any numbers that come after 237 in the sequence.
numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958,743, 527
]
Solution:-
Python Code:
numbers = [ 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328,
615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950,
626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379,
843, 831, 445, 742, 717, 958,743, 527 ]
for x in numbers:
if x == 237:
print(x)
break;
elif x % 2 == 0:
print(x)
Problem#2 Now, for the same list of numbers and for the same conditions save the chosen
numbers in a separate list (instead of printing). Print the mean, median and mode of the
numbers in the list without importing any package.
Solution: mmm.py
Import Package
Write a Python program to compute the distance between the points (x1, y1) and (x2, y2).
Pictorial Presentation:
Sample Solution:-
Python Code:
import math
p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)
Output:
6.324555320336759
import numpy as np
from scipy import stats
dataset= [1,1,2,3,4,6,18]
#mean value
mean= np.mean(dataset)
#median value
median = np.median(dataset)
#mode value
mode= stats.mode(dataset)
Output:
Mean: 5.0
Median: 3.0
Mode: ModeResult(mode=array([1]), count=array([2]))
[75,25,73]
[82,22,86]
[53,31,66]
Solution: marksP5.py