0% found this document useful (0 votes)
5 views52 pages

Lab Manual of Intro to Computer Programming for Data Sciences

The document is a lab manual for an introductory programming course focused on data sciences, covering installation of Anaconda, usage of CMD, and fundamentals of Python programming. It includes detailed instructions for setting up Jupyter Notebook, understanding command line operations, and basic Python concepts such as syntax, data types, and control structures. The manual is structured into multiple labs, each with specific tasks and examples to facilitate learning.

Uploaded by

vkqgq7c66h
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views52 pages

Lab Manual of Intro to Computer Programming for Data Sciences

The document is a lab manual for an introductory programming course focused on data sciences, covering installation of Anaconda, usage of CMD, and fundamentals of Python programming. It includes detailed instructions for setting up Jupyter Notebook, understanding command line operations, and basic Python concepts such as syntax, data types, and control structures. The manual is structured into multiple labs, each with specific tasks and examples to facilitate learning.

Uploaded by

vkqgq7c66h
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Lab Mannual

Introduction to programming for Data Sciences


Table of Contents
Lab 1(Date 6-9-2023) ................................................................................................................................... 6
Installation of Anaconda ............................................................................................................................... 6
Installing on Windows .............................................................................................................................. 6
Installing the classic Jupyter Notebook interface ....................................................................................... 10
Prerequisite: Python ................................................................................................................................ 10
Installing Jupyter using Anaconda and conda......................................................................................... 10
Alternative for experienced Python users: Installing Jupyter with pip ................................................... 10
Verifying your installation ...................................................................................................................... 11
Anaconda Navigator ............................................................................................................................... 11
Conda ...................................................................................................................................................... 11
Lab 2(13-9-2023) ........................................................................................................................................ 12
Understanding CMD ................................................................................................................................... 12
Networking Information (ipconfig) ........................................................................................................ 12
List Hardware Information (systeminfo) ................................................................................................ 12
Scan and Repair System Files (sfc /scannow)......................................................................................... 13
List Currently Running Task (tasklist).................................................................................................... 13
Change the Directory / Folder (cd) ......................................................................................................... 14
Create a New Directory / Folder (mkdir) ................................................................................................ 15
Clear Screen (cls) .................................................................................................................................... 16
Lab 3 (Date 20-9-2023) .............................................................................................................................. 17
Introduction to Python ................................................................................................................................ 17
Reason for increasing popularity ............................................................................................................ 17
LANGUAGE FEATURES ..................................................................................................................... 17
Interpreted ............................................................................................................................................... 17
Platform Independent ............................................................................................................................. 17
Advantages: ....................................................................................................................................... 18
Applications : .................................................................................................................................... 19
Python Basic Syntax ................................................................................................................................... 21
Variables ..................................................................................................................................................... 21
Creating Variables .................................................................................................................................. 21
Example............................................................................................................................................. 21
Example............................................................................................................................................. 21
Casting .................................................................................................................................................... 21
Example............................................................................................................................................. 21
Get the Type............................................................................................................................................ 21
Example............................................................................................................................................. 21
Single or Double Quotes? ....................................................................................................................... 21
Example............................................................................................................................................. 22
Example............................................................................................................................................. 22
Variable Names....................................................................................................................................... 22
Example............................................................................................................................................. 22
Snake Case .............................................................................................................................................. 22
Many Values to Multiple Variables ........................................................................................................ 22
Example............................................................................................................................................. 23
One Value to Multiple Variables ............................................................................................................ 23
Example............................................................................................................................................. 23
Output Variables ..................................................................................................................................... 23
Example............................................................................................................................................. 23
Example............................................................................................................................................. 23
Example............................................................................................................................................. 23
Python Data Types ...................................................................................................................................... 23
Getting the Data Type ............................................................................................................................. 24
Example............................................................................................................................................. 24
Setting the Data Type.............................................................................................................................. 24
Python Numbers...................................................................................................................................... 26
Python Numbers ................................................................................................................................... 26
Example............................................................................................................................................. 26
Example............................................................................................................................................. 26
Int ............................................................................................................................................................ 27
Example............................................................................................................................................. 27
Float ........................................................................................................................................................ 27
Example............................................................................................................................................. 27
Example............................................................................................................................................. 27
Complex ................................................................................................................................................. 28
Example............................................................................................................................................. 28
Type Conversion ................................................................................................................................... 28
Example............................................................................................................................................. 28
Strings ..................................................................................................................................................... 29
Example............................................................................................................................................. 29
Assign String to a Variable ..................................................................................................................... 29
Example............................................................................................................................................. 29
Multiline Strings ..................................................................................................................................... 29
Example............................................................................................................................................. 30
Example............................................................................................................................................. 30
Python - String Concatenation ................................................................................................................ 30
String Concatenation............................................................................................................................... 30
Example............................................................................................................................................. 30
Example............................................................................................................................................. 30
Escape Characters ................................................................................................................................... 30
Python Booleans ..................................................................................................................................... 32
Example............................................................................................................................................. 32
Python Operators .................................................................................................................................... 32
Example............................................................................................................................................. 32
Python Arithmetic Operators .............................................................................................................. 32
Python Assignment Operators............................................................................................................ 33
Python input() Function .............................................................................................................................. 35
Example............................................................................................................................................. 35
Definition and Usage .............................................................................................................................. 35
Syntax ..................................................................................................................................................... 35
Parameter Values .................................................................................................................................... 35
Lab 4(Date 29/9/2023) ................................................................................................................................ 37
Python Conditions and If statements .......................................................................................................... 37
Example............................................................................................................................................. 37
Example............................................................................................................................................. 37
Elif .......................................................................................................................................................... 38
Example............................................................................................................................................. 38
Else.......................................................................................................................................................... 38
Example............................................................................................................................................. 38
Example............................................................................................................................................. 38
Short Hand If........................................................................................................................................... 39
Example............................................................................................................................................. 39
Short Hand If ... Else............................................................................................................................... 39
Example............................................................................................................................................. 39
Example............................................................................................................................................. 39
And.......................................................................................................................................................... 39
Example............................................................................................................................................. 40
Or ............................................................................................................................................................ 40
Example............................................................................................................................................. 40
Not .......................................................................................................................................................... 40
Example............................................................................................................................................. 40
Nested If .................................................................................................................................................. 41
Example............................................................................................................................................. 41
The pass Statement ................................................................................................................................. 41
Example............................................................................................................................................. 41
Lab Task ..................................................................................................................................................... 42
Lab 5(4/10/2023) ........................................................................................................................................ 43
Python while Loop ...................................................................................................................................... 43
Python while Loop ................................................................................................................................ 43
Flowchart of Python while Loop ............................................................................................................ 43
Example: Python while Loop .............................................................................................................. 44
Example 2: Python while Loop............................................................................................................... 45
Output .................................................................................................................................................... 45
Infinite while Loop in Python ............................................................................................................... 45
Python While loop with else ................................................................................................................... 45
Lab Task ..................................................................................................................................................... 47
Lab 1
Installation of Anaconda
Installing on Windows
1. Download the Anaconda installer.
2. Go to your Downloads folder and double-click the installer to launch. To prevent
permission errors, do not launch the installer from the Favorites folder.

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.

