0% found this document useful (0 votes)
53 views

Introduction To Python

The document provides an introduction to Python programming. It discusses printing a string, object-oriented programming concepts like classes and objects, variables and assigning values, data types including numbers, strings, tuples, lists, sets and dictionaries. It also covers conditional statements, loops, and user-defined functions.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Introduction To Python

The document provides an introduction to Python programming. It discusses printing a string, object-oriented programming concepts like classes and objects, variables and assigning values, data types including numbers, strings, tuples, lists, sets and dictionaries. It also covers conditional statements, loops, and user-defined functions.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Introduction to Python

Suppose we want to print “Welcome to the world of programming” on our screen.


print(“Welcome to the world of programming”)

Python is an object oriented programming language. Unlike procedure oriented


programming, where the main emphasis is on functions, object oriented programming stress
on objects.

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.

Again, after some time, we replace this banana with a mango.

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.

Data Types in Python


Every variable is associated with a data type and these are the different types of  data types
available in python:
Now, let’s understand these individual data types by their implementation.

Numbers in Python
Numbers in python could be integers, floating point numbers or complex numbers.

Let’s start off with an example on integer:

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.

Next, we have an example on floating-point number:

This time, we have assigned the value 13.4 to num2 and checking the type of the variable,
tells us that it is float.

Finally, let’s look at an example of a complex number:

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.

Now, let’s start with Python Strings.

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:

Now, let’s head onto tuples in Python:

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:

Now, let’s access the first element from this tuple:

Extracting the last element from this tuple:

Now, we will go ahead and learn about Python lists.

Python Lists
Python Lists is an ordered collection of elements.

It can contain elements of different data types, unlike arrays.


Now, let’s create a list with different data types:

Now, let’s do some operation on the list we created:


Fetching the first element from the list:

Adding an element while removing the other:

The below line of code will return the length of the list:

This will return the list in reversed order.

Now, we will further look at Python Sets.

Python Sets
Python sets are a collection of unordered and unindexed items.

Every element in a set is unique and it does contain duplicate values.


Sets can be used to perform mathematical calculations such as union, intersection, and
differences.

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.

2.union: It returns the union of two sets.

3.intersection: This method returns the intersection of two sets.


4.difference: The difference of two sets(set1, set2) will return the elements which are present
only in set1.

Now, we will look at Python Dictionary.

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:

Accessing elements from a dictionary:

Removing elements from a dictionary:

Replacing elements in a dictionary:


Get() method

Conventional method to access a value for a key:


dic = {"A":1, "B":2}
print(dic["A"])
print(dic["C"])

The problem that arises here is that the 3rd line of the code returns a key error :

Traceback (most recent call last):


File ".\dic.py", line 3, in
print (dic["C"])
KeyError: 'C'

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:

dic = {"A":1, "B":2}


print(dic.get("A"))
print(dic.get("C"))
print(dic.get("C","Not Found ! "))

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.

Now, we will learn about user-defined functions in this python tutorial.

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.

Use this numbers list:

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

Problem#3 Mean, Median and Mode using Numpy and Scipy

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)

print("Mean: ", mean)


print("Median: ", median)
print("Mode: ", mode)

Output:
Mean: 5.0
Median: 3.0
Mode: ModeResult(mode=array([1]), count=array([2]))

Problem#4 Use Numpy and Scipy in Problem#2


Solution: mmm.py
Problem#5 Following is the input NumPy array of marks of three students for Eng, Maths
and Accounts. Save the data in an Numpy array and print it. Now, suppose there is a retest
for the subject Maths. Delete corresponding column and insert the given new retest marks in
its place.

English Maths Accounts

[75,25,73]

[82,22,86]

[53,31,66]

Retest Marks: [54, 67, 61]

Solution: marksP5.py

You might also like