Python For Grade 8 PDF
Python For Grade 8 PDF
Python For Grade 8 PDF
Why Python?................................................................................................................................................. 2
Introduction ................................................................................................................................................... 2
What can Python do? .................................................................................................................................... 3
Why Python?................................................................................................................................................. 3
Working with Python using Jupyter.............................................................................................................. 3
What is Anaconda Navigator? .................................................................................................................. 3
Creating a new notebook document .......................................................................................................... 4
Notebook user interface ............................................................................................................................ 5
Structure of a notebook document ............................................................................................................ 6
Python Syntax ............................................................................................................................................... 6
Python Indentations ...................................................................................................................................... 6
Example ............................................................................................................................................... 6
Python Comments ......................................................................................................................................... 6
Example ............................................................................................................................................... 7
Docstrings ..................................................................................................................................................... 7
Example ............................................................................................................................................... 7
Python Variables ........................................................................................................................................... 7
Creating Variables .................................................................................................................................... 7
Example ............................................................................................................................................... 7
Example ............................................................................................................................................... 8
Variable Names ......................................................................................................................................... 8
Functions ....................................................................................................................................................... 8
Print ........................................................................................................................................................... 8
Example ............................................................................................................................................... 8
Example ............................................................................................................................................... 8
Example ............................................................................................................................................... 9
Example ............................................................................................................................................... 9
Type .......................................................................................................................................................... 9
Example ............................................................................................................................................... 9
Python Casting .......................................................................................................................................... 9
String methods & built in functions ........................................................................................................ 10
Data type ..................................................................................................................................................... 11
Python Numbers...................................................................................................................................... 11
Int ........................................................................................................................................................ 11
Float .................................................................................................................................................... 12
Complex .............................................................................................................................................. 12
IF.................................................................................................................................................................. 12
Example............................................................................................................................................. 13
Elif ........................................................................................................................................................... 13
Example............................................................................................................................................. 13
Python Strings ............................................................................................................................................. 13
Let’s play with subscripts ................................................................................................................... 14
Creating and initializing strings .......................................................................................................... 14
Strings are immutable ......................................................................................................................... 15
Strings Operations ............................................................................................................................... 15
Python Loops............................................................................................................................................... 17
Python Functions ........................................................................................................................................ 19
PYTHON SAMPLE CALCULATOR .................................................................................................................. 21
Why Python?
Python is an easy-to-learn programming language that has some useful features for a beginning
programmer. The code is quite easy to read when compared to other programming languages,
and it has an interactive shell into which you can enter your programs and see them run. Python
is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its
design philosophy emphasizes code readability, and its syntax allows programmers to express
concepts in fewer lines of code than would be possible in languages such as C++ or Java. The
language provides constructs intended to enable clear programs on both a small and large scale.
Introduction
A computer program is a set of instructions that causes a computer to perform some kind of
action. It is not the physical parts of a computer—like the wires, microchips, cards, hard drive,
and such—but the hidden stuff running on that hardware. Like humans, computers use multiple
languages to communicate— in this case, programming languages. A programming language is
simply a particular way to talk to a computer—a way to use instructions that both humans and
the computer can understand. There are programming languages named after people (like Ada
and Pascal), those named using simple acronyms (like BASIC and FORTRAN), and even a few
named after TV shows, like Python.
Guido Van Rossum created python when he was working at CWI (Centrum Wiskunde &
Informatica) which is a National Research Institute for Mathematics and Computer
Science in Netherlands. The language was released in I991. Python got its name from a
BBC comedy series from seventies- “Monty Python‟s Flying Circus” not after python the
snake.
Why Python?
To write and run Python program, we need to have Python interpreter installed in our
computer. IDLE (GUI integrated) is the standard, most popular Python development
environment. IDLE is an acronym of Integrated Development Environment. It lets edit,
run, browse and debug Python Programs from a single interface. This environment makes
it easy to write programs.
The most recent major version of Python is Python 3
We can use Anaconda Navigator, which is from Anaconda.
You can download from Anaconda.org and choose 3.6 version.
As soon as you install you can open Anaconda Navigator.
What is Anaconda Navigator?
Anaconda Navigator is a desktop graphical user interface (GUI) included in Anaconda®
distribution that allows you to launch applications
Launch Jupiter Notebook from the dashboard.
The landing page of the Jupiter notebook web application, the dashboard, shows the
notebooks currently available in the notebook directory (by default, the directory from
which the notebook server was started).
You can create new notebooks from the dashboard with the New Notebook button, or
open existing ones by clicking on their name. You can also drag and
drop .ipynb notebooks and standard .py Python source code files into the notebook list
area.
When starting a notebook server from the command line, you can also open a particular
notebook directly, bypassing the dashboard, with Jupiter notebook my_notebook.ipynb.
The .ipynb extension is assumed if no extension is given.
When you are inside an open notebook, the File | Open… menu option will open the
dashboard in a new browser tab, to allow you to open another notebook from the
notebook directory or to create a new notebook.
Creating a new notebook document
A new notebook may be created at any time, either from the dashboard, or using the File ‣ New
menu option from within an active notebook. The new notebook is created within the same
directory and will open in a new browser tab. It will also be reflected as a new entry in the
notebook list on the dashboard.
Notebook user interface
When you create a new notebook document, you will be presented with the notebook name,
a menu bar, a toolbar and an empty code cell.
Notebook name: The name displayed at the top of the page, next to the Jupyter logo,
reflects the name of the .ipynb file. Clicking on the notebook name brings up a dialog
which allows you to rename it. Thus, renaming a notebook from “Untitled0” to “My first
notebook” in the browser, renames the Untitled0.ipynb file to My first notebook.ipynb.
Menu bar: The menu bar presents different options that may be used to manipulate the
way the notebook functions.
Toolbar: The tool bar gives a quick way of performing the most-used operations within
the notebook, by clicking on an icon.
Code cell: the default type of cell; read on for an explanation of cells.
Structure of a notebook document
The notebook consists of a sequence of cells. A cell is a multiline text input field, and its
contents can be executed by using CTRL-Enter or by clicking the “Play” button the
toolbar, or Cell, Run in the menu bar.
Code cells
A code cell allows you to edit and write new code, with full syntax highlighting and tab
completion. The programming language you use depends on the kernel, and the default
kernel (IPython) runs Python code.
Python Syntax
Python syntax can be executed by writing directly in the editor Or by creating a python file on
the server, using the .py file extension, and running it in the editor
print("Hello, World!")
Hello, World!
python myfile.py
Python Indentations
Where in other programming languages the indentation in code is for readability only, in Python
the indentation is very important.
Example
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation:
Python Comments
Example
Comments in Python:
#This is a comment.
print("Hello, World!")
Docstrings
Python uses triple quotes at the beginning and end of the docstring:
Example
"""This is a
multiline docstring."""
print("Hello, World!")
Python Variables
When we create a program, we often like to store values so that it can be used later.
Creating Variables
Unlike other programming languages, Python has no command for declaring a variable.
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)
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:
Functions
Print
Example
x = "awesome"
print("Python is " + x)
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z= x+y
print(z)
If you try to combine a string and a number, Python will give you an error:
Example
x=5
y = "John"
print(x + y)
Type
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Python Casting
There may be times when you want to specify a type on to a variable. This can be done with
casting.
Python Numbers
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
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))
Complex
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
IF
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.
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".
Elif
The elif keyword is pythons 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")
Python Strings
In python, consecutive sequence of characters is known as a string. An individual character in a
string is accessed using a subscript (index). The subscript should always be an integer (positive
or negative). A subscript starts from 0.
# Declaring a string in python
>>>myfirst=“Save Earth”
>>>print myfirst
Save Earth
Let’s play with subscripts
To access the first character of the string
>>>print myfirst[0]
To access the fourth character of the string
>>>print myfirst[3]
e
To access the last character of the string
>>>print myfirst[-1]
>>h
To access the third last character of the string
>>>print myfirst[-3]
r
Consider the given figure
while loops
for loops
Example
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
The while loop requires relevant variables to be ready, in this example we need to define an indexing
variable, i, which we set to 1.
Example
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Python Functions
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.
The following example has a function with one parameter (fname). When the function is called, we
pass along a first name, which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Return Values
To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
PYTHON SAMPLE CALCULATOR- Procedure 1 with return statement
# Program make a simple calculator that can add, subtract, multiply and
divide using functions
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Quotient")
print("5.Remainder")
if choice == '1':
print(num1,"+",num2,"=", add(a,b))
else:
print("Invalid input")
def Add(x,y):
c= x+y
print("The sum of two numbers is",c)
def Subtract(x,y):
c= x-y
print("The difference of two numbers is",c)
def Multiply(x,y):
c= x*y
print("The product of two numbers is",c)
def Quotient(x,y):
c= x//y
print("The Quotient after dividing two numbers is",c)
def Remainder(x,y):
c= x%y
print("The remainder after dividing two numbers is",c)
print ("1.Addition")
print ("2.Subtraction")
print ("3.Multiplication")
print ("4.Quotient of Division")
print ("5.Remainder of Division")
print("Enter the Choice of Arithemetic Operation as 1/2/3/4/5")
ch=int(input())
print("Enter the first number")
a=int(input())
print("Enter the Second number")
b=int(input())
if (ch==1):
Add(a,b)
elif(ch==2):
Subtract(a,b)
elif(ch==3):
Multiply(a,b)
elif(ch==4):
Quotient(a,b)
elif(ch==5):
Remainder(a,b)
else:
print(" Invalid Choice")