0% found this document useful (0 votes)
28 views73 pages

Grade-9 - PYTHON Programming

The document provides an introduction to Python, covering its features, limitations, and various programming concepts such as data types, statements, and user input. It explains Python's versatility in web development, software development, and data handling, highlighting its readability and ease of use. Additionally, it discusses programming methodologies like algorithms and flowcharts, along with practical examples and exercises for better understanding.
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)
28 views73 pages

Grade-9 - PYTHON Programming

The document provides an introduction to Python, covering its features, limitations, and various programming concepts such as data types, statements, and user input. It explains Python's versatility in web development, software development, and data handling, highlighting its readability and ease of use. Additionally, it discusses programming methodologies like algorithms and flowcharts, along with practical examples and exercises for better understanding.
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
You are on page 1/ 73

● Introduction to PYTHON

● Features of Python
● Limitations of Python
● Working with Python
● Python Tokens
● Data-types in Python
● Statements in Python Programs
● Expressions in Python
● Accepting User Input and Displaying Output in Python
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.
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.
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.
How a Program is Developed ?

Every machine, whether AI enabled or not, follows a particular path of


action.
It goes through exact specific steps which have been programmed into
it to accomplish the given task.

For example, a washing machine.


Can you think of possible steps to wash clothes in a washing machine?
What else it can do ?
A washing machine can wash clothes for us and not
do anything else because it is designed explicitly for
this task. It follows the steps programmed into it
and completes the work.

Ever wo
ndered
create s how do
uch prog people
rams?
To develop a program,
❖ The very first step that comes into the picture is to specify the
task which the machine needs to do.
❖ Once the task or the main objective of the program is finalized, the
task is broken into smaller tasks.
❖ Finally all together contribute towards achieving the main goal.

How to make sure that the flow of the process is proper ?

Algorithms and flowcharts are used which help us into developing a


stepwise framework to achieve the main goal.
● Algorithms - step-by-step method to solve the identified
problem

● Flowchart - Pictorial representation of a process.

● Pseudocode - informal way of programming description that


does not require any strict programming language syntax
Steps to make any instant noodles

Can you think of other ways to make instant noodles? Write them down.
Write algorithms for the challenges given.
Conclusion:

Through this activity, we understood:


1. How to divide a task into several sub-tasks and
the advantage of doing so.
2. There can be multiple approaches in terms of the number of
sub-tasks or the methods used in sub-tasks to solve a problem.
3. The one which is the simplest and the most efficient should be
chosen above all.
n Box
cis i o
g D e
Usin
Try it out

1. Draw a flowchart to find the sum of first 100 natural numbers.

2. Draw a flowchart to accept two numbers in two variables and


print them by swapping their values.
Eg: In Input if a = 5 b = 6 then
Output a=6 b=5
https://www.python.org/downloads/
Introduction to Python
● Comments in Python

● Python Tokens

● Data-types in Python

● Statements in Python Programs

● Expressions in Python

● Accepting User Input and Displaying Output in Python

● Some Simple Programs


Comments

# - Single line comment

“”” ………………….
………………….. “”” - Multi line comments

A comment is text that doesn't affect the outcome of a code, it is just a piece of text to
let someone know what you have done in a program or what is being done in a block
of code.
Keywords are the
reserved words in
Python used by
Python interpreter to
recognize the
structure of the
program.
Identifiers
Literals:
1. Numeric Literals
● Integers ( 23, -45)
● long int with unlimited size.
● Floating point - decimal values
● Complex literals - 2+3j
complex([real[, imag]])
x = complex(2,3)
>>>print(x)
>>>(2+3j)
2. Character Literals - ‘ ‘ or “ “ - ‘a’,’4’,’#’
3. String Literals - Single,Double & Triple quotes
4. Boolean Literals - True or False
print(bool("Hello")) -> True
>>> print(10 > 9) -> True
print(bool(15)) -> True
>>>print(10 == 9) -> False
print(bool()) -> False

● Almost any value is evaluated to True if it has some sort of content.


● Any string is True, except empty strings.
● Any number is True, except 0.
● Any list, tuple, set, and dictionary are True, except empty ones.
5. Special Literals - none - used to define a null variable.
If ‘None’ is compared with anything else other than a ‘None’, it will return false.

Eg: a=none print(a)

6. Collection Literals:
● List collections - [abc,xyz,pqr]
● Tuple collection - (23,56,89)
● Dictionary collections
{‘a’:”apple”,’b’:”ball”,’c’:”cat”}
● Set collections {‘a’,’b’,’c’}
Python Operators -
❖ Operators are special symbols which represent computation.

❖ Operators are categorized as Arithmetic, Relational, Logical and Assignment.

❖ Value and variables when used with operator are known as operands.
Arithmetic Operators