Caution: Do not install as Administrator unless admin privileges are required.


8. Choose whether to add Anaconda to your PATH environment variable or register
Anaconda as your default Python. We don’t recommend adding Anaconda to your PATH
environment variable, since this can interfere with other software. Unless you plan on
installing and running multiple versions of Anaconda or multiple versions of Python,
accept the default and leave this box checked. Instead, use Anaconda software by opening
Anaconda Navigator or the Anaconda Prompt from the Start Menu.

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.

Installing Jupyter using Anaconda and conda


For new users, we highly recommend installing Anaconda. Anaconda conveniently installs
Python, the Jupyter Notebook, and other commonly used packages for scientific computing and
data science.

Use the following installation steps:

1. Download Anaconda. We recommend downloading Anaconda’s latest Python 3 version


(currently Python 3.9).
2. Install the version of Anaconda which you downloaded, following the instructions on the
download page.
3. Congratulations, you have installed Jupyter Notebook. To run the notebook:
4. jupyter notebook
See Running the Notebook for more details.
Alternative for experienced Python users: Installing Jupyter with pip

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:

pip3 install --upgrade pip


Then install the Jupyter Notebook using:
pip3 install jupyter
(Use pip if using legacy Python 2.)

Verifying your installation


Note: Using Anaconda in a commercial setting? You may need to purchase a license to stay compliant with
our Terms of Service. This can be accomplished through several of Anaconda’s tiers: Pro, Business (On-
prem), Business (Cloud), or Enterprise. If you have already subscribed to the Pro or Business tiers, see the
quickstart guides for Pro or Business to get started!

Visit https://anaconda.cloud/pricing to compare tier capabilities and pricing.

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.

To open Anaconda Prompt:

• 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.

List Hardware Information (systeminfo)


Use systeminfo to know very basic information about your pc’s hardware,like – motherboard,
processor & ram.
04. Check if Server is Reachable (ping)
The ping command sends packets of data to a specific IP address (or domain) on a network and
then lets you know how long it took to transmit that data and get a response.
If you get the response properly then the connection of the device is working properly if not a
particular server or your online connection is blocking communication between your computer
and another.
ping <ip or domain>

Scan and Repair System Files (sfc /scannow)


