Python Booklet

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Grade

VI-VIII

Page 1 of 33
VI

Page 2 of 33
Introduction to Artificial Intelligence (AI)

What Is Artificial Intelligence (AI)?

Artificial Intelligence (AI) is a field of computer science that focuses on creating intelligent
machines capable of performing tasks that typically require human intelligence. AI involves
designing computer systems and programs that can learn, reason, and make decisions like
humans do.

AI can be explained as the development of computer programs or machines that can think and
learn from experiences, similar to how humans do. It involves teaching computers to perform
tasks that would typically require human intelligence, such as understanding and responding to
spoken language, recognizing objects in images, or playing games.

AI can be found in various technologies and applications we encounter in our daily lives. For
example, voice assistants like Siri or Alexa use AI to understand and respond to our spoken
commands, while recommendation systems on streaming platforms or online stores use AI to
suggest content or products based on our preferences.

In summary, AI is about creating intelligent machines that can mimic human intelligence and
perform tasks that usually require human thinking, learning, and decision-making abilities. It is
an exciting field that is shaping the future of technology and impacting various aspects of our
lives.

Examples of Artificial Intelligence in daily life

1. Voice Assistants: AI-powered voice assistants like Siri, Alexa, and Google Assistant are
commonly found in smart phones, smart speakers, and other devices. They can understand
spoken commands and perform various tasks such as answering questions, setting reminders,
playing music, and providing weather updates.

2. Online Recommendations: When you shop online or watch videos on platforms like
Amazon, Netflix, or YouTube, you may have noticed personalized recommendations. These
recommendations are based on AI algorithms that analyze your browsing or viewing history,
preferences, and similar user data to suggest products or content that you might be interested in.
Page 3 of 33
3. Social Media Algorithms: Social media platforms like Facebook, Instagram, and TikTok
utilize AI algorithms to curate your news feed or suggest posts and accounts to follow. These
algorithms consider factors such as your interests, engagement history, and interactions to show
you relevant content.

4. Virtual Assistants: Some chat bots or virtual assistants that you interact with on websites or
messaging apps use AI to understand and respond to your queries. These AI-powered assistants
can provide customer support, answer frequently asked questions, and assist with basic tasks.

5. Smart Home Devices: AI is integrated into many smart home devices, such as smart
thermostats, security systems, and lighting controls. These devices can learn your preferences,
adjust settings automatically, and provide energy-efficient solutions by analyzing data and
patterns.
These are just a few examples of how AI is present in our daily lives. It's important to note that
AI is continuously evolving and being integrated into various technologies and applications,
making our lives more convenient and efficient.

Importance of Artificial Intelligence


1. Efficiency
2. Problem-solving
3. Personalization
4. Automation

Applications of Artificial Intelligence


1. Healthcare
2. Education
3. Transportation
4. Entertainment
5. Customer Service
6. Environmental Conservation

Software that are built in Python


 Dropbox
 Spotify
 Instagram
 Pinterest
 Reddit
 Uber
Page 4 of 33
Artificial Intelligence with Python
Python is a machine learning program. Machine learning is a step in the direction of AI.

Role of Python in Artificial Intelligence

Python comes with pre-built libraries such as NumPy. To perform scientific calculations and
Python is used for human to computer interactions through chat bots. Chat bots use AI. Python
creates intelligent systems, explores machine learning algorithms.

Download and install Python Jupyter interpreter and PyCharm and get the most useful
package in machine learning in python. Understand its syntax using data visualization.
If you are a machine learning beginner and looking to finally get started using Python.

Interface of Jupyter Interpreter for Python

Page 5 of 33
Getting Started with Python Programming

What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released
in 1991. It is used for:
 Web development (server-side).
 Software development.
 Mathematics.
 System scripting.

What can Python do?


 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.

Page 6 of 33
Why Python?
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional way.

Basics of Python syntax and structure


Python is a popular programming language that is easy to learn and widely used. Understanding
the basics of Python syntax and structure will help you write simple programs and solve
problems using code.
In Python, a program is made up of statements. Each statement is written on a separate line.
Unlike other programming languages, Python uses indentation (spaces or tabs) to group
statements together. Indentation helps Python understand the structure of your code.
Example:
Print ("Hello, world!")
x=5
if x > 0:
print ("Positive number")

Python Syntax compared to other programming languages


 Python was designed for readability, and has some similarities to the English language with
influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this
purpose.

Page 7 of 33
Python comments
 Comments can be used to explain Python code.
 Comments can be used to make the code more readable.
 Comments can be used to prevent execution when testing code.
Comments: Comments are used to explain and document your code. They are not executed by
the computer but provide information for human readers.

Creating a Comment for a single line:


Comments starts with a #, and Python will ignore them:

Example

#This is a comment
print("Hello, World!")

Comments can be placed at the end of a line, and Python will ignore the rest of the line:

Example

print("Hello, World!") #This is a comment

A comment does not have to be text that explains the code, it can also be used to prevent Python
from executing code:

Example

#print("Hello, World!")
print("Cheers, Mate!")

Creating a Comment for a multiline


We can add a multiline string (triple quotes) in your code, and place comment inside it:
Example:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code, but then ignore it,
and you have made a multiline comment.
Page 8 of 33
Variables, data types, and operators

Variables: Variables are used to store and manipulate data in Python. You can think of
variables as containers that hold values. To create a variable, you give it a name and assign a
value to it using the assignment operator (=).
Example:
x = 10
y = "Hello"

Data Types: Python supports different data types, such as numbers, strings, and booleans.
Numbers can be integers (whole numbers) or floating-point numbers (numbers with decimal
points). Strings are sequences of characters enclosed in quotation marks. Booleans represent
either True or False.
Example:
x=5 # Integer
y = 3.14 # Floating-point number
name = "John" # String
is_student = True # Boolean

Operators: Python provides various operators to perform operations on variables and


values. Some common operators include arithmetic operators (+, -, *, /), comparison operators
(>, <, ==), and logical operators (and, or, not).
Example:
x = 5 + 3 # Addition
y = 10 - 2 # Subtraction
is_greater = x > y # Comparison
is_true = True and False # Logical

Page 9 of 33
Basics of Python syntax and structure
In Python, a program is made up of statements. Each statement is written on a separate line.
Unlike other programming languages, Python uses indentation (spaces or tabs) to group
statements together. Indentation helps Python understand the structure of your code.
Example 1: Print if value is a positive number
print("Hello, world!")
x=5
if x > 0:
print("Positive number")
Example 2: Check number and print if value is positive or negative
x = -2
if x > 0:
print("Positive number")
else:
print("Negative number")
Example 1( Addition of two numbers )
X = 5+3 # Addition
Print (“5+3 =”, x)
5+3=8
Flowchart

Page 10 of 33
Algorithm
Step1: Start
Step 2: Read 5, 3
Step 3: x=5+3
Step 4: Print x
Step 5: End

Example 1( Subtraction of two numbers )

y = 10 - 2 # Subtraction
print("10 - 2 = ",y)
10 - 2 = 8
Flow Chart

Algorithm
Step1: Start
Step 2: Read 10, 2
Step 3: y=10-2
Step 4: Print y
Step 5: End
Page 11 of 33
Example 3 (Comparison)
x=5+3
y = 10 - 1
is_greater = x > y # Comparison
print("Is x is greater than y: ", is_greater)
Is x is greater than y: False

Algorithm
1. Assign 5 + 3 to x // Addition
2. Assign 10 - 1 to y // Subtraction
3. Assign the result of x > y to is_greater // Comparison
4. Print "Is x is greater than y: " concatenated with the value of is_greater

Page 12 of 33
Example 4 (Logical)
is_true = False and True # Logical
print(is_true)
False
Algorithm
1. Assign the result of False and True to is_true // Logical
2. Print the value of is_true

Page 13 of 33
VII

Page 14 of 33
What is a Programming Language?
Programming languages define and compile a set of instructions for the CPU (Central Processing
Unit) for performing any specific task. Every programming language has a set of keywords
along with syntax- that it uses for creating instructions.

Till now, thousands of programming languages have come into form. All of them have their own
specific purposes. All of these languages have a variation in terms of the level of abstraction
that they all provide from the hardware. A few of these languages provide less or no abstraction
at all, while the others provide a very high abstraction. On the basis of this level of abstraction,
there are two types of programming languages:

 Low-level language
 High-level language
The primary difference between low and high-level languages is that any programmer can
understand, compile, and interpret a high-level language feasibly as compared to the machine.
The machines, on the other hand, are capable of understanding the low-level language more
feasibly compared to human beings.

What are High-Level Languages?


