0% found this document useful (0 votes)
5 views31 pages

G8 - Python Tutorials - v3

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 31

Version 3.

0 1
1. Introduction................................................................................................................................ 4
2. Python basics.............................................................................................................................. 5
Python Variables...............................................................................................................................5
Data types in Python........................................................................................................................ 6
Integer (int)................................................................................................................................ 6
Float (float)................................................................................................................... 6
String (str).................................................................................................................................. 6
List..............................................................................................................................................6
Input/output statements..................................................................................................................8
How to print values/variables in Python?..................................................................................8
How to read input values in Python?.........................................................................................9
Arithmetic operators in Python...................................................................................................... 10
4. Python Control Flow.................................................................................................................. 12
Conditional Statements.................................................................................................................. 12
if – else statement....................................................................................................................12
if-elif-else statement................................................................................................................ 13
Iterative statements (Loops)...........................................................................................................16
For loop....................................................................................................................................16
While Loop............................................................................................................................... 19
5. Python Lists............................................................................................................................... 20
Create a List.................................................................................................................................... 20
Iterating through a List................................................................................................................... 21
6. Python functions....................................................................................................................... 22
User-defined functions................................................................................................................... 22
Writing a function.................................................................................................................... 22
Calling a function..................................................................................................................... 22
Calling a function (With parameters).......................................................................................23
Returning a value from a function........................................................................................... 24
Actual and formal parameters:................................................................................................ 25
Built-in functions............................................................................................................................ 27
String functions........................................................................................................................27
List functions............................................................................................................................29
Random functions....................................................................................................................31
References.................................................................................................................................... 32

Version 3.0 2
1. Introduction
Python is an easy-to-understand and good-to-start programming language.

Why Python for Beginners?


The main reason for a beginner to start with Python is the simplicity and versatility of
Python. It makes it an ideal language for students to start their coding journey.

Python Syntax
Python syntax refers to the set of rules and conventions that dictate how Python
code should be written in order for it to be interpreted correctly by the Python
interpreter. It defines the structure and formatting of Python programs.

Python code is written as a sequence of statements. Each statement represents an


action or a command. For example, assigning a value to a variable, calling a
function, or defining a loop are all examples of statements.

My first Python program

print(“Hello World”)

Output
Hello World

The above program uses print() statement in Python. This statement prints the
string or variable that is given within the brackets.

Version 3.0 3
2. Python basics
Python Variables

If we have to store something in our real life, we need a container or box to store
this. Variables are nothing but simple containers to store data of different types like
numbers, strings, boolean, chars, lists, tuples, ranges etc.
Let us focus on the data types numbers and strings for now.
* string is a sequence of characters
Example: Declaring and using a variable
my_number = 10
print(my_number)

name = "Jack”
print(name)

Output
10
Jack

In the first two lines, the above program stores a number (value 10 in this case) in a
variable my_number. It prints the value stored in the variable my_number using
print() statement.

In the last two lines, the above program stores a string in a variable name. It prints
the value stored in the variable name using print() statement.

Here are some of the rules mentioned that you must consider before naming a
Python variable:
● A Python variable name must start with a letter or the underscore character.
● A Python variable name cannot start with a number.
● A Python variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
● Variable names in Python are case-sensitive (name, Name, and NAME are three
different variables).
● The reserved words (keywords) in Python cannot be used to name the variable in
Python.

Version 3.0 4
Data types in Python

Integer (int)
An integer represents whole numbers without decimals.
For example, our age, if someone asks us about our age, we generally give the
answer in numbers (without decimals) like 18, 21, 11, etc.

my_number = 10
print(my_number)

Float (float)
A float represents decimal numbers.
For example, price Rs.30.75, duration - 1.5 hours

my_number = 10.5
print(my_number)

String (str)
A string represents a sequence of characters or alphabets. It can be used to store
text-based information. The string is like a collection of letters, words, or sentences.
For example, a person’s name can be stored as a string. String values are assigned
to variables using double quotes or single quotes.

myname = "Jack Reicher”


print(myname)

List
A list is a collection of items. It can be used to store multiple values of the same or
different data types. A list is like a collection of items in a basket. It can contain
different things, such as numbers, words, or even other lists.
Version 3.0 5
Example: List of numbers, List of names, List of marks etc.