will scan and repair windows system files. But you must be run the console as an
sfc /scannow
administrator.

List Currently Running Task (tasklist)


Use tasklist to get currant list of all tasks running on your pc.

Use tasklist -v to obtain more detail of all tasks.


Change the Directory / Folder (cd)
Use cd\ to go to the top of the directory tree.

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: \.

Use the cd.. command to go one folder up.

Change the Drive


If you wanted to change the drive from “C:” to “D:”, type d: and then press Enter.
If you are now on the “D:” drive and you want to go to the Windows folder from the”C:” drive,
you should type cd /d C:\Windows and press Enter.

Create a New Directory / Folder (mkdir)


You can make a new folder using the mkdir (Make Directory) command. The syntax of these
commands is mkdir Folder.

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.

Clear Screen (cls)


To clear the existing commands in prompts type cls and press Enter. cls
Lab 3
Introduction to Python
Python is a widely used general-purpose, high level programming language. It was created by Guido van
Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an
emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines
of code.Python is a programming language that lets you work quickly and integrate systems more
efficiently.
There are two major Python versions: Python 2 and Python 3. Both are quite different.
Reason for increasing popularity
1. Emphasis on code readability, shorter codes, ease of writing
2. Programmers can express logical concepts in fewer lines of code in comparison to languages such
as C++ or Java.
3. Python supports multiple programming paradigms, like object-oriented, imperative and functional
programming or procedural.
4. There exists inbuilt functions for almost all of the frequently used concepts.
5. Philosophy is “Simplicity is the best”.
LANGUAGE FEATURES
Interpreted
• There are no separate compilation and execution steps like C and C++.
• Directly run the program from the source code.
• Internally, Python converts the source code into an intermediate form called bytecodes
which is then translated into native language of specific computer to run it.
• No need to worry about linking and loading with libraries, etc.
Platform Independent
• Python programs can be developed and executed on multiple operating system
platforms.
• Python can be used on Linux, Windows, Macintosh, Solaris and many more.
Free and Open Source; Redistributable
High-level Language
• In Python, no need to take care about low-level details such as managing the memory
used by the program.
Simple
• Closer to English language;Easy to Learn
• More emphasis on the solution to the problem rather than the syntax
Embeddable
• Python can be used within C/C++ program to give scripting capabilities for the
program’s users.
Robust:
• Exceptional handling features
• Memory management techniques in built
Rich Library Support
• The Python Standard Library is very vast.
• Known as the “batteries included” philosophy of Python ;It can help do various things
involving regular expressions, documentation generation, unit testing, threading,
databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI
and many more.
• Besides the standard library, there are various other high-quality libraries such as
the Python Imaging Library which is an amazingly simple image manipulation library.
Softwares making use of Python
Python has been successfully embedded in a number of software products as a scripting language.
1. GNU Debugger uses Python as a pretty printer to show complex structures such as C++
containers.
2. Python has also been used in artificial intelligence
3. Python is often used for natural language processing tasks.
Current Applications of Python
1. A number of Linux distributions use installers written in Python example in Ubuntu we have
the Ubiquity
2. Python has seen extensive use in the information security industry, including in exploit
development.
3. Raspberry Pi– single board computer uses Python as its principal user-programming language.
4. Python is now being used Game Development areas also.
Pros:
1. Ease of use
2. Multi-paradigm Approach
Cons:
1. Slow speed of execution compared to C,C++
2. Absence from mobile computing and browsers
3. For the C,C++ programmers switching to python can be irritating as the language requires proper
indentation of code. Certain variable names commonly used like sum are functions in python. So C,
C++ programmers have to look out for these.
Industrial Importance
Most of the companies are now looking for candidates who know about Python Programming. Those
having the knowledge of python may have more chances of impressing the interviewing panel. So I would
suggest that beginners should start learning python and excel in it.
Python is a high-level, interpreted, and general-purpose dynamic programming language that focuses on
code readability. It has fewer steps when compared to Java and C. It was founded in 1991 by developer
Guido Van Rossum. Python ranks among the most popular and fastest-growing languages in the world.
Python is a powerful, flexible, and easy-to-use language. In addition, the community is very active there.
It is used in many organizations as it supports multiple programming paradigms. It also performs
automatic memory management.

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

Organizations using Python :


1. Google(Components of Google spider and Search Engine)
2. Yahoo(Maps)
3. YouTube
4. Mozilla
5. Dropbox
6. Microsoft
7. Cisco
8. Spotify
9. Quora

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).

# Python code for "Hello World"

# nothing else to type...see how simple is the syntax.


print("Hello World")

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

Get the Type


You can get the data type of a variable with the type() function.

Example
x = 5
y = "John"
print(type(x))
print(type(y))

Single or Double Quotes?