High-level languages are programming languages that are designed to allow humans to write
computer programs and interact with a computer system without having to have specific
knowledge of the processor or hardware that the program will run on.

High-level languages use command words and Syntax which reflects everyday language, which
makes them easier to learn and use. High-level languages also offer the programmer
development tools such as libraries and built-in functions.

They are very widely used and popular in today’s times.

Examples of high-level programming languages in active use today include Python, JavaScript,
Visual Basic, Delphi, Perl, PHP, C#, Java and many others.

What are Low-Level Languages?


Low-Level language is the only language which can be understood by the computer. Low-level
language is also known as Machine Language. The machine language contains only two symbols
1 & 0. All the instructions of machine language are written in the form of binary numbers 1's &
0's.

 They are also called machine-level languages.


 Machines can easily understand it.
 They are not very easy to understand.
 These languages depend on machines. Thus, one can run it on various platforms.

Page 15 of 33
 They always require assemblers for translating instructions.
 Low-level languages do not have a very wide application in today’s times.

Introduction to Python
In this introduction to programming using Python, we will explore various Real-World examples
to understand the basics of programming concepts. Students in grades 6 to 8 can better grasp the
fundamental ideas behind programming and its relevance in everyday life by relating
programming concepts to practical examples.

Variables:
What are Variables and Data types?

Variables, and data types, are fundamental concepts in Python. Variables are used to store data
values in memory for later use. Let's define each of these concepts

Rules for naming variables


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)
 A variable name cannot be any of the Python keywords.

 Legal variable names:

 myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

 Illegal variable names:

 2myvar = "John"
my-var = "John"
my var = "John"

Page 16 of 33
Data Types:
The data type is a classification that tells the computer what kind of data is being stored or used
in a program, such as numbers, text, or true/false values.

Real-World Examples: Consider a school library. Different types of books are stored on
different shelves. In programming, data types are like different categories of information that we
can store and manipulate. Here are some common data types in Python:

a. Numeric Data Type:


- Real-World Examples: Think of a shopping receipt that lists the total amount spent. In
programming, numeric data types (e.g., integers and floating-point numbers) represent numerical
values. They can be used for calculations, keeping track of quantities, and representing
measurements.

b. String Data Type:


- Real-World Examples: Imagine you have a collection of student names in your class. In
programming, string data type is used to represent text or a sequence of characters. It can store
names, addresses, messages, and any other textual information.

c. Boolean Data Type:


- Real-World Examples: Consider a locked door. It can either be open or closed. A boolean data
type in programming represents two values: True or False. It is often used for conditions and
making decisions in programs.

Operators

Python language offers numerous operators to manipulate and process data. Following is the list
of some basic operator types. Here, we will discuss only two types of operators.
 Assignment Operator
 Arithmetic Operators
 Logical Operators
 Relational Operators
Assignment Operator
Assignment operator is used to assign a value to a variable, or assign value of variable to another
variable.
Equal sign (=) is used as assignment operator in Python. Consider the following example

Example:
sum = 5
Value 5 is assigned to a variable named sum after executing this line of code.

Page 17 of 33
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on data. Following table
represents arithmetic operators with their description.

Arithmetic Table

Operator Name Description


It is used to divide the value on the left
/ Division Operator
side by the value on right side
* Multiplication Operator It is used to multiply two values

+ Addition Operator It is used to add two values


It is used to subtract the value on right
- Subtraction Operator
side from the value on the left side
It gives remainder value after dividing
% Modulus Operator
the left operand by right operand

Python Program to Add Two Numbers

Page 18 of 33
Page 19 of 33
Python Program to Convert Kilometers to Miles

Page 20 of 33
Calculate Area of a triangle

Page 21 of 33
Python Program to Convert Celsius to Fahrenheit

Page 22 of 33
Python Program to check if a Number is Positive, Negative or 0

A number is positive if it is greater than zero. We check this in the expression of if. If it is False,
the number will either be zero or negative. This is also tested in subsequent expression.

Page 23 of 33
Python Program to check if a Number is odd or even
A number is even if it is perfectly divisible by 2. When the number is divided by 2, we use the
remainder operator % to compute the remainder. If the remainder is not zero, the number is odd.

Page 24 of 33
VIII

Page 25 of 33
In early grades you have learned about basics of Python language codes.

In this Grade, we will learn some advanced python language codes.

