0% found this document useful (0 votes)
3 views10 pages

Unit 1 Python Programming

This document provides an introduction to Python programming, covering its features, data types, control flow statements, and libraries used for various applications, including artificial intelligence. It explains concepts such as tokens, keywords, identifiers, literals, operators, and the use of libraries like NumPy and Pandas for data manipulation. Additionally, it discusses how to handle CSV files and the basics of data frames in Python.

Uploaded by

ankur94703
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)
3 views10 pages

Unit 1 Python Programming

This document provides an introduction to Python programming, covering its features, data types, control flow statements, and libraries used for various applications, including artificial intelligence. It explains concepts such as tokens, keywords, identifiers, literals, operators, and the use of libraries like NumPy and Pandas for data manipulation. Additionally, it discusses how to handle CSV files and the basics of data frames in Python.

Uploaded by

ankur94703
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

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, Jupyter, Spyder
* Python can process all characters of ASCII and UNICODE.
* Widely used in many different domains and industries.

Getting Started with Python : →→


Python program consists of Tokens. It is the smallest unit of a program that the interpreter
or compiler recognizes.
Tokens consist of identifiers, keywords, literals, operators, and punctuators. They
serve as the building blocks of Python code.

Keywords : →
Reserved words used for special purpose.
e.g. in, for, while, True, False, None, import, is etc.

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)

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

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

e.g.
import math
num = 625
root = [Link]( num)
print(“Square root =”, root)

Output : → Square root = 25.0

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 - “” , ()

Program-1
Display the string “National Animal-Tiger” on the screen.
print( “National Animal-Tiger” )

Program-2
Write a program to calculate the area of a rectangle given the length and breadth are
50 and 20 respectively.
length = 50
breadth = 20
area = length * breadth
print(“Area of rectangle =”, area)

Data Types : →
Data types are the classification or categorization of data items. It represents the
kind of value stored in a particular variable.
The following are the standard or built-in data types in Python:

Number sequence Map set


int list dictionary set
float tuple
bool str
complex

Integer( int) : →
Stores whole number
Float : →
Stores numbers with fractional part.
Boolean (bool) : →
Stores boolean values. It has two values True & False
Complex : →
Stores a number having real and imaginary part. e.g. num=a+bj
String (str) : →
Stores text enclosed in single or double quotes. It is immutable sequences (After
creation values cannot be changed in-place)
List : →
Stores list of comma separated values of any data type between square [ ]. It is
mutable sequences (After creation values can be changed in-place)
Tuple : →
Stores list of comma separated values of any data type between parentheses ( ). It is
Immutable sequence (After creation values cannot be changed in-place)
Dictionary : →
Unordered set of comma-separated key:value pairs
within braces {}
Set : →
Set is an unordered collection of values, of any type, with no duplicate entry

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.

e.g.
Write a program to read name and marks of a student and display the total mark.

Program
Write a program to read name and marks of a student and display the total mark.
name = input(“Enter student’s name”)
m1 = int(input(“Enter the marks of english”))
m2 = int(input(“Enter the marks of AI”))
m3 = int(input(“Enter the marks of maths”))
total = m1 + m2 + m3
print(“Name : =”, name)
print(“Total marks : =”, total)

Control flow statements in Python : →


The statements can be divided in three main categories depending upon the flow of
execution/control.
1) Sequential / Linear
2) Selection / Decision Making
3) Iterative / Looping

1) Sequential/Linear : →
These statements are executed from top to bottom. All the statements are executed
and none of them skipped

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

—---------
Program
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 →→
choice = input(“Enter the choice of food - Veg/Nonveg”)
if choice == “Veg”:
print(“Welcome to Vegetarian Food House”)

Case 2: Family members may choose non-vegetarian foods also if veg foods are
not available. (menu-veg/Nonveg) →→
choice = input(“Enter the choice of food - Veg/Nonveg”)
if choice == “Veg”:
print(“Welcome to Vegetarian Food House”)
elif choice == “Nonveg”:
print(“Welcome to Nonvegetarian Food House”)

Case 3: Family members can choose from variety of options →→


choice = input(“Enter the choice of food - Veg/Nonveg”)
if choice == “Veg”:
print(“Welcome to Vegetarian Food House”)
elif choice == “Nonveg”:
print(“Welcome to Nonvegetarian Food House”)
else:
print(“Welcome to your Favourite Choice of Food”)

Program
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

a = int(input(“Enter the first side”))


b = int(input(“Enter the second side”))
c = int(input(“Enter the third side”))
if (a == b) and (b == c) and (c == a) :
print(“It is an Equilateral triangle:”)
elif (a == b) or (b == c) or (c == a) :
print(“It is an Isosceles triangle:”)
else:
print(“It is a 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 : →
it works at least one time for each element present in the sequence/ range
e.g.
for each element in sequence :
Do some action
(Here sequence may be List/Tuple /String or range( ) method)

e.g.
for i in [34, 56, 67, 88, 98 ]:
print("hello")
for i in [34, 56, 67, 88, 98 ]:
print(2 * i)
In above example for each element in the given sequence (List), we perform action ----
1) print message hello 5 times becoz sequence contains 5 elements
2) print twice of each element in the sequence

while loop : →
It repeat a set of statements till the condition is True. This loop is also known as
conditional/entry controlled loop.
e.g. To display table of 5
i = 1 ----------> initialization
while ( i <= 10 ) : -----> condition
print("5", "X", i, "=", 5 * i)
i = i + 1 ------> Loop update
UNDERSTANDING CSV file (Comma Separated Values) : →
CSV files are text files that store tabular data (data stored in rows and columns). It
looks similar to spread sheets.
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 [Link] with
file object file. [Link] contains the columns rollno, name and mark.