String variables can be declared either by using single or double quotes:
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Variable names are case-sensitive.

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:

• A variable name must start with a letter or the underscore character


• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _)
• Variable names are case-sensitive (age, Age and AGE are three different 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"

Many Values to Multiple Variables


Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

One Value to Multiple Variables


And you can assign the same value to multiple variables in one line:

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)

You can also use the + operator to output multiple variables:

Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

Python Data Types


Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:

Text Type: Str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: Dict

Set Types: set, frozenset

Boolean Type: Bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

Getting the Data Type


You can get the data type of any object by using the type() function:

Example
Print the data type of the variable x:

x = 5
print(type(x))

Setting the Data Type


In Python, the data type is set when you assign a value to a variable:

Example Data Type

x = "Hello World" str


x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset

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)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(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".

You can display a string literal with the print() function:

Example
print("Hello")
print('Hello')

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

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)

Python - String Concatenation


String Concatenation
To concatenate, or combine, two strings you can use the + operator.

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

\' Single Quote

\\ Backslash

\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

\ooo Octal value

\xhh Hex value


Python Booleans
Booleans represent one of two values: True or False.
In programming you often need to know if an expression is True or False.

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)

Python divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common
mathematical operations:

Operator Name Example


+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Python Assignment Operators


Assignment operators are used to assign values to variables:

Operator Example Same As

= 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

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3


<<= x <<= 3 x = x << 3

Python input() Function


Example
Ask for the user's name and print it:
print('Enter your name:')
x = input()
print('Hello, ' + x

Definition and Usage


The input() function allows user input.

Syntax
input(prompt)

Parameter Values

Parameter Description

prompt A String, representing a default message before the input.


Lab 4
Lab 4
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:

• 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.

An "if statement" is written by using the if keyword.

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:

if a > b: print("a is greater than b")

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:

Example
One line if else statement:

a = 2
b = 330
print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional Expressions.


You can also have multiple else statements on the same line:

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.")

The pass Statement

if statements cannot be empty, but if you for some reason have


an if statement with no content, put in the pass statement to avoid getting an
error.

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.

The syntax of while loop is:

while condition:
# body of while loop

1. A while loop evaluates the condition


2. If the condition evaluates to True , the code inside the while loop is executed.
3. condition is evaluated again.
4. This process continues until the condition is False .
5. When condition evaluates to False , the loop stops.

Flowchart of Python while Loop

Flowchart of while Loop


Example: Python while Loop
# program to display numbers from 1 to 5
# initialize the variable
i = 1
n = 5

# while loop from i = 1 to 5


while i <= n:
print(i)
i = i + 1

Output

1
2
3
4
5

Here's how the program works:

Variable Condition: i <= n Action

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

number = int(input('Enter a number: '))

# add numbers until number is zero


while number != 0:
total += number # total = total + number

# take integer input again


number = int(input('Enter a number: '))

print('total =', total)


Output

Enter a number: 12
Enter a number: 4
Enter a number: -5
Enter a number: 0
total = 11

Infinite while Loop in Python


If the condition of a loop is always True , the loop runs for infinite times (until the memory is full). For
example,

age = 32

# the test condition is always True


while age > 18:
print('You can vote')
Python While loop with else
In Python, a while loop may have an optional else block.Here, the else part is executed after the
condition of the loop evaluates to False .

counter = 0

while counter < 3:


print('Inside loop')
counter = counter + 1
else:
print('Inside else')
Output

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

while counter < 3:


# loop ends because of break
# the else part is not executed
if counter == 1:
break

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,

languages = ['Swift', 'Python', 'Go', 'JavaScript']

# run a loop for each item of the list


for language in languages:
print(language)

Output

Swift
Python
Go
JavaScript

The syntax of a for loop is:

for val in sequence:


# statement(s)

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

Working of Python for loop

Example: Loop Through a String


for x in 'Python':
print(x)

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,

# use of range() to define a range of values


values = range(4)

# iterate from i = 0 to i = 3
for i in values:
print(i)
Run Code

Output

0
1
2
3

Using a for Loop Without Accessing Items


It is not mandatory to use items of a sequence within a for loop. For example,

languages = ['Swift', 'Python', 'Go']

for language in languages:


print('Hello')
print('Hi')

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:

languages = ['Swift', 'Python', 'Go']


for _ in languages:
print('Hello')
print('Hi')

The _ symbol is used to denote that the elements of a sequence will not be used within the loop body.

Python for loop with else


A for loop can have an optional else block. The else part is executed when the loop is exhausted
(after the loop iterates through every item of a sequence). For example,
digits = [0, 1, 5]

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:

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

The pass Statement


for loops cannot be empty, but if you for some reason have a for loop with no content, put in
the pass statement to avoid getting an error.

Example
for x in [0, 1, 2]:
pass

You might also like