Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
0 views

UNIT 3_Python

This document provides an introduction to Python programming, detailing its features, editors, and basic concepts such as tokens, data types, and control flow statements. It also covers libraries like NumPy and Pandas, emphasizing their importance in data manipulation and analysis, particularly in the context of artificial intelligence. Sample programs illustrate various programming concepts, including user input, control flow, and working with CSV files.

Uploaded by

poorani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

UNIT 3_Python

This document provides an introduction to Python programming, detailing its features, editors, and basic concepts such as tokens, data types, and control flow statements. It also covers libraries like NumPy and Pandas, emphasizing their importance in data manipulation and analysis, particularly in the context of artificial intelligence. Sample programs illustrate various programming concepts, including user input, control flow, and working with CSV files.

Uploaded by

poorani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

UNIT 3: Python Programming

Introduction to Python
Python is a general-purpose, high level programming language. It was created by Guido
van Rossum, and released in 1991. Python got its name from a BBC comedy series – “Monty
Python’s Flying Circus”

Features of Python
High Level language
Interpreted Language
Free and Open Source
Platform Independent (Cross-Platform) – runs virtually in every platform if a
compatible python interpreter is installed.
Easy to use and learn – simple syntax similar to human language.
Variety of Python Editors – Python IDLE, PyCharm, Anaconda, Spyder
Python can process all characters of ASCII and UNICODE.
Widely used in many different domains and industries.

Python Editors

There are various editors and Integrated Development Environments (IDEs) that you
can use to work with Python. Some popular options are PyCharm, Spyder, Jupyter
Notebook, IDLE etc. Let us look how we can work with Jupyter Notebook.

Jupyter Notebook is an open-source web application that allows you to create and share
documents containing live code, equations, visualizations, and narrative text. It's widely
used in data science and research. It can be installed using Anaconda or with pip.
For more details of installation use the link
https://docs.jupyter.org/en/latest/install/notebook-classic.html
Those who are familiar with Python, open the command prompt in administrative mode and
type
pip install notebook
To run the notebook, Open the command prompt and type
jupyter notebook

Following window will open


You can type the code in the cell provided. Then click to see the output just
below it.

Getting Started with Python Programs


Python program consists of Tokens. It is the smallest unit of a program that the
interpreter or compiler recognizes. Tokens consist of keywords, identifiers, literals,
operators, and punctuators. They serve as the building blocks of Python code, forming the
syntactic structure that the interpreter parses and executes. During lexical analysis, the
Python interpreter breaks down the source code into tokens, facilitating subsequent parsing
and interpretation processes.

https://www.studytrigger.com/wp-content/uploads/2022/08/Tokens-in-Python.jpg
Keywords
Reserved words used for special purpose. List of keywords are given below.

Identifier
An identifier is a name used to identify a variable, function, class, module or other
object. Generally, keywords (list given above) are not used as variables. Identifiers cannot
start with digit and also it can’t contain any special characters except underscore.

Literals:
Literals are the raw data values that are explicitly specified in a program. Different
types of Literals in Python are String Literal, Numeric Literal (Numbers), Boolean Literal
(True & False), Special Literal (None) and Literal Collections.

Operators:
Operators are symbols or keywords that perform operations on operands to produce a
result. Python supports a wide range of operators:
• Arithmetic operators (+, -, *, /, %) • Logical operators (and, or, not)
• Relational operators (==, !=, <, >, <=, • Bitwise operators (&, |, ^, <<, >>)
>=) • Identity operators (is, is not)
• Assignment operators (=, +=, -=) • Membership operators (in, not in)