numlist=[10,22,3,45,7,8,9]
print(numlist)

chocs=[“nestle”,”amul”,”parle”,”cadbury”]
print(chocs)

There are other data types such as boolean, float, tuple, dictionary, set. We will learn
about them later.

Version 3.0 6
Input/output statements

How to print values/variables in Python?

print() function is used in Python to print the value to the screen/display.

Example-1: To print any message/string on the display.


print(“Hello everyone”)
print(“My name is Benny”)

Note: The message/string to be printed should be enclosed in double quotes or


single quotes.

Example-2: To print values of variables


num = 10
print(num)

myname=”Jack”
print(myname)

Example-3: To combine messages and values of variables


num = 10
print(“Value of num=”, num)
myname=”Jack”
print(“Welcome to python world Mr.”, myname)

a=10
b=15
print(“a=”,a,”b=”,b)

Note: The string of characters enclosed in the double quotes will be printed as it is.
The variables are replaced with the corresponding values. Also note that different
items can be separated by commas (,).

Version 3.0 7
How to read input values in Python?

So far we have been assigning values to variables inside the program. We use the
input() function to read values given by the user.

Example-1: To read a string value from the user.


movie= input(“Enter your favourite movie:”))
print(“you like the movie ”, movie)

● Using the input() function, the above program will read a string and store it
in the variable ‘movie’.
● The print() function will display it on the screen with a message “You like
the movie:”

Example-2: To read an integer (int) value from the user.


num= int (input(“Type a number:”))
print(“you typed ”,num)

The above program will read an integer (whole number) from the user and print the
number on the display. Note the int() used before the input() function. This will
actually convert and store the entered number as integer in the variable num.
The print() function will display it on the screen with a message “You typed ”

Example-3: To read a decimal value (float) value from the user.


num= float (input(“Type a number:”))
print(“you typed ”,num)

The above program will read a float (decimal number) from the user and print the
number on the display. Note the float() used before the input() function. This
will actually convert and store the entered number as integer in the variable num.
The print() function will display it on the screen with a message “You typed ”

Version 3.0 8
Arithmetic operators in Python

Python provides the following arithmetic operators for calculations.

The following examples explain a few of the operations.


Addition operator (+)
Example-1:
num1= int(input(“Type a number:”))
num2= int(input(“Type another number:”))
sum = num1 + num2
print(“Sum is ”, sum)

● There are three variables in this program. They are num1, num2 and sum.
● Using the input() function, the above program will read two numbers from
the user and store the values in the variables ‘num1’ and ‘num2’.
● The line sum = num1 + num2 adds the numbers and stores the value in the
variable ‘sum’.
● The print() function prints the value of ‘sum’ with a message “sum is”.

Version 3.0 9
Multiplication operator (*)
Example-2:
num1= int(input(“Type a number:”))
num2= int(input(“Type another number:”))
prod = num1 * num2
print(“Product is ”, prod)

Modulus operator (%)


Example-3:
Print(“Modulus is remainder after division”)
num1= int(input(“Type a number:”))
num2= int(input(“Type another number:”))
mod = num1 % num2
print(num1,”%”,num2, “=”, mod)

In Python, % is called the modulus operator. This gives the remainder after division.
(e.g.) a = 15 % 2, stores the value 0 in the variable ‘a’
(e.g.) a = 14 % 3, stores the value 2 in the variable ‘a’

Floor division operator (//)


Example-4:
Print(“Floor division gives quotient of the division”)
num1= int(input(“Type a number:”))
num2= int(input(“Type another number:”))
q = num1 // num2
print(“Quotient=”, q)

In Python, // is called the floor division operator. This gives the quotient (whole
number) after division.
(e.g.) a = 15 // 2, stores the value 7 in the variable ‘a’
(e.g.) a = 15 // 4, stores the value 3 in the variable ‘a’

Note: ‘/’ is a division operator that returns a decimal value as quotient.


Version 3.0 10
4. Python Control Flow
In programming, control flow refers to the order in which the code is executed. It
determines how the computer goes through different parts of the code based on
certain conditions.
There are two types of control flow:
- Conditional
- Iterative (Repetition)

Conditional Statements
Conditional statements allow the computer to make decisions based on conditions. It
checks if a certain condition is true or false and executes different blocks of code
accordingly.