3000
3.0
Conditional Operators
Logical Operators
Assignment Operators
Statements in python
Output Statements -
print(“hello python”)
print(a)
print(23,45,36)
print(“The value is “, a)
x=”python” print(“This is “ + x)
Input statements -
String:
a=input(“enter your name:”)
b=input(“enter your grade:”)

Numeric:
1. a=int(input(“Enter the value of a:”))

2. print(“Enter the value of a :”)


a=int(input( ))
Sample Program
Type - 1 Type - 2

print("Enter a value") a=int(input("Enter a value"))

a=int(input( ) ) b=int(input("Enter b value"))

print("Enter b value") c=a+b

b=int(input( ) ) print("The result is ",c)

c=a+b

print("The result is ",c)


Write a Python program to print the following string in a specific format.

Twinkle, twinkle, little star,

How I wonder what you are!

Up above the world so high,

Like a diamond in the sky.

Twinkle, twinkle, little star,

How I wonder what you are


print(“Twinkle, twinkle, little star,”)

print(“ How I wonder what you are! “)

print(“ Up above the world so high,”)

Like a diamond in the sky.


Now try the same program with single print
statement.

How did you do it ? Discuss


print(“Twinkle, twinkle, little star,”)

print(“ How I wonder what you are! “)

print(“ Up above the world so high,”)

Like a diamond in the sky.

print(“Twinkle, twinkle, little star, \n \t How I wonder what you are! \n \t \t


Up above the world so high,\n \t \tLike a diamond in the sky. …………… “)
1. Write a Python program to display your name and
grade.
2. Write a Python program to assign values of 4
variables and show their addition on the screen.
3. Write a Python program to accept 3 numbers and
show their product on the screen.
4. Write a Python program to convert Celsius
measurement to Fahrenheit. (c*9/5)+32
5. Write a Python program to find the area of a triangle
by accepting required values.
More about Variables
● Variables are containers for storing data
● Like other programs, No declaration required for variables.
● A variable is created the moment user just assign a value.
● Variable names are case sensitive (name,Name,NAME,NamE)

Try the examples: a=5 A=5 x=a+A


1. Assigning values to variables - a=5,b=6.7

2. Assigning different values to multiple variables -

a,b,c=5,6.7,”APPLE”

3. Assigning same values to multiple variables - a=b=c=10

4. type( ) function - type(b) = class float

5. Type conversion (Casting) - x=float(a); x=5.0 / z=int(b) z= 6

6. Random numbers - randint(1,100)


import random
a=random..randrange(34,100 )
print(a)

from numpy import random


x=random.randint(100)
print(x)
x,y,z="car",4,6.8

a=b=c=5
a=int(z)
print(x) print(a) 6

print(y)
print(float(y)) 4.0
print(z)

print(a,b,c)

print(type(x))

print(type(c))

print(type(z))
Try it out….
Declare 5 variables in a single line declaration, with numeric whole numbers for
first 2 and decimal value for the 3rd variable. The 4th & 5th variable should be
string value.

1. Multiply the 1st & 3rd variable and display the output.
2. Concatenate the 4th & 5th variable and display the output.
3. Combine the 1st and 5th variable and display the output.
4. Convert the decimal variable to a whole number and display.
5. Convert the 2nd variable into a decimal value and display it with its datatype.
Conditional Statements
● While coding in Python, a lot of times we need to take decisions.
● In this case, we need the machine to understand what should happen when.
This is where conditional statements help.
● Conditional statements help the machine in taking a decision according to
the condition which gets fulfilled.
There exist different types of conditional statements in Python.

According to the number of conditions and their dependency on each other, the relevant type of
conditional statement is used.
If statement in PYTHON

if condition : if condition 1 :
Stmt 1 Stmt 1….
elif condition 2 :
Stmt 2…
elif condition 3:
Stmt 3…
If condition : else:
Stmt ...
Stmt 1...

else :

Stmt 2 ….
Example - If statement in PYTHON
#if statement
a=(input("Enter ur choice"))
a=50,b=10
if a == "pizza" :
if a>b: print("\n You have ordered pizza")
print(a) elif a== "burger":
else: print("\n You have order burger")

print(b) else :
print("\n Pls order again")
Example - If statement in PYTHON

ch=input("Enter any character")


vow="aeiouAEIOU"
if ch in vow:
print("\n Entered character is vowel")
else:
print("\n Entered character is not vowel")
Shorthand if

print( ...) if condition else print (....)

print( ...) if condition else print (....) if condition else print (...)

# 3 conditions example
a=8001
b=8008

print("a >") if a>b else print ("equal") if a==b else print("b >")

Link
Logical AND & OR in if stmt

If a>b and a>c:


print(“Both conditions are True”)
else :
print(“One condition is True or Both False”)

a=7,b=69,c=80
if a>b and c>a:
print("c is >")
else:
print("*****")

Link
❏ Accept the age of a person and check whether the person is a senior citizen or not.

❏ Write a program to display "Hello" if a number entered by user is a multiple of five,