Punctuators:
Common punctuators in Python include
: ( ) [ ] { } , ; . ` ' ' " " / \ & @ ! ? | ~ etc.

Example

output
Tokens in the above program are given below
Keyword - import
Identifier - num , root (Here it can be said as variables also)
Literal - 625
Operator - =
Punctuator - ““ ,().
In the above program
print () is used to display the output on the screen
# symbol is used to write comments which are used to increase readability and
will not be executed
import statement is used to load the functions from the library (math)
Variables – Named labels whose value can be used and processed during the
execution of the program.

Sample Program-1
Display the string “National Animal-Tiger” on the screen

Sample Program-2

Write a program to calculate the area of a rectangle given the length and breadth are 50
and 20 respectively.

Data Types:
Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data. Python
supports Dynamic Typing. A variable pointing to a value of certain data type can be made to
point to a value/object of another data type. This is called Dynamic Typing.
The following are the standard or built-in data types in Python:
Data Type Description
Integer Stores whole number a=10
Boolean is used to represent the truth values of the Result = True
Boolean
expressions. It has two values True & False
Floating point Stores numbers with fractional part x=5.5
Complex Stores a number having real and imaginary part num=a+bj
Immutable sequences (After creation values cannot name= “Ria”)
String be changed in-place)
Stores text enclosed in single or double quotes
Mutable sequences (After creation values can be lst=[ 25, 15.6, “car”,
changed in-place) “XY”]
List
Stores list of comma separated values of any data
type between square [ ]
Immutable sequence (After creation values cannot tup=(11, 12.3, “abc”)
be changed in-place)
Tuple
Stores list of comma separated values of any data
type between parentheses ( )
Set is an unordered collection of values, of any type, s = { 25, 3, 3.5}
Set
with no duplicate entry.
Unordered set of comma-separated key:value pairs dict= { 1 : “One”, 2:
Dictionary
within braces {} “Two”, 3: “Three”}

Accepting values from the user


The input() function retrieves text from the user by prompting them with a string
argument. For instance:
name = input("What is your name?")
Return type of input function is string. So, to receive values of other types we have to use
conversion functions together with input function.

Sample Program-3
Write a program to read name and marks of a student and display the total mark.

output

In the above example float( ) is used to convert the datatype into floating point. The explicit
conversion of an operand to a specific type is called type casting.
Control flow statements in Python
Till now, the programs you've created have followed a basic, step-by-step progression,
where each statement executes in sequence, every time. However, there are many
practical programs where we have to selectively execute specific sections of the code or
iterate over parts of the program. This capability is achieved through selective statements
and looping statements.

Selection Statement

The if/ if..else statement evaluates test expression and the statements written below
will execute if the condition is true otherwise the statements below else will get executed.
Indentation is used to separate the blocks.

Syntax:

Let’s check out different examples to see the working of if and if-else statements

Sample Program-4
Asmita with her family went to a restaurant. Determine the choice of food according to the
options she chooses from the main menu.
Case 1: All Members are vegetarians. They prefer to have veg food. No other options.
(menu-veg)
Program & Output
Case 2: Family Members may choose non-vegetarian foods also if veg foods are not
available. (menu-veg/Nonveg)

Case 3: Family members can choose from variety of options

Sample Program-5
Write a program to get the length of the sides of a triangle and determine whether it is
equilateral triangle or isosceles triangle or scalene triangle,
Looping Statements
Looping statements in programming languages allow you to execute a block of code
repeatedly. In Python, there are mainly two types of looping statements: for loop and while
loop.

For loop
For loop iterates through a portion of a program based on a sequence, which is an ordered collection
of items.
The “for” keyword is used to start the loop. The loop variable takes on each value in the specified
sequence (e.g., list, string, range). The colon (:) at the end of the for statement indicates the start of
the loop body. The statements within the loop body are executed for each iteration. Indentation is
used to define the scope of the loop body. All statements indented under the for statement are
considered part of the loop. It is advisable to utilize a for loop when the exact number of iterations
is known in advance.
Syntax
for <control-variable> in <sequence/items in range>:
⏴statements inside body of the loop>
Example -1 Example-2

In the above program


range (5) returns the values 0,1,2,3,4
For each iteration of the loop variable i receives these values.
First iteration of the loop i=0 (one time print(“Python”) executes, similarly with

Whatever is given inside the loop executes repeatedly. In the first example, 5 times

The loop iterates over each item in the sequence until it reaches the end of the sequence
or until the loop is terminated using a break statement. It's a powerful construct for iterating
over collections of data and performing operations on each item.
Sample Program-6
Write a program to display even numbers and their squares between 100 and 110.

Sample Program-7
Write a program to read a list, display each element and its type. (use type( ) to display the
data type.)

In the above program


the control variable word gets each element of the list. Hence in print statement

Same program can be written using the following code also

print ( lst[i] , type ( lst[i] )


Here we take i as index number, lst[0]= 25 & lst[-1] = 100

Sample Program-8
Write a program to read a string. Split the string into list of words and display each word.
Sample Program-9
Write a simple program to display the values stored in dictionary

UNDERSTANDING CSV file (Comma Separated Values)

CSV files are delimited files that store tabular data (data stored in rows and columns). It
looks similar to spread sheets, but internally it is stored in a different format. In csv file,
values are separated by comma. Data Sets used in AI programming are easily saved in csv
format. Each line in a csv file is a data record. Each record consists of more than one
fields(columns). The csv module of Python provides functionality to read and write tabular
data in CSV format.
Let us see an example of opening, reading and writing formats for a file student.csv with
file object file. student.csv contains the columns rollno, name and mark.
importing library import csv
Opening in reading mode file= open(“student.csv”, “r”)
Opening in writing mode file= open(“student.csv”, “w”)
closing a file file.close( )
writing rows wr=csv.writer(file)
wr.writerow( [ 12, “Kalesh”, 480] )
Reading rows details = csv.reader(file )
for rec in details:
print(rec)

Sample Program-10
Write a Program to open a csv file students.csv and display its details
INTRODUCING LIBRARIES

A library in Python typically refers to a collection of reusable modules or functions that


provide specific functionality. Libraries are designed to be used in various projects to
simplify development by providing pre-written code for common tasks. Concept of libraries
are very easy to understand.

In Python, functions are organized within libraries similar to how library books are arranged
by subjects such as physics, computer science, and economics. For example, the "math"
library contains numerous functions like sqrt(), pow(), abs(), and sin(), which facilitate
mathematical operations and calculations. To utilize a library in a program, it must be
imported. For example, if we wish to use the sqrt() function in our program, we include the
statement "import math". This allows us to access and utilize the functionalities provided
by the math library.
Python offers a vast array of libraries for various purposes, making it a versatile language for
different domains such as web development, data analysis, machine learning, scientific
computing, and more. Now, let us explore some libraries that are incredibly valuable in the
realm of Artificial Intelligence.
NUMPY

NumPy, which stands for Numerical Python, is a powerful library in Python used for
numerical computing. It is a general-purpose array-processing package. NumPy provides
the ndarray (N-dimensional array) data structure, which represents arrays of any
dimension. These arrays are homogeneous (all elements are of the same data type) and can
contain elements of various numerical types (integers, floats, etc.)
Where and why do we use the NumPy library in Artificial Intelligence?

Suppose you have a dataset containing exam scores of students in various subjects, and you want
to perform some basic analysis on this data. You can utilize NumPy arrays to store exam scores
for different subjects efficiently. With NumPy's array operations, you can perform various
calculations such as calculating average scores for each subject, finding total scores for each
student, calculating the overall average score across all subjects, identifying the highest and
lowest scores. NumPy's array operations streamline these computations, making them both
efficient and convenient. This makes NumPy an indispensable tool for data manipulation and
analysis in data science applications.

NumPy can be installed using Python's package manager, pip.


pip install numpy
Creating a Numpy Array - Arrays in NumPy can be created by multiple ways. Some of the
ways are programmed here:
Using List of Tuples

Using values from the user (using empty( )) )-- ľ”e e½pťQ() ru⭲cťio⭲ i⭲ NQť”o⭲ is used

ťo íeťuí⭲ a ⭲e aííaQ or a gi»e⭲ size)

PANDAS

The name "Pandas" has a reference to both "Panel Data", and "Python Data
Analysis”. Pandas is a powerful and versatile library that simplifies tasks of data
manipulation in Python . Pandas is built on top of the NumPy library which means that a lot
of structures of NumPy are used or replicated in Pandas and Pandas is particularly well-
suited for working with tabular data, such as spreadsheets or SQL tables. Its versatility and
ease of use make it an essential tool for data analysts, scientists, and engineers working
with structured data in Python.
Where and why do we use the Pandas library in Artificial Intelligence?

Suppose you have a dataset containing information about various marketing campaigns
conducted by the company, such as campaign type, budget, duration, reach, engagement metrics,
and sales performance. We use Pandas to load the dataset, display summary statistics, and
perform group-wise analysis to understand the performance of different marketing campaigns.
We then visualize the sales performance and average engagement metrics for each campaign type
using Matplotlib, a popular plotting library in Python.
Pandas provides powerful data manipulation and aggregation functionalities, making it easy to
perform complex analysis and generate insightful visualizations. This capability is invaluable in AI
and data-driven decision-making processes, allowing businesses to gain actionable insights from
their data.

Pandas can be installed using:


pip install pandas
Pandas generally provide two data structures for manipulating data, they are: Series and
DataFrame.
Series
A Series is a one-dimensional array containing a sequence of values of any data type (int,
float, list, string, etc.) which by default have numeric data labels starting from zero. The data
label associated with a particular value is called its index. We can also assign values of other
data types as index. We can imagine a Pandas Series as a column in a spreadsheet as given
here.

In data science, we often encounter datasets


with two-dimensional structures. This is where
Pandas DataFrames come into play.
A Data Frame is used when we need to work on
multiple columns at a time, i.e., we need to process
the tabular data.
For example, the result of a class, items in a
restaurant’s menu, reservation chart of a
train, etc.
A DataFrame is a two-dimensional labeled
data structure like a table of MySQL. It
contains rows and columns, and therefore
has both a row and column index. Each
column can have a different type of value
such as numeric, string, boolean, etc., as in
tables of a database.

Creation of DataFrame

There are several methods to create a DataFrame in Pandas, but here we will discuss two
common approaches:
Using NumPy ndarrays-

Using List of Dictionaries

➔ Dictionary keys become column labels by default in a DataFrame, and the lists
become the rows.
➔ NaN (Not a Number) is inserted if a corresponding value for a column is missing.
➔ Pandas uses isnull() function to identify NaN values in a DataFrame.

You might also like