Translator
Any program written in a high-level language is known as source code. However, computers
cannot understand source code. Before it can be run, source code must first be translated into a
form which a computer understands - this form is called object code.

A translator is a program that converts source code into object code. Generally, there are three
types of translator:

 Compilers
 Interpreters
 Assemblers

Compiler
A compiler is software that is responsible for the conversion of computer program written in
some high level programming language to machine language code.

Interpreters
An interpreter translates source code into object code one instruction at a time. It is similar to a
human translator translating what a person says into another language

Page 26 of 33
Comparison between the Compiler and the Interpreter

Compiler Interpreter

A compiler translates the entire source code in a An interpreter translates the entire source code line by
single run. line.

It consumes less time i.e., it is faster than an It consumes much more time than the compiler i.e., it is
interpreter. slower than the compiler.

It is more efficient. It is less efficient.

CPU utilization is more. CPU utilization is less as compared to the compiler.

Both syntactic and semantic errors can be checked Only syntactic errors are checked.
simultaneously.

The localization of errors is difficult. The localization of error is easier than the compiler.

A presence of an error can cause the whole program A presence of an error causes only a part of the program
to be re-organized. to be re-organized.

The compiler is used by the language such as C, An interpreter is used by languages such as Java, python
C++. etc.

Interpreted language
Similar to other scripting languages, Python is an interpreted language. At runtime an interpreter
processes the code and executes it. To demonstrate the use of the Python interpreter, we write
print “Hello World” to a file with a .py extension.

Operators

Python language offers numerous operators to manipulate and process data. Following is the list

of some basic operator types.

 Assignment Operator

 Arithmetic Operators

 Logical Operators

 Relational Operators

Page 27 of 33
Logical Operators (Basic logical operators and their description)

Operator Description
&& Logical AND

ll Logical OR

! Logical NOT

Relational Operators (Basic Relational Operators with their description)

Relational Operators Description

== Equal to

!= Not equal

> Greater than

< Less than

>= Greater than equal to

<= Less than equal to

Example codes
Here are some small and basic coding programs that demonstrate the use of different data types
in Python: (Recall data types keep asking questions about data types before demonstrating
examples)

Page 28 of 33
Numeric Data Types:

Explanation:
The code prompts the user to enter two numbers using the input() function. The int()
function is used to convert the input to integers since input() returns a string by default.

The program performs various arithmetic operations on the input numbers: addition (+),
subtraction (-), multiplication (*), and division (/).

The results of the arithmetic operations are stored in separate variables: sum_result,
difference_result, product_result, and quotient_result.

Finally, the program prints the results of the arithmetic operations using the print()
function.

Page 29 of 33
Output:

In this example, the program asks the user to enter two numbers. It performs arithmetic
operations on those numbers and displays the results. The output generated depends on the input
provided by the user.

Page 30 of 33
String Data Type:

Explanation
The code prompts the user to enter a message using the input() function, and the input is
stored in the variable user_input.

The program defines a dictionary responses that maps user inputs to AI responses.

The dictionary consists of key-value pairs, where the key represents the user input, and
the value represents the corresponding AI response.

The program retrieves the AI response based on the user input using the get() method of
the responses dictionary. It converts the user input to lowercase using the lower()
method to make it case-insensitive.

If the user input matches one of the keys in the responses dictionary, the corresponding
AI response is returned. Otherwise, it retrieves the default response.

Finally, the program prints the AI response with the prefix "AI: ".

Page 31 of 33
Output

In this example, the program simulates a simple AI chatbot. It takes user input, matches it with
predefined responses, and generates an appropriate AI response. The output displayed depends
on the user's input and the corresponding AI response defined in the responses dictionary.

Boolean Data Type

Explanation
The code prompts the user to enter their age using the input() function. The int() function
is used to convert the input to an integer since input() returns a string by default.

The if-else statement checks the value of age. If the condition age >= 18 evaluates to
True, it means the user is 18 years or older, and the program prints "You are eligible to
vote.".
Page 32 of 33
If the condition is False, indicating that the user is younger than 18, the else block is
executed, and the program prints "You are not eligible to vote yet.

Output

In this example, the program asks the user to enter their age. If the age entered is 18 or above, the
program displays the message "You are eligible to vote." If the age is less than 18, it displays the
message "You are not eligible to vote yet." The output generated depends on the input provided
by the user.

Page 33 of 33

You might also like