if – else statement
Python uses an ‘if’ statement to control the flow of execution of the program.

if Statement: use it to execute a block of code, if a specified condition is true

else Statement: use it to execute a block of code, if the same condition is false

Example-1:
X = 7
y = 5
if (x > y):
print('x is greater')
else:
print(‘y is greater’)

In the above example, (x > y) is a condition. Depending upon the value of ‘x’ and ‘y’
this condition will be evaluated to ‘true’ or ‘false’.

Version 3.0 11
if-elif-else statement

Example-2:
x = 5
y = 5
if x > y:
print('x is greater')
elif x < y:
print('y is greater')
else:
print('x and y are equal')

In the above example, (x > y) and (x < y) are conditions. Depending upon the value
of ‘x’ and ‘y’ these conditions will be evaluated to ‘true’ or ‘false’.
If a condition is ‘true’ then the corresponding code under that condition will be
executed. Otherwise the next condition in elif is evaluated and so on and so forth.
If none of the conditions are ‘true’ then the code in the ‘else’ part will be executed.

Significance of Indentation

Moreover, Python uses indentation to define code blocks. Unlike other


programming languages that use braces or keywords, Python uses indentation to
indicate the start and end of blocks of code. Typically, four spaces or a tab is used
for indentation.
Indentation has a special significance in Python. It is used to define a block of
code. Contiguous statements that are indented to the same level are considered
as part of the same block.

Version 3.0 12
Relational Operators
If-else statements require conditions. These conditions can be formed using
relational operators. They are also called comparison operators.

You can use following comparison operators to compare two values as given in the
examples:

Comparison operators with if statement

Operator Meaning Example

== Equals if x == y

!= Not equals if x != y

> Greater than if x > y

>= Greater than or equal to if x >= y

< Less than if x < y

<= Less than or equal to if x <= y

Version 3.0 13
Logical Operators
If-else statements require conditions. Logical operators are used to combine two or
more conditions. Python has the following logical operators.

Operator Description Syntax Example


and Returns True if both x and y x>7 and x>10
the conditions are
true

or Returns True if x or y x<7 or x>15


either of the
condition is true

not Returns True if the not x not(x>7 and x> 10)


condition is false

Example-1:
x = 5
y = 5
z=10
if x > y and x > z:
print('x is greater')
elif y > x and y > z:
print('y is greater')
else:
print('z is greater')

Example-2:
inp_ch = “e”

if inp_ch == ‘a’ or
inp_ch == ‘e’ or
inp_ch == ‘i’ or
inp_ch == ‘o’ or
inp_ch == ‘u’ :
print(“The character is a vowel”)
else:
print(“The character is a consonant”)

Version 3.0 14
Iterative statements (Loops)
Loops allow the programs to repeat a block of code multiple times.

For loop
A for-loop is used to repeat a block of code, a specific number of times.

Syntax
for variable in range(start,end,[,skip]):
block of statements
range( ) function
The range() function can be used in combination with the ‘for’ loop to generate a
sequence of numbers and to execute the block of code for each value generated.
The following are the variations of range( ) statement

*argument - the number of values passed to the range( ) function.

When the ‘for’ loop is used in combination with the range() function, the block of
code under the ‘for’ loop will be executed once for each value generated in the
sequence. The following diagram illustrates how a ‘for’ loop functions.

Version 3.0 15
Example-1
for i in range(5)
print(“Hello”)

Output
Hello
Hello
Hello
Hello
Hello
In the above example,
● range() function generates values from 0 to 4.
● Each value is assigned to the variable ‘i’.
● For each value of ‘i' the print() statement indented under the ‘for’ statement will
be executed once.
● So the print() statement is executed 5 times.
● If there are more than one statement (block) indented under the ‘for’ statement then
all the statements are executed for each value of ‘i'.
Example-2
for i in range(1,5)
print(“Hello”,i)

Output
Hello 1
Hello 2
Hello 3
Hello 4
In the above example,
● range(1,4) function generates values starting from 1 to 4.
● Each value is assigned to the variable ‘i’.
● For each value of ‘i' the print( ) statement indented under the ‘for’
statement will be executed once.
● So the print( ) statement is executed 4 times.
● If there are more than one statement (block) indented under the ‘for’
statement then all the statements are executed in sequence for each value of
‘i'.
Version 3.0 16
Example-3
for i in range(1,10,2)
print(i)