otherwise print "Bye"

❏ Write a program to check whether an years is leap year or not.

❏ A company decided to give bonus to employee according to following criteria:


Time period of Service Bonus
More than 10 years 50%
>=6 and <=10 years 30%
Less than 6 years 10%
Ask user for their salary and years of service and print the net bonus amount.
age=int(input("Enter ur age: "))

if age>=60:

print("you are a Senior Citizen")

else:

print("you are not a Senior


Citizen")
“Program to calculate Electricity bill”
Program Explanation - Write a Python program to calculate Electricity Bill by accepting
necessary data (Refer Output) from the user. A sample bill appearance of how the output
should be is given for your reference.

1. If the unit consumed is less or equal to 100 units, calculates the total amount of consumed
= units*1.5
2. If the unit consumed between 100 to 200 units, calculates the total amount of consumed
=(100*1.5)+(unit-100)*2.5
3. If unit consumed between 200 to 300 units, calculates total amount of consumed
=(100*1.5)+(100*2.5)+(units-200)*4
4. If unit consumed between 300-400 units, calculates total amount of consumed
=(100*1.5)+(100*2.5)+(100*4)+(units-300)*5
5. If unit consumed is > 400 units, calculates total amount of consumed
=(100*1.5)+(100*2.5)+(100*4)+(100*5)+(units-400)*8
Condition for Meter charges apply

if units<=100, Meter charges = Rs. 25.00

if units > 100 and units <=200, Meter charges = Rs.50.00

if units > 200 and units < =300, Meter charges = Rs.75.00

if units > 300 and units < =400, Meter charges = Rs.100.00

if units above 400, No Meter charges (Rs.00) but Standard Additional charge of
Rs.500/- is applicable.
~~~~~~~~~Tamil Nadu Electricity Board~~~~~~~~~~~

Coimbatore District
Date:
p le Consumer no:2324255
a m ut Name: Shiva
S tp Units consumed: 500
Ou r nce …………………………………………………………………………………………………….
o
F fer e Unit Charges in Rs : xxxx
re Meter Charges in Rs: 75
Additional charge in Rs: 500

Total Amount in Rs: XX75

*****Save Electricity*****
Loops in Python
● while loops
● for loops
Python programming language provides above types
of loops to handle looping requirements.

While all the ways provide similar basic


functionality, they differ in their syntax and
condition checking time.
While Loop
Syntax:

while expression : Example:


Output:
statement(s) i=1
1
while i < 5:
2
print(i)
3
i +=1
4

It is important to increment the initialization value or else the looping continues.


While Loop with else
Syntax: Example:
Output:
while expression : i=1
1
while i < 5:
statement(s) 2
print(i)
else : 3
i +=1
Statement 2 4
else :
Loop completed
print(“Loop completed”)

It is important to increment the initialization value or else the looping continues.


While Loop with break
Syntax:
Example:
while expression :
i=1 Output:
statement(s)
while i < 5: 1
condition :
print(i) 2
break
if i == 3: 3
break
i +=1

It is important to increment the initialization value or else the looping continues.


While Loop with continue
Syntax: Example:
while expression : i=0
Output:
statement(s) while i < 5:
1
condition : i += 1
2
continue if i == 3:
4
continue
5
print(i)

It is important to increment the initialization value or else the looping continues.


For Loop Example: Output:

for x in “Hai”: H
Syntax:
print(x) a
for var in iterable:
i
# statements fruits = ["apple", "banana", "cherry"]
apple
for x in fruits:
banana
print(x) cherry

1
nos=[1,2,3,4,5]
2
for x in nos: 3
print(x) 4
5
Can you try creating….

for loop with “else” , “break” and “continue” statements

Keeping while loop examples.


fruits = ["apple", “mango”,"banana", "cherry"] fruits = ["apple", “mango”,"banana", "cherry"]

for x in fruits: for x in fruits:


if x == “banana”: if x == “banana”
break continue
print(x) print(x)

Output: Output:

apple apple

mango mango

cherry
for loop with range( ) Function
for x in range(5): for x in range(5):
Output:
print(x) if x == 3
0

else: break 1

2
print("Loop Completed") print(x)

else:

Output: print("Loop Completed")


0

3 What difference do you find


between both for loop O/P ?
4
Why ?
Loop Completed
for loop with range( ) Function
for x in range(10): for x in range(2, 10): for x in range(2, 21, 3):

print(x) print(x) print(x)

Output: Output: Output:


2
0 2
5
1 3
8
2 4
11
3 5
14
4 6
17
5 7

6 8

7 9

9
Nested for loop

Output:
no = [1,2,3,4] 1 apple

1 banana
fruits = ["apple", “banana", "cherry"]
1 cherry

for x in no: 2 apple

2 banana
for y in fruits:
2 cherry
print(x,y) 3 apple

3 banana

3 cherry

4 apple

4 banana

4 cherry

You might also like