Lab Manual of Intro to Computer Programming for Data Sciences
Lab Manual of Intro to Computer Programming for Data Sciences
Note: If you encounter issues during installation, temporarily disable your anti-virus
software during install, then re-enable it after the installation concludes. If you installed for
all users, uninstall Anaconda and re-install it for your user only.
3. Click Next.
4. Read the licensing terms and click I Agree.
5. It is recommended that you install for Just Me, which will install Anaconda Distribution
to just the current user account. Only select an install for All Users if you need to install
for all users’ accounts on the computer (which requires Windows Administrator
privileges).
6. Click Next.
7. Select a destination folder to install Anaconda and click Next. Install Anaconda to a
directory path that does not contain spaces or unicode characters. For more information on
destination folders, see the FAQ.
Note: As of Anaconda Distribution 2022.05, the option to add Anaconda to the PATH
environment variable during an All Users installation has been disabled. This was done to
address a security exploit. You can still add Anaconda to the PATH environment variable
during a Just Me installation.
9. Click Install. If you want to watch the packages Anaconda is installing, click Show Details.
10. Click Next.
11. Optional: To learn more about Anaconda’s cloud notebook service, go
to https://www.anaconda.com/code-in-the-cloud.
Or click Continue to proceed.
12. After a successful installation you will see the “Thanks for installing Anaconda” dialog
box:
13. If you wish to read more about Anaconda.org and how to get started with Anaconda,
check the boxes “Anaconda Distribution Tutorial” and “Learn more about Anaconda”.
Click the Finish button.
14. Verify your installation.
Installing the classic Jupyter Notebook interface
This section includes instructions on how to get started with Jupyter Notebook. But there are
multiple Jupyter user interfaces one can use, based on their needs. Please checkout the list and
links below for additional information and instructions about how to get started with each of them.
This information explains how to install the Jupyter Notebook and the IPython kernel.
Prerequisite: Python
While Jupyter runs code in many programming languages, Python is a requirement for installing
the Jupyter Notebook. The Python version required differs between Jupyter Notebook releases
(e.g. Python 3.6+ for Notebook v6.3, and Python 3.7+ for Notebook v7) .
We recommend using the Anaconda distribution to install Python and Jupyter. We’ll go through
its installation in the next section.
Important
Jupyter installation requires Python 3.3 or greater, or Python 2.7. IPython 1.x, which included the
parts that later became Jupyter, was the last version to support Python 3.2 and 2.6.
As an existing Python user, you may wish to install Jupyter using Python’s package
manager, pip, instead of Anaconda.
First, ensure that you have the latest pip; older versions may have trouble with some
dependencies:
Confirm that Anaconda is installed and working with Anaconda Navigator or conda with the
following instructions.
Anaconda Navigator
Anaconda Navigator is a graphical user interface (GUI) that is automatically installed with
Anaconda. Navigator will open if the installation was successful. If Navigator does not open,
review our help resources.
• Windows: Click Start, search for Anaconda Navigator, and click to open.
• macOS: Click Launchpad and select Anaconda Navigator. Or use Cmd+Space to open
Spotlight Search and type “Navigator” to open the program.
• Linux: See next section.
Conda
If you prefer using a command line interface (CLI), use conda to verify the installation using
Anaconda Prompt on Windows or the terminal on Linux and macOS.
• Windows: Click Start, search for Anaconda Prompt, and click to open.
• macOS: Use Cmd+Space to open Spotlight Search and type “Navigator” to open the
program.
• Linux–CentOS: Open Applications > System Tools > terminal.
• Linux–Ubuntu: Open the Dash by clicking the Ubuntu icon, then type “terminal”.
After opening Anaconda Prompt or the terminal, choose any of the following methods to verify:
• Enter conda list. If Anaconda is installed and working, this will display a list of
installed packages and their versions.
• Enter the command python. This command runs the Python shell, also known as the
REPL. If Anaconda is installed and working, the version information it displays when it
starts up will include “Anaconda”. To exit the Python shell, enter the command quit().
• Open Anaconda Navigator with the command anaconda-navigator. If Anaconda is
installed properly, Anaconda Navigator will open.
Lab 2
Understanding CMD
Networking Information (ipconfig)
ipconfig will provide you your ip address along with your local network.
If you need to go to a specific folder from this drive run the command CD Folder. The subfolders
must be separated by a backslash character: \.
To test if it worked, use the dir command. The newly created folder appears in the list.
If you are working on the “C:” drive and you want to create a new folder in “D:,” called Google,
type mkdir d:\Google and then press Enter.
Advantages:
1. Presence of third-party modules
2. Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc)
3. Open source and community development
4. Versatile, Easy to read, learn and write
5. User-friendly data structures
6. High-level language
7. Dynamically typed language(No need to mention data type based on the value assigned, it takes data
type)
8. Object-oriented language
9. Portable and Interactive
10. Ideal for prototypes – provide more functionality with less coding
11. Highly Efficient(Python’s clean object-oriented design provides enhanced process control, and the
language is equipped with excellent text processing and integration capabilities, as well as its own
unit testing framework, which makes it more efficient.)
12. (IoT)Internet of Things Opportunities
13. Interpreted Language
14. Portable across Operating systems
Applications :
1. GUI based desktop applications
2. Graphic design, image processing applications, Games, and Scientific/ computational Applications
3. Web frameworks and applications
4. Enterprise and Business applications
5. Operating Systems
6. Education
7. Database Access
8. Language Development
9. Prototyping
10. Software Development
So before moving on further.. let’s do the most popular ‘HelloWorld’ tradition and hence compare
Python’s Syntax with C, C++, Java ( I have taken these 3 because they are most famous and mostly used
languages).
Note: Please note that Python for its scope doesn’t depend on the braces ( { } ), instead it uses indentation
for its scope.Now moving on further Lets start our basics of Python . I will be covering the basics in
some small sections. Just go through them and trust me you’ll learn the basics of Python very easily.
Introduction and Setup
1. If you are on Windows OS download Python by Clicking here and now install from the setup and
in the start menu type IDLE.IDLE, you can think it as an Python’s IDE to run the Python Scripts.
It will look somehow this :
2. If you are on Linux/Unix-like just open the terminal and on 99% linux OS Python comes
preinstalled with the OS.Just type ‘python3’ in terminal and you are ready to go.
It will look like this :
The ” >>> ” represents the python shell and its ready to take python commands and code
Python Basic Syntax
Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after they have
been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Example
x = 5
y = "John"
print(type(x))
print(type(y))
Example
This will create two variables:
a = 4
A = "Sally"
#A will not overwrite a
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Output Variables
The Python print () function is often used to output variables.
Example
x = "Python is awesome"
print(x)
In the print () function, you output multiple variables, separated by a comma:
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Example
Print the data type of the variable x:
x = 5
print(type(x))
x = 20.5 float
x = 1j complex
x = range(6) range
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
Python Numbers
Python Numbers
There are three numeric types in Python:
• int
• float
• complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
Example
Integers:
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or negative, containing
one or more decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Complex numbers are written with a "j" as the imaginary part:
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:
Example
Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
Example
print("Hello")
print('Hello')
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Or three single quotes:
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Example
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Escape Characters
Other escape characters used in Python:
Code Result
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the Boolean answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
print(10 + 5)
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
Syntax
input(prompt)
Parameter Values
Parameter Description
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if statement to test whether b is
greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that
"b is greater than a".
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other
programming languages often use curly-brackets for this purpose.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
pri\nt("b is greater than a") # you will get an error
Elif
The elif keyword is Python's way of saying "if the previous conditions were not true, then try this
condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print
to screen that "a and b are equal".
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so
we go to the else condition and print to screen that "a is greater than b".
You can also have an else without the elif:
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
One line if statement:
Example
One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
Example
One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
The or keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Not
The not keyword is a logical operator, and is used to reverse the result of the conditional statement:
Example
Test if a is NOT greater than b:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If
You can have if statements inside if statements, this is called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Example
a = 33
b = 200
if b > a:
pass
Lab 5
Lab 5
Python while Loop
Python while Loop
Python while loop is used to run a block code until a certain condition is met.
while condition:
# body of while loop
Output
1
2
3
4
5
i = 1
True 1 is printed. i is increased to 2.
n = 5
i = 2
True 2 is printed. i is increased to 3.
n = 5
i = 3
True 3 is printed. i is increased to 4.
n = 5
i = 4
True 4 is printed. i is increased to 5.
n = 5
i = 5
True 5 is printed. i is increased to 6.
n = 5
i = 6
False The loop is terminated.
n = 5
Example 2: Python while Loop
# program to calculate the sum of numbers
# until the user enters zero
total = 0
Enter a number: 12
Enter a number: 4
Enter a number: -5
Enter a number: 0
total = 11
age = 32
counter = 0
Inside loop
Inside loop
Inside loop
Inside else
Note: The else block will not execute if the while loop is terminated by a break statement.
counter = 0
print('Inside loop')
counter = counter + 1
else:
print('Inside else')
Output
Inside loop
Inside else
Lab 6
Lab 6
For Loop in Python
In computer programming, loops are used to repeat a block of code.
For example, if we want to show a message 100 times, then we can use a loop. It's just a simple example;
you can achieve much more with loops.
In Python, a for loop is used to iterate over sequences such as lists, tuples, string, etc. For example,
Output
Swift
Python
Go
JavaScript
Here, val accesses each item of sequence on each iteration. The loop
continues until we reach the last item in the sequence.
flowchart of Python for Loop
Output
P
y
t
h
o
n
Python for Loop with Python range()
A range is a series of values between two numeric intervals.We use Python's built-in function range() to
define a range of values. For example,
values = range(4)
Here, 4 inside range() defines a range containing values 0, 1, 2, 3.In Python, we can use for loop to iterate
over a range. For example,
# iterate from i = 0 to i = 3
for i in values:
print(i)
Run Code
Output
0
1
2
3
Output
Hello
Hi
Hello
Hi
Hello
Hi
If we do not intend to use items of a sequence within the loop, we can write the loop like this:
The _ symbol is used to denote that the elements of a sequence will not be used within the loop body.
for i in digits:
print(i)
else:
print("No items left.")
Run Code
Output
0
1
5
No items left.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Nested Loops
A nested loop is a loop inside a loop.The "inner loop" will be executed one time for each iteration of the
"outer loop":
Example
Print each adjective for every fruit:
for x in adj:
for y in fruits:
print(x, y)
Example
for x in [0, 1, 2]:
pass