Output
1
3
5
7
9

In the above example,


● range(1,10,2) function has 3 values. The first value gives the starting
value, second value is the ending value of the sequence and the third value
gives the value to be added to the current value after processing the
statements in the block.
● Each value is assigned to the variable ‘i’. (1, 3, 5, 7, 9)
● For each value of ‘i' the print(i) statement indented under the ‘for’
statement will be executed once.
● So the print() statement is executed 5 times.
● If there are more than one statement (block) indented under the ‘for’
statement then all the statements are executed in sequence for each value of
‘i'.

Version 3.0 17
While Loop
A while-loop is used to repeat a block of code as long as a certain condition is true.
Syntax
while condition:
block of statements
Example-1:
count=0
while count < 5:
print(count)
count = count + 1

Output
0
1
2
3
4
In the above example,

● The while loop checks the condition.


● If the condition evaluates to True, the block of code inside the while loop is
executed.
● Condition is checked again.
● This process continues until the condition is False.
● When condition evaluates to False, the loop stops.
Example-2:
count=5
while count <=25 :
print(count)
count = count + 5

Output
5
10
15
20
25

Version 3.0 18
5. Python Lists
Lists are types of collections in Python. Lists are used to store multiple data at once.
Each data in the list is called an ‘item’.

Suppose we need to record the ages of 5 students. Instead of creating 5 separate


variables, we can simply create a list.

Create a List
We create a list by placing elements inside [ ] separated by commas. For example,

Example-1
ages =[12,8,7,22,5]
print(ages)

Output
[12,8,7,22,5]

The above example creates a list of ages and prints the same

Example-2
names =[“jack”,”jill”,”rick”,”Marty”]
print(ages)

Output
[jack,jill,rick,Marty]

The above example creates a list of names (strings) and prints the same. Note that
each string is enclosed within double quotes.

Version 3.0 19
Iterating through a List
A for-loop can be used to iterate through each element in the loop. The block of code
is executed once for each item in the list.
Example-1
languages = ['English', 'French', 'Spanish']

for lang in languages:


print(lang)

Output
English
French
Spanish

The above example creates a list of languages (languages). For each iteration,
one item in the list is assigned to the variable ‘lang’ and the block of code is
executed once.

Example-2
agelist = [10,19,13,12,15]

for age in agelist:


if age > 12:
print(age)

Output
19
13
15

The above example creates a list to store age of students (agelist). For each
iteration, one item in the list is assigned to the variable ‘age’ . The program checks
and prints the ‘age’ only if age > 12. Other items are ignored.

Version 3.0 20
6. Python functions
User-defined functions
Functions are a convenient way to divide your code into useful blocks. Each block
can perform a particular task. This allows us to avoid duplication of code. The same
code can be reused multiple times in the same program or in a different program.

Writing a function
A function must be defined before it is used in a program.

Example-1:

def printHello():

print(“Hello friends”)

def - Keyword used to define a function

Function name - Name of the function used as a reference to execute the function.

Parameters - These are a set of values passed to the function as input. Parameters are optional and
used when needed.

Calling a function
Just defining the function will not execute the code under the function. The function should be called
explicitly inside your program using the ‘function name’ to execute the code defined under the
function. The following code will call the function defined in the previous example.

printHello()

Note: Both the function definition and call should be written in one program (.py) file.

Version 3.0 21
Calling a function (With parameters)
This example creates a function with the name sayHello. This function has one parameter
‘name’. The same function is called twice inside the program with different parameters each time.

Example-2

# function definition

def sayHello(name): #line-1

print(“Hello “,name) #line-2

# function calls

print(“Start of the program...”) #line-3

sayHello(“Roshan”) #line-4

print(“After first call”) #line-5

sayHello(“Dravid”) #line-6

print(“After second call”) #line-7

Output
Start of the program…
Hello Roshan
After first call
Hello Dravid
After the second call