importing library → import csv


Opening in reading mode → file= open(“[Link]”, “r”)
Opening in writing mode → file= open(“[Link]”, “w”)
closing a file → [Link]( )
writing rows → wr=[Link](file)
[Link]( [ 12, “Kalesh”, 480] )
Reading rows → details = [Link](file )
for rec in details:
print(rec)
(Note : → csv files can be created easily using spreadsheets saved with extension .csv)

Program : →
Write a Program to open a csv file [Link] and display its details.
import csv
f = open(“[Link]”, “r”)
details = [Link](f)
for rec in details:
print(rec)

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

Python Libraries for Artificial intelligence : →


NumPy : →
It stands for Numerical Python, is a powerful library in Python used for numerical computing.
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).
It contains numerous functions that are used for manipulation of data stored in numpy array.
NumPy can be installed using Python's package manager, pip.
pip install numpy

e.g.
import numpy as np
rollno = [5, 7, 23, 45, 55]
ar = [Link](rollno)
print(ar)

PANDAS : →
It stands for Panel Data System
Pandas is one the most preferred and widely used Library. It offers some very efficient data
structure through which we can store data and perform action on data.
Pandas can be installed using:
pip install pandas
Pandas generally provide two data structures for manipulating data, They are: Series and
Data Frame.
Series : →
Pandas Series is a one-dimensional array-like object containing a sequence of values. Each
of these values is associated with a label called index. Ji
A Series data structure has two main components --
1) A collection of actual data
2) An associate data Label
e.g.
Index/ Label Data
0 35
1 56
2 45
3 67
4 78
--------------------------------------
We can also assign user-defined labels to the index : →→

Index/ Label Data


Jan 31
Feb 28
March 31
April 30
May 31
-------------------------------------------
Index/ Label Data
Amit 78
Shivani 98
Rajat 87
Ankit 46
Riya 88
e.g.
import pandas as pd
data = [35, 56, 45, 67, 78]
s = [Link] (data)
print(s)

e.g.
import pandas as pd
marks = [78, 98, 87, 46, 88]
s = [Link] (marks)
[Link] = [“Jan” , “Feb”, “March”, “ April”, “May”]
print(s)

e.g.
import pandas as pd
d= [31, 28, 31, 30, 31]
s = [Link] (data)
[Link] = [“Amit”, “Shivani”, “Rajat”, “Ankit”, “Riya”]
print(s)

Data Frame : →
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.
e.g.
Eng Maths AI
Ravi 67 89 77
Jay 56 70 87
Tej 65 77 80
Om 77 74 66
Anu 88 78 89

e.g.
import pandas as pd
marks = {“Eng” : [67, 56, 65, 77, 88], “Maths” : [89, 70, 77, 74, 78], “AI” : [77, 87, 80, 66, 89]
}
result = [Link](marks)
[Link] = [“Ravi”, “Jay”, “Tej”, “Om”, “Anu”]
print(result)

e.g.
⇒⇒Adding a New Column to a DataFrame:
Suppose we want to add one more subject (Science) in DataFrame result
result[ “Science” ] = [80, 64, 69, 59, 76]

⇒⇒Adding a New Row to a DataFrame:


Add new record of student into result DataFrame–
[Link][ “Umesh”] = [78, 90, 87, 76]

⇒⇒ Adding a New Row to a DataFrame:


Suppose we want to delete Maths record (column)
[Link](“Math”, axis = 1, inplace = True)
Suppose we want to delete Jay student record, actually we are deleting row..
[Link]( “Jay”, axis = 0, inplace = True)

⇒⇒Accessing Rows and Columns from a DataFrame:


Suppose we want to access only AI marks of all student
result[“AI”]
OR
[Link][ : , “AI”]
Suppose we want to access the record Om student –
[Link][ “Om”]

Understanding Missing Values : →


Missing Data or Not Available data can occur when no information is provided for one
or more items or for a whole unit.
In DataFrame it is stored as NaN (Not a Number) . Pandas provide a function isnull() to
check whether any value is missing or not in the DataFrame.

Attributes of DataFrames : →
Attributes are the properties of a DataFrame that can be used to fetch data.
e.g. DataFrame : Teacher
X XI XII
Physics Jay Kavi Mahima
Maths Dev Neel Om
AI Ravi Zen Ali
⇒⇒Displaying Row Indexes -
[Link]

⇒⇒Displaying column Indexes


[Link]

⇒⇒Displaying datatype of each


[Link]

⇒⇒Displaying data in Numpy Array form


[Link]

⇒⇒Displaying total number of rows and columns


[Link]

⇒⇒Displaying first n rows ( here n = 2)


[Link](2)
⇒⇒Displaying last n rows ( here n = 2)
[Link](2)

Importing and Exporting Data between CSV Files and DataFrames :



We can create a DataFrame by importing data from CSV files. Similarly, we can also
store or export data in a DataFrame as a .csv file.

Importing a CSV file to a DataFrame


Using the read_csv() function, you can import tabular data from CSV files into pandas
dataFrame
e.g.
pd.read_csv("[Link]")

Exporting a DataFrame to a CSV file


We can use the to_csv() function to save a DataFrame to a text or csv file.
For example, to save the DataFrame Teacher into csv file resultout, we should write
Teacher.to_csv(‘[Link]')

Scikit-learn : →
Scikit-learn (Sklearn) is the most useful and robust library for machine learning in Python.
Key Features:
● Offers a wide range of supervised and unsupervised learning algorithms.
● Provides tools for model selection, evaluation, and validation.
● Supports various tasks such as classification, regression, clustering, and more.

You might also like