Python For Grade 8 PDF

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

Contents

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.

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 perform complex mathematics.

Why Python?

 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 was designed to 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.

Working with Python using Jupyter

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

Python uses indentation to indicate a block of code.

Example
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation:

Python Comments

Python has commenting capability for the purpose of in-code documentation.


Comments start with a #, and Python will render the rest of the line as a comment:

Example

Comments in Python:

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

Docstrings

Python also has extended documentation capability, called docstrings.

Docstrings can be one line, or multiline.

Python uses triple quotes at the beginning and end of the docstring:

Example

Docstrings are also comments:

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

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

Remember that variables are case-sensitive

It is a good practice to follow these identifier naming conventions:

1. Variable name should be meaningful and short

2. Generally, they are written in lower case letters

Functions
Print

The Python print statement is often used to output variables.

To combine both text and a variable, Python uses the + character:

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)

For numbers, the + character works as a mathematical operator:


Example
x=5
y = 10
print(x + y)

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.

Casting in python is therefore done using constructor functions:

 int() - Converts, a float literal, or a string literal to an integer


 float() - Converts, a float number from an integer literal, a float literal or a string literal to
a float
 str() - Converts, wide variety of data types, including strings, integer literals and float
literals into strings
String methods & built in functions
Data type
It is a set of values, and the allowable operations on those values.
It can be one of the following:
1. Number
2. Sequence
3. Sets
4. Mapping
5. Dictionaries

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

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

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.

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

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

Important points about accessing elements in the strings using subscripts


 Positive subscript helps in accessing the string from the beginning
 Negative subscript helps in accessing the string from the end.
 Subscript 0 or –ve n(where n is length of the string) displays the first element.
Example : A[0] or A[-5] will display „H‟
 Subscript 1 or –ve (n-1) displays the second element.
Creating and initializing strings
A literal/constant value to a string can be assigned using a single quotes, double quotes or triple
quotes.
Enclosing the string in single quotes Example
>>>print („A friend in need is a friend indeed‟)
A friend in need is a friend indeed
Escape Sequence
An escape sequences is nothing but a special character that has a specific function

Strings are immutable


Strings are immutable means that the contents of the string cannot be changed after it is created.
Let us understand the concept of immutability with help of an example.
Example
>>>str='honesty'
>>>str[2]='p'
TypeError: 'str' object does not support item assignment
Python does not allowthe programmer to change a character in a string. As shown in the above
example, str has the value „honesty‟. An attempt to replace „n‟ in the string by ‟p‟ displays a
TypeError.
Strings Operations
Operator Description Example
Python Loops
Python has two primitive loop commands:

while loops
for loops

The while Loop


With the while loop we can execute a set of statements as long as a condition is true.

Example
Print i as long as i is less than 6:

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

Note: remember to increment i, or else the loop will continue forever.

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.

The break Statement


With the break statement we can stop the loop even if the while condition is true:

Example
Exit the loop when i is 3:

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

The continue Statement


With the continue statement we can stop the current iteration, and continue with the next:
Example
Continue to the next iteration if i is 3:

i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

Python Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

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

# This function adds two numbers


def add(x, y):
return x + y

# This function subtracts two numbers


def subtract(x, y):
return x - y

# This function multiplies two numbers


def multiply(x, y):
return x * y

# This function divides two numbers


def quotient (x, y):
return x / y
def remainder (x, y):
return x % y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Quotient")
print("5.Remainder")

# Take input from the user


choice = input("Enter choice(1/2/3/4):")

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))

if choice == '1':
print(num1,"+",num2,"=", add(a,b))

elif choice == '2':


print(num1,"-",num2,"=", subtract(a,b))

elif choice == '3':


print(num1,"*",num2,"=", multiply(a,b))

elif choice == '4':


print(num1,"/",num2,"=", quotient(a,b))
elif choice == '5':
print(num1,"/",num2,"=", remainder(a,b))

else:
print("Invalid input")

PYTHON SAMPLE CALCULATOR- Procedure 2 without return statement


# Program make a simple calculator that can add, subtract, multiply and
divide using functions

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

You might also like