1) When executing the program the code under the function definition (line#1 and line#2) will
not be executed. The line#3 prints the message “Start of the program…”.

2) line#4 is the function call to SayHello(). During this call, the value “Roshan” is passed to
the function (line#1) and assigned to the variable name. Inside the function the name is printed as
given in the print() statement(line#2) . The control will return to the statement after the function
call (line#5).

3) line#5 prints the message “After first call”.

4) line#6 is the next function call to sayHello(). During this call, the value “Dravid” is passed to
the function (line#1) and assigned to the variable name. Inside the function the name is printed as
given in the print() statement(line#2). The control will return to the statement after the function
call (line#7).

5)line7 prints the message “After the second call”.

Version 3.0 22
Returning a value from a function
A function can ‘return’ a value back to the function call. This is required in programs where the
output of the function is used after calling the function.

Syntax
return [variable/value]

Example-2

# function definition

def addNum(num1,num2): #line-1

sum = num1 + num2 #line-2

return sum #line-3

# function calls

print(“Beginning execution...”) #line-4

x=10 #line-5

y=20 #line-6

z = addNum(x,y) #line-7

print(“After first call...”) #line-8

print(“Sum =”,z) #line-9

c=addNum(15,25) #line-10

print(“After second call...”) #line-11

print(“Sum =”,c) #line-12

Output
Beginning execution…
After first call
Sum=30
After second call
Sum=40

Version 3.0 23
The above program is executed in the following sequence.

1) The program execution starts with line#4 that prints “Beginning execution…”. In line#5
and line#6 values are assigned to variables ‘x’ and ‘y’.
2) line#7 calls the function addNum() with values x and y. The values of ‘x’ and ‘y’ are
assigned to the parameters num1 and num2 in the function definition (line#1)
3) Line#2 calculates the sum of num1 and num2 and stores it in the variable sum.
4) Line#3 returns/sends the value of ‘sum’ to the calling program.
5) The returned value is assigned to the variable ‘z’ in line#7.
6) Line#8 and Line#9 print the following text.

After first call


Sum=30

7) line#10 calls the function addNum() with values ‘x’ and ‘y’. The values of 15 and
25 are assigned to the parameters num1 and num2 in the function definition (line#1)
8) Line#2 calculates the sum of num1 and num2 and stores it in the variable sum.
9) Line#3 returns/sends the value of ‘sum’ to the calling program.
10) The returned value is assigned to the variable ‘c’ in line#10.
11) Line#11 and Line#12 print the following text.

After second call


Sum=40

Actual and formal parameters:


The variables used in the function definition are called ‘formal parameters. The variables used in the
function call are called ‘actual parameters’.

During the function call, the values in the actual parameters will be assigned to the corresponding
formal parameters in the function definition.

In some programs, the actual parameters and formal parameters may use the same variable names.

Version 3.0 24
Here are a few examples. Take note of the following details.

● def keyword to define the function.


● Function name.
● Actual parameters
● Formal parameters

Example-3

def findAverage(a, b, c): #findAverage is the function name

sum = (a + b + c) # a, b and c are formal parameters

avg = sum / 3

return avg

m1=10

m2=20

m3=50

avg = findAverage(m1,m2,m3) #This is the function call

# m1, m2 and m3 are actual parameters

print(“Average Marks =”,avg)

Example-4

def getFullname(last, first): #getFullname is the function name

full_name= last +” “+ first #last and first are the formal parameters

return full_name

lname=”Pandya”

fname=”Hardik”

print(getFullname(lname,fname)) #This is the function call

#lname and fname are actual parameters

Version 3.0 25
Built-in functions
Python provides a lot of built-in functions that ease the writing of code. In this section, you will learn
about Python’s built-in functions, exploring their various applications and highlighting some of the
most commonly used ones. The functions are grouped into

● String functions
● List functions
● Random functions

String functions

Function Example
count() txt = "I love apples, apple are my
Counts the number of favorite fruit"
occurrences of a ‘word’ in the x = txt.count("apple")
given ‘string’. print(x)

Output:
2

This example counts the number of occurrences of the word


‘apple’ in the given string txt.

find() txt = "Hello, welcome to my world."


Checks whether the given ‘word’ x = txt.find("welcome")
occurs in the ‘string’ and returns print(x)
the position of the first character.
Output:
7

This example checks the occurrence of the word ‘welcome’ in


the string txt and returns the position of the first character.
The index starts with zero.

