G8 - Python Tutorials - v3
G8 - Python Tutorials - v3
G8 - Python Tutorials - v3
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.
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.
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.
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
myname=”Jack”
print(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.
● 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:”
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 ”
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
● 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)
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’
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’
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.
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
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:
== Equals if x == y
!= Not equals 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.
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
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
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,
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’.
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']
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]
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”)
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
# function calls
sayHello(“Roshan”) #line-4
sayHello(“Dravid”) #line-6
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).
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).
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
# function calls
x=10 #line-5
y=20 #line-6
z = addNum(x,y) #line-7
c=addNum(15,25) #line-10
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.
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.
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.
Example-3
avg = sum / 3
return avg
m1=10
m2=20
m3=50
Example-4
full_name= last +” “+ first #last and first are the formal parameters
return full_name
lname=”Pandya”
fname=”Hardik”
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
Output:
Version 3.0 26
True
True - If the string contains either alphabets or numbers.
Output:
True
Output:
True
Output:
True
print(x)
Output:
I like apples
Version 3.0 27
The word ‘bananas’ in the string is replaced with the word
‘apples’.
Output:
HELLO MY FRIENDS
List functions
Output:
[ ]
Output:
1
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
Output:
['apple','cherry']
Output:
['cherry',’banana’,'apple']
Output:
['BMW',’Ford’,'Volvo']
Version 3.0 29
Random functions
In this case, the program will choose and print any number
between 2 and 8.
In this case, the program will choose and print any number
between 2 and 9.
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