Ece Project3
Ece Project3
Naturally a language is the source of communication between two persons, language is used
to fallow sum instructions.
3. What is Coding?
Coding is a list of step by step instructions that get computers to do what you want them to do.
Coding makes it possible for us to create computer software, games, apps and websites.
Coders or Programmers behind everything we see and do on a computer.
4. What is Programming?
Programming is the process of creating a set of instructions that tell a computer how to
perform a task.
Programming can be done using a variety of computer programming languages such as
JavaScript, Python, and C++.
PROGRAMING LANGUAGES:-
1
translator in to machine level. A translator is software which is used to translate high level
languages to machine level languages.
History of Python
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. Guido Van Rossum is known as the founder of python programming.
It was created by Guido van Rossum during 1985- 1990.
2
Features of Python
1) Easy to Learn and Use
Python is easy to learn and use. It is developer-friendly and high level programming language.
2) Expressive Language
Python language is more expressive means that it is more understandable and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This
makes debugging easy and thus suitable for beginners.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh
etc. So, we can say that Python is a portable language.
6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come into
existence.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can
be used further in our python code.
3
8) Large Standard Library
Python has a large and broad library and provides rich set of module and functions for rapid
application development.
10) Integrated
It can be easily integrated with languages like C, C++, JAVA etc.
Python applications :
Web Applications
Enterprise Applications
Software Development Applications
Desktop GUI Applications
3D CAD Applications
Scientific and Numeric Applications
Image Processing Applications
Audio or Video-based Applications
Console-based Applications
Business Applications
Python versions:
Python Version Released Date
Python 1.0 January 1994
Python 1.5 December 31, 1997
Python 1.6 September 5, 2000
Python 2.0 October 16, 2000
Python 2.1 April 17, 2001
Python 2.2 December 21, 2001
Python 2.3 July 29, 2003
Python 2.4 November 30, 2004
4
Python 2.7 July 3, 2010
Flavors of Python
Flavors of Python simply refers to the different Python compilers. These flavors are useful to
integrate various programming languages into Python. Let us look at some of these flavors :
3. PyPy : This is the implementation using Python language. PyPy often runs
faster than CPython because PyPy is a just-in-time compiler while CPython is
an interpreter.
5
5. RubyPython : RubyPython is a bridge between the Ruby and Python
interpreters. It embeds a Python interpreter in the Ruby application’s process
using FFI (Foreign Function Interface).
Installation of Python
6
Double-click the executable file which is downloaded; the following window will open.
Select Customize installation and proceed.
The following window shows all the optional features. All the features need to be installed
and are checked by default; we need to click next to continue.
The following window shows a list of advanced options. Check all the options which you
want to install and click next. Here, we must notice that the first check-box (install for all
users) must be checked.
7
Now, we are ready to install python-3.6.7. Let's install it.
Now, try to run python on the command prompt. Type the command python in case of
python2 or python3 . It will show an error as given in the below image. It is because we
haven't set the path.
To set the path of python, we need to the right click on "my computer" and go to Properties
→ Advanced → Environment Variables.
8
Add the new path variable in the user variable section.
9
Type PATH as the variable name and set the path to the installation directory of the python
shown in the below image.
Example:
print(“Hello World”)
10
How to Run Python Programs
There are three way to execute python code they are given below;
Interactive Mode(Shell)
Script Mode(.py)
Using IDE
Whenever you are done in the python command line, you can simply type the following to
quit the python command line interface: exit()
Or by creating a python file on the server, using the .py file extension, and running it in the
Command Line:
C:\Users\Your Name>python myfile.p
Note: Python follows indentation. Indentation very important in python. If we not follow
indentation the program will not execute.
IDE
IDE is nothing but Integrated Development Environment. IDE is a tool that provides user
interface with compilers to create, compile and execute Java programs.
Python have its own platform with operating system like windows, Linux and Mac but it’s
difficult to work (complex) so we can use IDE.
These provide Integrated Development Environment with compiler for Python. Some of ides
are shown below
11
An integrated development environment (IDE) is a software suite that consolidates basic
tools required to write and test software.
Installation of VScode
1. Download vs code latest version from the browser. By searching vs code download.
12
Click on Next and Click on Install.
After successful installation go to settings and change the theme if you want, increase font
size as your wish and change auto save option to yes.
13
C vs Python:
C Python
C is a procedure-oriented Python is object oriented
programming language. programming language
C language does not contain the Python contain the features like
features like Class, object, Class, Object, Inheritance, etc.
inheritance, etc. In python datatype declaration is
In C language datatype declaration not required.
is compulsory. Python Only supports single
C supports single and multi- Dimensional Array. By using third
dimensional arrays. party like NumPy library we can
It works on Positive index only. run multi dim Array.
Pointer – yes It works on both positive and
C program execute faster.(compiler) negative index.
C supports Do while, switch. Pointer – no
C does not have Exception Python program are slower than
handling then programs are Weak. C.(dynamic typed
C should be responsible for variables)(interpreter)
allocate and deallocate memory. Python not supports Do-While,
switch. (we can use for else also)
Python have exceptions handling
then programs are robust.
In python memory allocation and
deallocation is done automatically
by PVM.
JAVA vs PYTHON:
JAVA
Java type declaration compulsory.
Java supports single and multi-dimensional arrays.
It works on Positive index only.
Java supports Do while, switch.
In Java memory allocation and deallocation is done automatically by JVM.
Python
In python datatype declaration is not required.
Python Only supports single Dimensional Array. By using third party like NumPy
library we can run multi dim Array.
It works on both positive and negative index.
Python not supports Do-While, switch. (we can use for else also)
14
In general, the interpreter reads and executes the statements line by line i.e sequentially.
Though, there are some statements that can alter this behavior like conditional statements.
Mostly, python statements are written in such a format that one statement is only
written in a single line. The interpreter considers the ‘new line character’ as the terminator of
one instruction. But, writing multiple statements per line is also possible that you can find
below.
Example:
print(“Hello World”)
Comments:
# I am single line comment
15
Tokens
Keywords in Python
Keyword is a predefined or reserved word in Python with a fixed meaning and used to
perform.
Every Keyword exists in lower case letter like auto, break, case, const, continue, int etc.
There are nearly 35 keywords in Python.
Identifier
Identifiers in Python are names given to different parts of a Python program like variables,
functions, classes, etc. They are user-defined and the users must follow a set of rules to define
them in a python program.
Literals
A literal in Python is a syntax that is used to completely express a fixed value of a specific
data type. Literals are constants that are self-explanatory and don’t need to be computed or
evaluated. They are used to provide variable values or to directly utilize them in expressions.
Types of Literals in Python
String literals
Character literal
Numeric literals
16
Boolean literals
String Literals
# in single quote
s = 'geekforgeeks'
# in double quotes
t = "geekforgeeks"
# multi-line String
m = '''geek
for
geeks'''
print(s)
print(t)
print(m)
Numeric Literals
Integer
Integer values can represent in 4 ways:
1. Binary (base 2) ----------- 0 and 1
2. Decimal (base 10)------- 0,1,2,3,4,5,6,7,8,9
3. Octal (base 8) -------------0,1,2,3,4,5,6,7
4. Hexadecimal (base 16)---------0,1,2,3,4,5,6,7,8,9 & A,B,C,D,E,F
Float
Complex
Example:
# integer literal
# Binary Literals
#we can specify literal value even in binary form also, allowed digits are 0 and 1. Literals
value should be prefixed with 0b or 0B.
a = 0b10100
# Decimal Literal
b = 50
# Octal Literal(Base 8)
#Here Octal number should be prefix with 0o.
c = 0o320
17
print(a, b, c, d)
Example:
# Float Literal
e = 24.8
f = 45.0
print(e, f)
Example:
z = 7 + 5j
k = 7j
print(z, k)
Boolean Literal
a = (1 == True)
b = (1 == False)
c = True + 3
d = False + 7
print("a is", a)
print("b is", b)
print("c:", c)
print("d:", d)
Variable
● Python Variable is containers which store values.
● Python is not “statically typed”.
● We do not need to declare variables before using them or declare their
type.
● A variable is created the moment we first assign a value to it.
● A Python variable is a name given to a memory location.
● It is the basic unit of storage in a program.
18
underscores(A-z, 0-9, and _ ).
● Variable names are case-sensitive (name, Name and NAME are
three differentvariables).
● The reserved words(keywords) cannot be used naming the variable.
Example
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type and can even
change type after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
And you can assign the same value to multiple variables in one line:
Example
19
x = y = z = "Orange"
print(x)
print(y)
print(z)
Output Variables
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)
If you try to combine a string and a number, Python will give you an error:
Example
x=5
y = "John"
print(x + y)
Global Variables
Variables that are created outside of a function (as in all of the examples above)
are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
20
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
If you create a variable with the same name inside a function, this variable will
be local, and can only be used inside the function. The global variable with the
same name will remain as it was, global and with the original value.
Example
Create a variable inside a function, with the same name as the global
variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
Global Keyword
A global keyword is a keyword that allows a user to modify a variable outside
the current scope. It is used to create global variables in Python from a non-
global scope, i.e. inside a function. Global keyword is used inside a function
only when we want to do assignments or when we want to change a variable.
Global is not needed for printing and accessing.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Example
21
To change the value of a global variable inside a function, refer to the variable
by using the global keyword:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Data Types
Variables can hold values of different data types. Python is a dynamically typed language
hence we need not define the type of the variable while declaring it. The interpreter implicitly
binds the value with its type.
Python enables us to check the type of the variable used in the program. Python provides us
the type() function which returns the type of the variable passed.
Example
>>a=10
>>print(type(a))
22
Example:
a=10
b=20.5
c=1+3j
d=True
e={2,4,5}
f={1:'x',2:'z'}
g=[1,'4.5','ram']
h=(3,4,5)
i='y'
j="Ram"
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
print(type(g))
print(type(h))
print(type(i))
print(type(j))
Numbers: The number data type in Python is used to store numerical values. It is used to
carry out normal mathematical operations.
Strings: Strings in Python are used to store textual information. They are used to carry out
operations that perform positional ordering among items.
Lists: The list data type is the most generic Python data type. Lists can consist of a collection
of mixed data types, stored by relative positions.
23
Tuples: Python Tuples are one among the immutable Python data types that can store values
of mixed data types. They are basically a list that cannot be changed.
Sets: Sets in Python are a data type that can be considered as an unordered collection of data
without any duplicate items.
Dictionaries: Dictionaries in Python can store multiple objects, but unlike lists, in
dictionaries, the objects are stored by keys and not by positions.
Number Datatype
Python supports 3 types of numeric data.
int (signed integers like 10, 2, 29, etc.)
float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)
Example:
x = 8 # int
y = 2.8 # float
z = 1j # complex
# To verify the type of any object in Python, use the type() function:
# Example
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
implicit type conversion (Automatic Type casting) -------------- no data loss (ex:int
to float) (a=100,b=3,c=a/b print(type(c))
explicit type conversion -------------- data loss(ex: float to int)
Example
Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
24
print(a)
print(b)
print(c)
print(x.real)
print(x.imag)
print(type(a))
print(type(b))
print(type(c))
Note: You cannot convert complex numbers into another number type.
Example
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1,10))
input function
Input function is used to send the data dynamically by using terminal.
The below program takes the input of any data type
a=input("Enter the input:")
print(a)
If suppose if we give specific data type it will take that type of data only as input.
a=int(input("Enter the input:"))
print(a)
print(type(a))
25
2. Print with string formatting %
name="Rama Krishna"
age=29
print("My name is %s and my age is %d"%(name,age))
name1="Gopal"
print("My name is {name} and my age is {age}".format(name=name1,age=age))
course="Python"
price=2.99 #print this is dollar format
print("My course is {} and the price is ${price:.1f}".format(course,price=price))
salary=10000
tax=0.2
print(f"my monthly salary is ${salary-tax}")
#printing to a stream
import sys
print("This will return to a stream", file=sys.stderr)
Operators
The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built in a
particular programming language. Python provides a variety of operators described as follows.
26
Arithmetic operators
Comparison operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two operands. It
includes +(addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor
division), and exponent (**).
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30
- (Subtraction) It is used to subtract the second operand from the first operand. If the first
operand is less than the second operand, the value result negative. For example,
if a = 20, b = 10 => a - b = 10
/ (divide) It returns the quotient after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b = 10
(Multiplication) => a * b = 200
% (reminder) It returns the reminder after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a%b = 0 Example: if a=17 b=7 =>b%a =7
here if it is not possible then returns above value.
// (Floor It gives the floor value of the quotient produced by dividing the two operands.
division) print(20//10)=2 its not gives any decimal value.
Assignment Operators
Assignment operators are used to assign values to variables:
Operator Example Same As
= x=5 x=5
27
+= x += 3 x=x+3
-= x -= 3 x=x–3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
Comparison operator
Comparison operators are used to comparing the value of the two operands and returns
boolean true or false accordingly. The comparison operators are described in the following
table.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the condition
becomes true.
>= If the first operand is greater than or equal to the second operand, then the condition
becomes true.
> If the first operand is greater than the second operand, then the condition becomes
true.
< If the first operand is less than the second operand, then the condition becomes true.
Logical Operators
Logical operators are used to combine conditional statements:
28
is true
not Reverse the result, returns False if the not(x < 5 and x <
result is true 10)
Bitwise operator
The bitwise operators perform bit by bit operation on the values of the two operands.
Example:
if a = 7;
b = 6;
then, binary (a) = 0111
binary (b) = 0011
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the
and) result. Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero otherwise the resulting bit will
be 1.
^ (binary xor) The resulting bit will be 1 if both the bits are different otherwise the resulting bit
will be 0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting
bit will be 1 and vice versa.
<< (left shift) The left operand value is moved left by the number of bits present in the right
operand.
>> (right The left operand is moved right by the number of bits present in the right operand.
shift)
Membership Operators
Membership operators are used to test if a sequence is presented in an object:
29
Operator Description Example
Example:
x = ["apple", "banana"]
print("banana" in x)
# returns True because a sequence with the value "banana" is in the list
Example:
x = ["apple", "banana"]
print("pineapple" not in x)
# returns True because a sequence with the value "pineapple" is not in the list
Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is not z)
# returns False because z is the same object as x
print(x is not y)
# returns True because x is not the same object as y, even if they have the same content
print(x != y)
30
# to demonstrate the difference betweeen "is not" and "!=": this comparison returns False
because x is equal to y.
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
# returns True because z is the same object as x
print(x is y)
# returns False because x is not the same object as y, even if they have the same content
print(x == y)
# to demonstrate the difference betweeen "is" and "==": this comparison returns True because
x is equal to y
Control Statements
Conditional statements
If
If-else
If-elif-else
Nested-if
Looping statements
for
while
Nested loops
Transfer Statements
Break
Continue
Pass
Return
31
Conditional statements
In programming languages, most of the time in large projects we have to controlthe flow of
execution of our program and we want to execute some set of statements only if the given
condition is satisfied, and a different set of statements when it’s not satisfied.
Conditional statements are also known as decision-making statements. We needto use these
conditional statements to execute the specific block of code if the given condition is true or
false.
32
Here, the condition will be evaluated to a Boolean expression (true or false).
If the condition is true, then the statement or program present inside the ” if ” block will be
executed and if the condition is false, then the statements or program present insidethe “else”
block will be executed.
Note :In every programming language only "0" is the false value. Remaining integer
values( either +ve or -ve) are all true values.
Example:
if(1):
print("Hi")
print("Hello")
Example:
age=int(input("Enter your age:"))
if(age>18):
print("your are Major")
If-else
The statement itself says if a given condition is true then execute the statementspresent inside
the “if block” and if the condition is false then execute the “else” block.
The “else” block will execute only when the condition becomes false. It is theblock where you
will perform some actions when the condition is not true.
Syntax :
if (EXPRESSION == TRUE):
Statement (Body of the block)
else:
Statement (Body of the block)
Example:
if(0):
33
print("Hi")
else:
print("Hello")
Example:
age=int(input("Enter your age:"))
if(age>18):
print("You are major")
else:
print("You are minor")
If-elif-else
In Python, we have one more conditional statement called “elif” statements.
“elif” statement is used to check multiple conditions only if the given condition is false.
It’s similar to an “if-else” statement and the only difference is that in “else” we willnot check
the condition but in “elif” we will check the condition.
“elif” statements are similar to “if-else” statements but “elif” statements evaluate multiple
conditions.
Syntax:
if (condition):
#Set of statement to execute if condition is true
elif (condition):
#Set of statements to be execute when if condition is false and elif condition is true
else:
#Set of statement to be executed when both if and elif conditions are false
34
WAP to find biggest among 3 numbers :
Example:
a,b,c=input("Enter a,b,c value:").split()
if((a>b)&(a>c)):
print("a is big")
elif(b>c):
print("b is big")
else:
print("c is big")
Nested if-else
Nested “if-else” statements mean that an “if” statement or “if-else” statement is present inside
another if or if-else block.
Python provides this feature as well, this in turn will help us to check multiple conditions in a
given program.
An “if” statement is present inside another “if” statement which is present inside another “if”
statements and so on.
Syntax:
if boolean_expression:
if Boolean_expression:
statement(s)
else:
statement(s)
else:
statement(s)
Example:
a,b,c=input("Enter a b c value:").split()
if(a>b):
if(a>c):
print("a is big")
else:
print("c is big")
else:
if(b>c):
print("b is big")
35
else:
print("c is big")
Example:
year=int(input("Enter the year:"))
if(year%100==0):
if(year%400==0):
print("Leap Year")
else:
print("It is not Leap Year")
else:
if(year%4==0):
print("Leap Year")
else:
print("It is not Leap Year")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example:
if a > b: print("a is greater than b")
a=2
b = 330
print("A") if a > b else print("B")
36
Looping statements
The following loops are available in Python to fulfil the looping needs. Python offers 3
choices for running the loops. The basic functionality of all the techniques is the same,
although the syntax and the amount of time required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop command.
For loop This type of loop executes a code block multiple times andabbreviates
the code that manages the loop variable.
Nested loops We can iterate a loop inside another loop.
while
A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax
while condition:
statements(s)
Here, statement(s) may be a single statement or a block of statements. The condition may
be any expression, and true is any non-zero value. The loop iterates while the condition
is true. When the condition becomes false, program control passes to the line
immediately following the loop.
Example: Print 1 to 5 numbers
i=1
while(i<=5):
print(i)
i+=1
37
print(i)
count+=1
i=i-1
print("The count is:",count)
for
It has the ability to iterate over the items of any sequence, such as a list or a string
Syntax:
for iterating_var in sequence:
statement(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating_var.
38
Next, the statements block is executed. Each item in the list is assigned to iterating_var,and
the statement(s) block is executed until the entire sequence is exhausted.
Example:
fruits=["apple", "banana", "cherry"]
for x in fruits:
print(x)
Range() Function:
To loop through a set of code a specified number of times, we can use the range() function,
range() function returns a sequence of numbers, starting from 0 by default, and increment by
1(by default) and ends with specified number.
Parameters:
Start: Optional. An integer number specifying at which position to start. Default is 0.
Stop: Required. An integer number specifying at which position to stop (not excluded).
Step: Optional. An integer number specifying the incrementation. Default is 1.
Example:
for x in range(6):
print(x)
39
for x in range(1,5):
fact=fact*x
print(fact)
Syntax:
for iterating_var in sequence:
for iterating_var in sequence:
statement(s)
statement(s)
Example:
for i in range(1,101):
for j in range(1,11):
print(i*j,end=" ")
print()
Example:
for i in range(2,3):
for j in range(1,11):
print(i,"*",j,"=",i*j)
print()
Transfer Statements
Break
The break statement is used to break out of a loop. It is used inside for and while loops to
alter the normal behavior. the break will end the loop it is in and controlflows to the
statement immediately below the loop.
Continue
The continue keyword is used to end the current iteration in a for loop or a while loop
and continues to the next iteration.
The continue statement is a temporary break in a loop.
Pass
The pass statement in Python is used when a statement is required syntactically but you
do not want run any code to execute.
40
The pass statement is a null operation; nothing happens when it executes.
The pass is also useful in places where your code will eventually go, but has not been
written yet.
Python List
Create a List:
L1=[]
L2 = ["John", 102, 'USA',10,"20"]
L3 = [1, 2, 3, 4, 5, 6]
L4=list([1,"Ram"]) #in this case we can use [],{}() ---inside brackets
print(type(L1))
41
print(type(L2))
print(type(L3))
print(L1)
#List can hold any complex data type like dict,tuple, etc
L1=[40,{"name":"Ram"},list((10,20,30))]
print(type(L1))
print(L1)
Characteristics of Lists :
The list has the following characteristics:
The lists are ordered.
The element of the list can access by index.
The lists are the mutable type.
A list can store the number of various elements in [].
Allow Duplicate values.
42
We can get the sub-list of the list using the following
syntax:
list_varible(start:stop:step)
The start denotes the starting index position of the list.
The stop denotes the last index position of the list.
The step is used to skip the nth element within a start:stop
# By default the index value is 0 so its starts from the 0th element and gofor index -1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
43
Unlike other languages, Python provides the flexibility to use the negative indexing also. The
negative indices are counted from the right. The last element (rightmost) of the list has the
index -1; its adjacent left element is present at the index -2 and so on until the left-most
elements are encountered.
Let's have a look at the following example where we will use negative indexing to access the
elements of the list.
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
As we discussed above, we can get an element by using negative indexing. In the above
code, the first print statement returned the rightmost element of the list. The second print
statement returned the sub-list, and so on.
44
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which
can be iterated as follows.
Using While:
list = ["John", "David", "James", "Jonathan"]
i=0
while i<len(list):
print(list[i])
i=i+1
List Methods
Method Description
append() Adds an element at the end of the list
extend() Add the elements of a list to the end of the current list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified
positionremove() Removes the first item with the
specified valuereverse() Reverses the order of the list
sort() Sorts the list
45
Example:
list=[1,2,3]
list.append(4) #To add as sub list use list.append([4])
print(list)
insert():
Inserts an element at the specified position.
Syntax:
list.insert(position, element)
Note: Position mentioned should be within the range of List, as in this case between 0
and 4, else wise would throw IndexError.
Example:
l1=[1,2,3,4,2,5,6,7,2,8,9,10]
l1.insert(3,24)
print(l1)
Output:
[1,2,3,24,4,2,5,6,7,2,8,9,10]
count():
Calculates total occurrence of a given element of List.
Syntax: List.count(element)
Example:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
Output: 4
index():
Returns the index of the first occurrence. The start and End index are not necessary
parameters.
Syntax:
List.index(element,start,end)
Example:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
46
print(List.index(2))
Output:
1
list.remove(2)
print("\nprinting the list after the removal of second element...")
for i in list:
print(i,end=" ")
pop():
The index is not a necessary parameter, if not mentioned takes the last
index.Syntax:
list.pop([index])
Example:
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(List.pop())
Output:
2.5
extend():
Adds contents to List2 to the end of List1.
Example:
list=[1,2,3]
47
list.extend([4]) #we cannot process this extend as sublist
print(list)
Example:
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
Output:
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
sum():
Calculates the sum of all the elements of the List.
Syntax:
sum(List)
Example:
List = [1, 2, 3, 4, 5]
print(sum(List))
Output:
15
Length():
Calculates the total length of the List.
Syntax: len(list_name)
Example:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(Li
st))Output:
10
48
Example:
list=[1,3,2,5,2,7,8]
for i in range(len(list)):
if list[i]==2:
print(i)
min():
Calculates minimum of all the elements of List.
Example:
List = [8, 2, 3, 5,8,9]
print(min(List))
clear:
It is used to clear the list.
Example:
List = [8, 2, 3, 5,8,9]
List.clear()
print(List)
copy:
It is used to copy the list
Example:
List = [8, 2, 3, 5,8,9]
print(List)
b=List.copy()
List.append(10)
print(List)
print(b)
To Delete one or more elements, i.e. remove an element, many built-in functions can
be used, such as pop() & remove() and keywords such as del.
Example:
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(List.pop
(0))Output:
2.3
del():
Element to be deleted is mentioned using list name and index.
49
Syntax:
del list.[index]
Example:
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
del List[0]
print(List)
Output:
[4.445, 3, 5.33, 1.054, 2.5]
remove():
Element to be deleted is mentioned using list name and element.
Syntax:
list.remove(elem
ent)
Example:
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
List.remove(3)
print(List)
Outpu
t:
[2.3, 4.445, 5.33, 1.054, 2.5]
Reverse():
It is used to reverse the list.
Example:
List = [8, 2, 3, 5,8,9]
List.reverse()
print(List)
50
Example:
list = [8, 2, 3, 5,8,9]
list.sort(reverse=True)
print(list)
Example:
sample=["Even" if a%2==0 else "Odd" for a in range(10)]
print(sample)
Example:
NewList=[]
for i in["Apple","Banana","Mango"]:
if "a" in i:
NewList.append(i)
print(NewList)
Example:
List=["Apple","Banana","Kiwi"]
NewList=[x for x in List if "a" in x]
print(NewList)
Concatenate of Lists:
Joining of list is known as Concatenation of lists.
+ Operator is used for concatenate list.
Example:
L1=[20,30,40,50,60]
S1=['Ram','Priyanka',40,50]
C1=L1+S1
print(C1)
Repetition of Lists:
It will repeat the list based on specified number of times.
* operator is used to repeat list.
Example:
L1=[10,20,40]
Rep=L1*5
print(Rep)
51
project=1
SUM GAME
#sum game with random numbers
import os
from random import randint
count=0
while True:
os.system("cls") #To clear the screen
a=randint(1,50)
b=randint(1,50)
c=a+b
question=randint(1,3)
print("Type your answer: ")
match question:
case 1:
print(f"? + {b}= {c}")
correct_answer=a
case 2:
print(f"{a} + ?= {c}")
correct_answer=b
case 3:
print(f"{a} + {b}= ?")
correct_answer=c
while True:
try:
your_answer=int(input())
break
except:
print("Please Enter the numbers only")
if your_answer==correct_answer:
print("Correct. Press Enter to continue...")
count=count+1
input() #pause the program wait for Enter.
else:
print("Not Correct.")
break
52
project=2
MATH GAME
correct=0
wrong=0
level=int(input("Choose Difficulty Level(1= Easy, 2=Medium, 3=Hard):"))
Difficulty_level="None"
if level==1:
Difficulty_level="Easy"
elif level==2:
Difficulty_level="Medium"
elif level==3:
Difficulty_level="Hard"
for i in range(10):
os.system("cls") #To clear the screen
a=randint(1,50)
b=randint(1,50)
c=a+b
question=randint(1,3)
print(f"Difficulty Level :{Difficulty_level} | Questions: {i}/10 | Correct
Answers: {correct} | Wrong Answers: {wrong}")
print("Type your answer: ")
match question:
case 1:
print(f"? + {b}= {c}")
correct_answer=a
53
case 2:
print(f"{a} + ?= {c}")
correct_answer=b
case 3:
print(f"{a} + {b}= ?")
correct_answer=c
while True:
try:
your_answer=int(input())
break
except:
print("Please Enter the numbers only")
if your_answer==correct_answer:
print("Correct. Press Enter to continue...")
correct=correct+1
input() #pause the program wait for Enter.
else:
print("Not Correct.")
wrong=wrong+1
time.sleep(1)
# store end time
end = time.time()
if correct==10:
grade="A"
elif correct in range(7,10):
grade="B"
elif correct in range(5,7):
grade="C"
else:
grade="D"
54
print("Your Test Result:")
print(f" > Scores: {correct}/10 ({correct/10*100} %)")
print(f" > Time to complete: {end-begin} seconds")
print(f" > Grade : {grade}")
55
conclusion:
One of the key takeaways from this project is the flexibility Python offers
across multiple domains such as web development, automation, artificial
intelligence, data science, and software engineering. We also gained experience
in using Python tools like IDEs (e.g., VS Code), packages (like random and
time), and best practices such as modular programming and code readability.
The development of small games and logic-based applications enhanced our
problem-solving skills and reinforced our understanding of computational logic.
56