index() txt = "Hello, welcome to my world."


Returns the position of a ‘word’ x = txt.index("welcome")
in the given string. print(x)

Note: Position of the first Output:


7
character is 0.
This example checks the occurrence of the word ‘welcome’ in
the string txt and returns the position of the first character.

isalnum() txt = "Company12"


Checks if the given string contains x = txt.isalnum()
both alphabets and numbers. print(x)

Output:

Version 3.0 26
True
True - If the string contains either alphabets or numbers.

False - If the string contains special characters($,#,@, space


etc).

isalpha() txt = "CompanyX"


Checks if the given string contains x = txt.isalpha()
only alphabets. print(x)

Output:
True

True - If the string contains only alphabets.

False - If the string contains characters other than alphabets.


(numbers,special characters etc.,)

isdigit() txt = "50800"


Checks if the given string contains x = txt.isdigit()
only numbers. print(x)

Output:
True

True - If the string contains only numbers.

False - If the string contains characters other than numbers.


(alphabets,special characters etc.,)

islower() txt = "hello world!"


Checks if the given string contains x = txt.islower()
only lower case letters. print(x)

Output:
True

True - If the string contains only lower case letters.

False - If the string contains upper case letters.

replace() txt = "I like bananas"


Changes a ‘word’ in a string with
a different word. x = text.replace("bananas", "apples")

print(x)

Output:
I like apples

Version 3.0 27
The word ‘bananas’ in the string is replaced with the word
‘apples’.

upper() txt = "Hello my friends"


Convert the characters in a given x = txt.upper()
string to uppercase. print(x)

Output:
HELLO MY FRIENDS

List functions

append() fruits = ['apple', 'banana', 'cherry']


Adds an ‘item’ at the end of the
list. fruits.append("orange")
print(fruits)
Only one item can be added at a
time. Output:
['apple', 'banana', 'cherry',’orange’]

In this case ‘orange’ is added as the last item in the list.

clear() fruits = ['apple', 'banana', 'cherry',


Deletes all the items in the list. 'orange']
fruits.clear()
print(fruits)

Output:
[ ]

All items are removed from the list.

count() fruits = ['apple', 'banana', 'cherry']


Counts the number of
occurrences of an item in the x = fruits.count("cherry")
given list. print(x)

Output:
1

In this case, the search item is ‘cherry’ which occurs only


once in the list.

Version 3.0 28
index() fruits = ['apple', 'banana', 'cherry']
Returns the position of an item in
the list. (position starts with 0) x = fruits.index("cherry")
print(x)

Output:
2

In this case, the search item ‘cherry’ is at position 2 in the


list.

remove() fruits = ['apple', 'banana', 'cherry']


Removes/deletes an item from
the given list. fruits.remove("banana")
print(fruits)

Output:

['apple','cherry']

In this case, the item ‘banana’ is deleted from the list.

reverse() fruits = ['apple', 'banana', 'cherry']


Reverse the order of all the items
in the list. fruits.reverse()
print(fruits)

Output:

['cherry',’banana’,'apple']

sort() cars = ['Ford', 'BMW', 'Volvo']


Arranges all the items in the list in
ascending/alphabetical order. cars.sort()
print(cars)

Output:

['BMW',’Ford’,'Volvo']

Version 3.0 29
Random functions

randrange() import random


Randomly chooses any number print(random.randrange(3, 9))
within the given range.

In this case, the program will choose and print any number
between 2 and 8.

randint() import random


Randomly chooses any number print(random.randint(3, 9))
within the given range.

In this case, the program will choose and print any number
between 2 and 9.

choice() import random


Randomly chooses any item from mylist = ["apple", "banana", "cherry"]
the given list of items. print(random.choice(mylist))

In this case, the program will choose and print any one of
the items.

Built-in functions may require one or more parameters for the process.

Built-in functions will return a value which can be printed directly as output or it can be stored
in a variable for further processing.

Some built-in functions require importing modules in the program. For example, the following
statement must be used to import the random module before using any random functions.

import random

Version 3.0 30
References
https://www.w3schools.com/python/
https://www.geeksforgeeks.org/python-for-kids/
https://www.learnpython.org/
https://www.programiz.com/python-programming

Version 3.0 31

You might also like