7. Programming Concept (Python)
7.1 Introduction to programming languages
7.2 Types of programming languages
7.3 Programming tools: flowchart and algorithm
7.4 Introduction to coding, testing, and debugging
7.5 Compiler and interpreter
7.6 Introduction to python programming
7.7 Basic syntaxes
7.8 I/O statements and string formatting
7.9 Data types and variables
7.10 Concept of Type casting
7.11 Operators and expressions: Arithmetic, Relational, Logical, Assignment
7.12 Conditional statement (if, elseif, else)
7.13 Iteration (for and while)
7.14 List and Dictionary
7.15 Use library functions: String Functions (center, upper, lower, Len), Numeric and mathematical (sum, pow, round, abs, sqrt, Int)
7.1 Introduction to Programming Language
Programming Language
A programming language is a
language used to write instructions that tell a computer to solve problems or
perform specific tasks. Python, Java, PHP, C++, etc. are some examples of
popular programming languages.
Programming
Programming is the process of
providing step-by-step instructions to a computer to solve problems or perform
specific tasks.
Programmer
A programmer is a person who writes
computer programs using programming languages to solve problems or perform
specific tasks.
Program
A program is a sequence of
instructions that a computer executes to solve a problem or perform a specific
task.
Syntax
Syntax is the set of rules that
defines the correct structure of statements in a programming language.
7.2 Types of programming languages
- High-level
programming language and Low-level programming language
High-level programming language
A high-level
programming language is a machine-independent language that uses English-like
statements, making it easy for humans to write and understand programs, and it
requires a compiler or interpreter to translate it into machine code. Examples: Python, Java, C++, PHP, JavaScript
Low-level programming language
A low-level programming language is
a machine-dependent language that is very close to computer hardware and
machine code. It is difficult for humans to understand but easy and fast for
the computer to execute.
Types of low level programming
language - Machine
Level Language and Assembly Language.
Machine language is a low-level
programming language which uses binary digits (0 and 1) that a computer can
understand and execute directly without any translator.
Assembly language is a low-level
programming language that uses mnemonics (e.g., MOV, ADD, SUB) instead of
binary (0s and 1s), making it easier for humans to write programs, and it
requires an assembler to translate it into machine language.
High level language Vs Low level
language
|
Low-Level Language |
High-Level
Language |
|
Difficult for humans
to understand; close to hardware/machine code |
Easy to understand;
uses English-like statements |
|
Machine dependent
(not portable) |
Machine independent
(portable) |
|
Machine language
needs no translator; assembly language needs an assembler |
Needs a compiler or
interpreter |
|
Examples: Machine
language, Assembly language |
Examples: Python,
Java, JavaScript |
7.3 Programming tools: Flowchart
and Algorithm
Algorithm
An algorithm is a finite set of
clear, step-by-step instructions designed to solve a specific problem or
perform a particular task. It is written in simple language and generally
begins with Start and ends with Stop.
Flowchart
A flowchart is a diagrammatic
(graphical) representation of an algorithm, using standard
symbols and arrows to show the sequence of steps and the flow of
control in solving a problem.
|
Algorithm |
Flowchart |
|
A step-by-step
written procedure to solve a problem |
A graphical/diagrammatic
representation of an algorithm |
|
Written in simple
language |
Drawn using standard
symbols and arrows |
|
Easy to write but may
be harder to visualize |
Easy to understand
visually |
|
No symbols are used |
Uses standard
symbols (oval, rectangle, diamond, etc.) |
|
Easy to modify
steps |
Modification can be time-consuming |
|
Takes less space |
Takes more space |
The table below shows shapes used
in flowchart and their meaning:
|
Shape |
Name |
Meaning / Use |
|
Oval |
Terminator |
Indicates Start
and Stop (End) of the flowchart |
|
Rectangle |
Process |
Represents a processing
step such as calculation or assignment |
|
Parallelogram |
Input / Output |
Used for input
(read data) or output (display result) |
|
Diamond |
Decision |
Used for decision
making with Yes/No or True/False paths |
|
Arrow |
Flow line |
Shows the direction
and sequence of steps |
|
Circle (small) |
Connector |
Connects different
parts of a flowchart (avoids long lines or connects pages) |
7.4 Coding, testing and debugging
Coding
Coding is the process of writing
instructions (code) in a programming language to create a computer
program. These instructions tell the computer what tasks to perform.
Testing
Testing is the process of executing
a program with different inputs to check whether it works correctly and
produces the expected output.
Debugging
Debugging is the process of identifying,
locating, and correcting errors (bugs) in a program after testing to ensure
it runs correctly and smoothly.
7.5 Compiler and Interpreter
Compiler
A compiler is a translator program
that converts the entire high-level program into machine language in a single
operation before execution. Examples: C, C++, FORTRAN.
Interpreter
An interpreter is a translator
program that translates and executes a high-level program into machine language
one line at a time. Examples: Python, Ruby, QBasic, JavaScript.
|
Compiler |
Interpreter |
|
Translates the entire
program at once |
Translates one
line at a time |
|
Program is executed after
complete compilation |
Each line is translated
and executed immediately |
|
Generates object
code |
Does not generate
object code |
|
Shows all errors
after compilation |
Shows errors one
by one and stops at error |
|
Faster execution (after compilation) |
Slower execution |
|
Requires more
memory |
Requires less
memory |
|
C, C++, FORTRAN |
Python, JavaScript,
Ruby |
Assembler
An assembler is a translator
program that converts programs written in assembly language into machine code
that the computer can understand and execute.
7.6 Introduction to Python
Programming
Python
- Python is a high-level,
interpreted programming language introduced by Guido van Rossum in
1991.
- It
is easy to learn and uses simple English-like syntax, which
makes it suitable for beginners.
- Python
is widely used in areas such as web development, artificial
intelligence (AI), data science, and automation.
- It
has a large number of built-in libraries and strong community
support, which makes program development faster and easier.
- Python
uses indentation instead of braces { } to define blocks of code,
which improves readability and makes programs easier to understand.
Features of Python
Features of Python (Exam-Type,
Topper Level)
a)
Easy
to Read and Write - Python
uses simple, English-like syntax, which makes programs easy to
understand and write.
b)
Versatile
- Python can be
used in many fields such as web development, data science, artificial
intelligence, automation, and game development.
c)
Beginner-Friendly
- Python is easy
to learn, allowing beginners to start programming with less effort.
d)
Extensive
Standard Library - Python
provides a large number of built-in modules and functions, reducing the
need to write code from scratch.
e)
Platform
Independent - Python
programs can run on different operating systems like Windows, macOS, and
Linux without modification.
f)
Huge
Community Support - Python
has a large community that offers tutorials, documentation, and online
support, making problem-solving easier.
Advantages of Python
- Python
is simple and easy to learn, making it suitable for beginners.
- It
is cross-platform, meaning the same program can run on Windows,
Linux, and macOS.
- Python
is free and open-source and supported by a large global
community.
- Python
programs are shorter and faster to develop, which saves time and
effort.
- Python
is widely used in modern fields such as artificial intelligence, data
science, automation, and web development.
Disadvantages of Python
- Python
is slower than compiled languages like C, C++ and Java because it
is interpreted.
- It
is not ideal for mobile application development, where languages
like Java or Kotlin are preferred.
- Python
programs generally require more memory, making them less efficient
for large or resource-intensive applications.
- Due
to dynamic typing, some errors are detected only at runtime,
which may cause issues if not properly tested.
Installation Process of Python
Step 1: Download Python
- Go
to the official Python website: www.python.org
- Click
on Download Python and choose the latest version suitable for your
operating system (Windows / macOS / Linux).
Step 2: Run the Installer
- Open
the downloaded setup file.
- Important: Check the box “Add Python
to PATH” (students forget this and then panic later).
- Click
Install Now.
📌 PATH means the system can
find Python easily from anywhere.
Step 3: Complete Installation
- Wait
for the installation process to finish.
- Click
Close after successful installation.
Step 4: Verify Installation
- Open
Command Prompt (Windows) or Terminal (macOS/Linux).
- Type:
- python
--version
- If
the Python version appears, installation is successful.
Step 5: Run Python
- Type
python in Command Prompt/Terminal to enter the Python interpreter.
- You
can now start writing and executing Python programs.
Download and Install a Suitable IDE
for Python
An IDE (Integrated Development
Environment) is software that helps write, run, and debug programs easily.
For Python, some popular IDEs are IDLE, PyCharm, VS Code, Jupyter Notebook.
Download and Install VS Code for
Python
VS Code (Visual Studio Code) is a popular, free, and
lightweight code editor used for Python programming.
Step 1: Download VS Code
- Go
to the official website: https://code.visualstudio.com
- Click
Download and choose the version for your operating system
(Windows / macOS / Linux).
Step 2: Install VS Code
- Open
the downloaded setup file.
- Click
Next and follow the on-screen instructions.
- Check
“Add to PATH” (recommended).
- Click
Install and wait for completion.
Step 3: Launch VS Code
- Open
Visual Studio Code from the Start menu or desktop.
Step 4: Install Python Extension
- In
VS Code, click on the Extensions icon (left side).
- Search
for Python.
- Install
the extension by Microsoft.
📌 This extension enables Python
syntax highlighting, debugging, and running programs.
Step 5: Verify Python Setup
- Make
sure Python is already installed on your computer.
- Open
Terminal inside VS Code.
- Type:
- python
--version
- If
the version appears, Python is ready to use.
Step 6: Run a Python Program
- Create
a new file and save it with .py extension.
- Write
Python code and click Run.
7.7 Basic Syntaxes in Python
Python syntax refers to the rules
for writing Python programs correctly.
1) Indentation
- Python
uses indentation (spaces) to define blocks of code.
- Curly
braces { } are not used.
Example:
if a > b:
print("a is greater")
📌 Important: Wrong
indentation = error.
2) Comments
- Comments
are used to explain code.
- Python
uses # for single-line comments.
Example:
# This is a comment
print("Hello")
3) Case Sensitivity
- Python
is case-sensitive.
- name
and Name are treated as different variables.
📌 Small letter, capital letter —
Python notices everything.
4) Statements
- Python
statements usually end without semicolons (;).
- One
statement is written per line.
Example:
x = 10
y = 20
5) Variables
- Variables
are used to store data.
- No
need to declare data type explicitly.
Example:
x = 5
name = "Python"
6) Print Statement
- print()
is used to display output.
Example:
print("Hello World")
7) Input Statement
- input()
is used to take input from the user.
Example:
name = input("Enter name:
")
Comments in Python
Comments
in Python are notes written using # or triple quotes to explain the code, and
they are ignored by the Python interpreter.
Why Comments Are Used?
- To
explain code
- To
make programs easier to understand
- To
help debugging
- To
leave notes for other programmers
Types of Comments in Python
- Single-line
Comment - Begins
with #.
Example:
#
This is a single-line comment
print("Hello,
World!") # This prints a message
- Multi-line
Comment - Written
inside triple quotes ''' ''' or """ """.
- Useful
for writing long explanations or documentation.
- Example:
'''This
is a
multi-line
comment
in Python'''
print("Welcome")
Keywords
Keywords are reserved words in
Python that have special meanings and cannot be used as variable
names, function names, or identifiers.
Python 3 has more than 35 keywords,
which are reserved words such as if, else, while, def, class, True, False, and
None, and they cannot be used as variable or function names.
7.8 I/O statements and string
formatting
Input/Output statements (I/O)
I/O stands for Input and Output.
Input statements are used to take data from the user, and output
statements are used to display results.
Input Statement - input() is used to take input from
the user.
Example: name = input("Enter name:
")
Output Statement - print() is used to display output.
Example: print(name)
String Formatting -String formatting is used to display
variables along with strings in a proper format.
Different Ways of String Formatting
Using % Operator (Old Style) - This is the old style of string
formatting, where we use % to insert values into a string.
Example:
name = "Charlie"
age = 22
message = "My name is %s and I
am %d years old." % (name, age)
print(message)
Output - My name is Charlie and I am 22
years old.
Using format( ) Method (New-style
formatting) - The
format( ) method allows to insert values into a string using curly braces {} as
placeholders.
Example 1:
name = "Bob"
age = 30
message = "My name is {} and I
am {} years old.".format(name, age)
print(message)
Output
My name is Bob and I am 30 years
old.
We can also use numbered or named
placeholders
Example 2:
message = "My name is {0} and
I am {1} years old.".format(name, age)
print(message)
Using commas in print( ) - Simple and beginner-friendly. Easiest
method but adds spaces automatically.
Example:
name = "Alex"
age = 15
print("My name is", name,
"and I am", age, "years old.")
Output:
My name is Alex and I am 15 years
old.
Formatted string literals (Using
f-strings - modern and easiest)
This is the most widely used method
in string formatting in the current time. In formatted string literal we use
‘f’ before the string and embedding expressions inside { }. It is the most
popular method of using string format. It was introduced in Python 3.6.
Example 1:
name = "Alice"
age = 25
message = f"My name is {name}
and I am {age} years old."
print(message)
Output
My name is Alice and I am 25 years
old.
7.9 Data types and variables
Data type
Data types are categories of data that
specify the type of value a variable can store. In Python, the data type
is automatically assigned to a variable when a value is stored in it.
Python supports several data types:
- int
(Integer) - Stores
whole numbers without decimals. Example: 10, -25
- float
(Floating point) - Stores
decimal numbers. Example: 3.14, -0.5
- str
(String) - Stores
text or characters enclosed in single or double quotes. Example:
"Hello", 'Python'
- bool
(Boolean) - Stores
logical values True or False. It is often used in decision-making
statements. Example: is_pass = True
- List
- Stores multiple
values in a single variable using square brackets [ ].
Example: fruits = ["apple", "banana", "mango"] - Dictionary
(dict) - Stores
data in key–value pairs using curly braces { }.
Example: student = {"name": "Ram", "age": 14}
Identifier
An identifier is the name
given to variables, functions, classes, or any other user-defined items in
Python. It is used to identify different parts of a program.
Rules for Identifiers / variables
in Python
- An
identifier must begin with a letter (A–Z or a–z) or an underscore (_).
- It cannot
start with a number.
- It
can contain letters, digits, and underscores only (e.g.,
student_1).
- Keywords like if, else, class, def cannot
be used as identifiers.
- Python
identifiers are case-sensitive (name, Name, and NAME are
different).
- Spaces
are not allowed
in identifiers.
Valid Identifiers - A1, B34, First_Name, x_1
Invalid Identifiers - 1A, 34BA, 198, int, first-name, def
Variables in Python
A variable is a named memory
location used to store data in a program, and its value can change during
program execution.
|
Variable Name |
Data Type |
Description |
Python
Representation |
|
age |
Integer (int) |
Stores an integer
value 15 |
age = 15 |
|
height |
Float (float) |
Stores a decimal
value 5.7 |
height = 5.7 |
|
fname |
String (str) |
Stores a string value
"Sanjog" |
fname =
"Sanjog" |
|
is_student |
Boolean (bool) |
Stores a Boolean
value True |
is_student = True |
7.10 Concept of Type Casting
Type Casting (Type Conversion)
Type casting is the process of
converting one data type into another, such as converting strings into integers
or floats in Python.
Types of casting
·
Implicit
casting
·
Explicit
casting
Implicit casting
Implicit casting is the automatic
conversion of one data type into another by Python when necessary, without the
programmer doing anything.
Examples:
x = 10 # integer
y = 5.5 # float
z = x + y # the integer ‘x’ is cast
to a float for the addition.
print(z)
Explicit casting
Explicit casting is the manual
conversion of one data type into another using functions like int(), float(),
and str().
Common Casting Functions in Python
·
int():
Converts a value to an integer.
·
float():
Converts a value to a float.
·
str():
Converts a value to a string.
·
bool():
Converts a value to a boolean (True or False).
Example:
int(x): Converts x to an integer.
x = 3.14
y = int(x) # Converts float to int (removes decimal
part)
print(y) # Output: 3
x = 25
y = str(x) # Converts integer to string
print(y) # Output: "25"
7.11 Operators and Expressions:
Arithmetic, Relational, Logical, Assignment
Operators
An operator in Python is a
symbol that is used to perform a specific operation on one or more operands to
produce a result.
Example: 5 + 3
- + →
operator
- 5,
3 → operands
Result → 8
Operands
Operands are the values, variables, or
constants on which an operator performs an operation. For example, in x +
y, the operands are x and y, while + is the operator.
Example: add = 5 + 3
Here, ‘5’ and ‘3’ are operands and
‘+’ is an operator, and it is performing an ‘addition’ operation.
Arithmetic Operators
An arithmetic operator in Python
is a symbol that is used to perform basic mathematical operations such as
addition, subtraction, multiplication, division, floor division, modulus, and
exponentiation on numeric operands and returns a numeric result.
List of Arithmetic Operators
|
Operator |
Name |
Example |
Result |
|
+ |
Addition |
10 + 3 |
13 |
|
- |
Subtraction |
10 - 3 |
7 |
|
* |
Multiplication |
10 * 3 |
30 |
|
/ |
Division |
10 / 3 |
3.33 |
|
// |
Floor Division |
10 // 3 |
3 |
|
% |
Modulus |
10 % 3 |
1 |
|
** |
Exponentiation |
2 ** 3 |
8 |
Example:
Simple program to find the sum of
the two number for the user input
num1 = float(input(“Enter first
number: “))
num2 = float(input(“Enter second
number: “))
sum = num1 + num2
print(“The sum of {0} and {1} is
{2}”.format(num1, num2, sum))
Relational operator
A
relational operator in Python is an operator used to compare two values
and return a Boolean result, that is True or False.
List of Relational Operators
|
Operator |
Meaning |
Example |
Result |
|
> |
Greater than |
5 > 3 |
True |
|
< |
Less than |
5 < 3 |
False |
|
>= |
Greater than or equal
to |
5 >= 5 |
True |
|
<= |
Less than or equal to |
3 <= 5 |
True |
|
== |
Equal to |
5 == 3 |
False |
|
!= |
Not equal to |
5 != 3 |
True |
Logical operator
A logical operator in Python
is an operator used to combine two or more conditions and return a Boolean
result, that is True or False. There are 3 main logical operators, ‘and’,
‘or’, and ‘not’.
|
Operator |
Name |
Meaning |
|
and |
Logical AND |
True if both
conditions are True |
|
or |
Logical OR |
True if at least one
condition is True |
|
not |
Logical NOT |
Reverses the result |
AND Operator
The AND operator in Python
is a logical operator that returns True only when all the given
conditions are True; otherwise, it returns False.
Example: x = (5<2) and (5>3)
Result: False
Truth Table for ‘and’ Operator
|
Condition A |
Condition B |
Result (A and B) |
|
True |
True |
True |
|
True |
False |
False |
|
False |
True |
False |
|
False |
False |
False |
OR Operator
The OR operator in Python is
a logical operator that returns True if at least one of the given
conditions is True; it returns False only when all conditions are
False.
Example: (5<2) or (5>3)
Result: True’
Truth Table for ‘or’ Operator
|
Condition A |
Condition B |
Result(A or B) |
|
True |
True |
True |
|
True |
False |
True |
|
False |
True |
True |
|
False |
False |
False |
NOT Operator
The NOT operator in Python
is a logical operator that reverses the Boolean value of a condition,
changing True to False and False to True.
Example: not(5<2)
Result: True
Truth Table for
not Operator
|
Condition
A |
Result(not
A) |
|
True |
False |
|
False |
True |
Assignment operator
An assignment operator in Python
is an operator used to assign or update the value of a variable by
performing an operation and storing the result in the same variable.
List of Assignment
Operators
|
Operator |
Name |
Example |
Meaning |
|
= |
Assignment |
a =
5 |
Assigns
5 to a |
|
+= |
Add
and assign |
a +=
3 |
a =
a + 3 |
|
-= |
Subtract
and assign |
a -=
2 |
a =
a - 2 |
|
*= |
Multiply
and assign |
a *=
2 |
a =
a * 2 |
|
/= |
Divide
and assign |
a /=
2 |
a =
a / 2 |
|
//= |
Floor
divide and assign |
a
//= 3 |
a =
a // 3 |
|
%= |
Modulus
and assign |
a %=
3 |
a =
a % 3 |
|
**= |
Power
and assign |
a
**= 2 |
a =
a ** 2 |
Expression
An expression in Python is a
combination of variables, constants, and operators that is evaluated to
produce a single value.
Example:
x = 10
y = 5
z = x + y # arithmetic expression
print(z) # 15
x + y → is an expression.
The result is 15.
Other examples:
- 10
> 5 → relational expression → result: True
- (5
> 3) and (2 < 7) → logical expression → result: True
|
Algebraic
Expression (Maths) |
Python Expression
(Code) |
Meaning / Example |
|
( x + y ) |
x + y |
Addition of two
numbers |
|
( x - y ) |
x - y |
Subtraction of two
numbers |
|
( x × y ) |
x * y |
Multiplication |
|
x/y |
x / y |
Division (float
result) |
|
x\y |
x // y |
Floor division
(quotient only) |
|
( x mod y ) |
x % y |
Modulus (remainder) |
|
( x^y ) |
x ** y |
Exponent (power) |
Exam Tip:
- In algebra,
we use symbols like × and ^.
- In Python,
we use * for multiplication and ** for exponent.
7.12 Conditional statement (if,
elif, else)
A conditional statement in
Python is a control structure used for decision making. It
allows a program to test a condition and execute a block of code if
the condition is True, and optionally execute another block of code if
the condition is False. The main conditional statements in Python are if,
if–else, and if–elif–else.
For example:
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible")
Types of Conditional Statements in
Python
if statement - → Executes a block of code when
a condition is True.
Syntax:
if condition:
# Code to execute if condition is true
Example:
age = 18
if age >= 18:
print("You are eligible to vote")
if–else statement - → Executes one block if the
condition is True, otherwise executes another block.
Syntax:
if condition:
# Code to execute if condition is true
else:
# Code to execute if condition is false
Example:
age = 16
if age >= 18:
print("You can vote")
else:
print("You cannot vote")
if–elif–else statement: → Tests multiple conditions and
executes the block of the first True condition.
Syntax:
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
else:
# Code to execute if none of the conditions are true
Example:
Checking the number’s category,
whether it is positive, negative or zero.
user_number = int(input(“Enter a
number: “))
if user_number > 0:
print(“The number is positive.”)
elif user_number == 0:
print(“The number is zero.”)
else:
print(“The number is negative.”)
Nested if Statements: A nested if statement in Python is a conditional statement
in which one if statement is placed inside
another if or else block to test multiple conditions.
Syntax:
if condition1:
#code to be executed if condition1 is True
if condition2:
#code to be executed if condition 2
is True
else:
#code to be executed when condition2
is False
else:
#code to be executed when condition1 and condition2 are False
Example:
age = int(input(“Enter your age:
“))
if age >= 16:
print(“You are eligible for citizenship.”)
if age >= 18:
print(“You are eligible to cast a
vote.”)
else:
print(“You are not eligible to cast
vote.”)
else:
print(“You are a minor.”)
7.13 Iteration (for and while)
Iteration in Python is the process
of repeatedly executing a block of code as long as a given condition is True. It is also called a loop.
The two main types are for loop
(used when the number of iterations is known) and while loop (used when
iterations depend on a condition). For example, for i in range(5): print(i)
prints numbers from 0 to 4.
Types of iterations
·
for
loop
·
while
loop
For Loop
A for loop in Python is an
iteration statement used to repeat a block of code for each element in a
sequence such as a list, string, or range. It is mostly used when the number
of repetitions is known.
Syntax:
for variable in sequence:
# Code to execute
Example:
# Iterating over a range of numbers
from 0 to 4
for i in range(5):
print(i)
Example:
#Using for loop to print “jump”
five times
for x in range(5):
print(“Jump!”)
Example:
# Iterating over a list
fruits = ["apple",
"banana", "cherry"]
for fruit in fruits:
print(fruit)
While Loop
A while loop in Python is an
iteration statement that repeats a block of code as long as a given
condition remains True. It is mainly used when the number of iterations
is not known in advance.
Syntax:
while condition:
# Code to execute
Example:
# Using while loop to print numbers
from 0 to 4
i = 0
while i < 5:
print(i)
i += 1 # Incrementing the value
of i to avoid infinite loop
Example 2 (infinite loop warning!):
while True:
print("This will run forever!")
Example 3:
x = 1
while x <= 5:
print(x)
x += 1
# prints numbers from 1 to 5.
Difference between for loop and
while loop
|
for loop |
while loop |
|
Used when the number
of iterations is known |
Used when the number
of iterations is not known |
|
Iterates over a sequence
(list, string, range) |
Repeats based on a condition |
|
Loop variable is automatically
updated |
Loop variable must be
updated manually |
|
Syntax is short
and clean |
Syntax is more
flexible |
|
Less chance of
infinite loop |
Higher chance of
infinite loop |
|
Example: for i in
range(5): |
Example: while i <
5: |
pass Statement
The pass statement in Python
is a null statement that does nothing and is used as a placeholder
where a statement is syntactically required but no action is needed. For
example, if x > 5: pass allows the program to run without producing an error
even though the block is empty.
The pass statement in Python
is a null statement.
Syntax:
if condition:
# Some code here
else:
pass # Nothing happens in the “else” case
Example:
for i in range(5):
if i == 2:
pass
# Do nothing if i is 2
else:
print(i)
Output:
0
1
3
4
In this example, when i is equal to
2, the pass statement is executed, which does nothing, so the loop continues
without printing 2.
continue Statement
The continue statement in
Python is a loop control statement that skips the remaining code of
the current iteration and immediately moves to the next iteration of the
loop. For example, in a loop from 1 to 5, if continue is used when i == 3,
the number 3 will be skipped from the output.
Example:
for i in range(5):
if i == 2:
continue # Skip the rest of the code when i is 2
print(i)
Output:
0
1
3
4
Here, when i == 2, the continue
statement skips the print(i) and moves to the next iteration of the loop, so 2
is not printed.
break Statement
The break statement in
Python is a loop control statement that terminates the loop
immediately when it is encountered, and the control moves to the statement
following the loop. For example, in a loop from 1 to 5, if break is used when i
== 3, the loop will stop after printing 1 and 2.
Example:
for i in range(5):
if i == 3:
break
# Exit the loop when i is 3
print(i)
Output:
0
1
2
In this case, when i == 3, the
break statement causes the loop to terminate, and no further numbers are
printed.
Comparison Table: break, continue,
and pass
|
Feature |
break |
continue |
pass |
|
Type |
Loop control
statement |
Loop control
statement |
Null statement |
|
Function |
Terminates the loop
completely |
Skips current
iteration |
Does nothing |
|
Effect on loop |
Loop ends immediately |
Loop continues |
Loop unaffected |
|
Use in loops |
Yes |
Yes |
Yes |
|
Use outside loops |
No |
No |
Yes |
|
Purpose |
Exit loop early |
Skip unwanted
iteration |
Placeholder |
|
Common use |
Stop searching |
Ignore certain values |
Empty block |
7.14 Lists and Dictionary
Python list
A list in Python is an ordered,
mutable collection of elements that can store multiple values of
different data types in a single variable. A list can store numbers,
strings, or even mixed data types. Lists are indexed, meaning each item
has a position starting from 0.
Features
of Lists
- Ordered → Elements have a fixed position (index) (index starts from
0).
- Mutable → Values can be changed after creation
- Can hold mixed data types (numbers, strings, booleans).
- Allows duplicate values.
1. Creating a List
- Using
square brackets:
numbers
= [1, 2, 3, 4, 5]
fruits
= ["apple", "banana", "cherry"]
mixed
= [1, "apple", 3.14, True]
empty
= []
- Using
the list() constructor:
thislist =
list(("apple", "banana", "cherry"))
2. Accessing Elements
- Lists
use indexing (starts at 0).
print(fruits[0]) # apple
print(fruits[-1])
# cherry (last element)
3. Modifying a List
- Lists
are mutable → items can be changed, added, or removed.
numbers[0]
= 10
fruits.append("orange") # add at end
fruits.insert(1,
"grape") # insert at
position
fruits.remove("banana") # remove by value
removed
= fruits.pop(2) # remove by index
4. List Length
print(len(fruits)) # number of elements
5. Looping Through a List
for
fruit in fruits:
print(fruit)
6. List Slicing
fruits
= ["apple", "grape", "cherry",
"orange"]
print(fruits[1:3]) # ['grape', 'cherry']
print(fruits[:2]) # ['apple', 'grape']
print(fruits[2:]) # ['cherry', 'orange']
7. Concatenation & Repetition
list1
= [1, 2, 3]
list2
= [4, 5, 6]
print(list1
+ list2) # [1,2,3,4,5,6]
print(list1
* 2) # [1,2,3,1,2,3]
8. List Comprehension
squares
= [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
evens
= [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
9. Nested Lists
nested
= [1, [2, 3], 4, [5, 6]]
print(nested[1]) # [2, 3]
print(nested[1][0]) # 2
10. Common List Methods
|
Method |
Use |
|
append(x) |
Add item at end |
|
insert(i,x) |
Insert at index |
|
remove(x) |
Remove item by value |
|
pop(i) |
Remove item by index |
|
sort() |
Sort list ascending |
|
reverse() |
Reverse list order |
|
clear() |
Remove all items |
Python Dictionary
A dictionary in Python is an
unordered, mutable collection of data that stores elements in the form
of key–value pairs, written inside curly braces { }. Each element
has a key and its associated value, and values are accessed using
the keys.
1. Creating a Dictionary
# Syntax
my_dict = {key1: value1, key2:
value2, key3: value3}
# Example
fruit_colors = {"apple":
"red", "banana": "yellow", "cherry":
"red"}
2. Accessing Values
print(fruit_colors["apple"]) # red
print(fruit_colors.get("orange",
"Not found")) # Not found
3. Adding or Modifying Items
fruit_colors["orange"] =
"orange" # Add new
fruit_colors["banana"] =
"green" # Modify existing
4. Removing Items
del
fruit_colors["cherry"] #
delete by key
removed =
fruit_colors.pop("apple") # removes and returns value
print(removed) # red
5. Dictionary Properties
- Unordered → items have no fixed order.
- Mutable → items can be added,
changed, or deleted.
- Keys
must be unique.
- Values
can be of any data type.
6. Dictionary Methods
|
Method |
Description |
|
keys() |
Returns all keys |
|
values() |
Returns all values |
|
items() |
Returns all key–value pairs |
|
update() |
Merges another dictionary |
|
clear() |
Removes all items |
|
pop(key) |
Removes and returns value by key |
|
popitem() |
Removes last inserted item |
7. Dictionary Length
print(len(fruit_colors)) # Number of key–value pairs
8. Looping through a Dictionary
for key, value in
fruit_colors.items():
print(key, ":", value)
9. Dictionary Comprehension
squares = {x: x**2 for x in
range(5)}
print(squares) # {0:0, 1:1, 2:4, 3:9, 4:16}
10. Nested Dictionaries
students = {
"John": {"age": 25, "grade":
"A"},
"Anna": {"age": 22, "grade":
"B"}
}
print(students["Anna"]["grade"]) # B
11. Merging Dictionaries
dict1 = {"apple":
"red", "banana": "yellow"}
dict2 = {"cherry":
"red", "orange": "orange"}
dict1.update(dict2) # merge into dict1
Difference between
List and Dictionary in Python
|
List |
Dictionary |
|
Ordered
collection of elements stored inside square brackets [ ]. |
Unordered
collection of key–value pairs stored inside curly braces { }. |
|
Elements
are accessed using index numbers (starting from 0). |
Elements
are accessed using keys. |
|
Single
collection of values. |
Collection
of key–value pairs. |
|
Mutable
(elements can be changed). |
Mutable
(items can be added, changed, or removed). |
|
Allows
duplicate elements. |
Keys
must be unique (values may repeat). |
|
fruits
= ["apple", "banana", "cherry"] |
fruit_colors
= {"apple": "red", "banana":
"yellow"} |
Features of List in Python
- A
list is an ordered collection of items.
- Lists
are created using square brackets [ ].
- Lists
support indexing and slicing, and indexing starts from 0.
- Lists
are mutable, which means elements can be changed after creation.
- A
list can store different data types such as numbers and strings in
a single list.
- Lists
allow duplicate elements.
- Lists
support useful methods such as append(), insert(), remove(), sort(), etc.
Features of Dictionary in Python
- A
dictionary is an unordered collection of key–value pairs.
- Dictionaries
are created using curly braces { }.
- Elements
are accessed using keys, not index numbers.
- Keys
must be unique,
but values can be repeated.
- Dictionaries
are mutable, which means key–value pairs can be added, modified, or
removed.
- A
dictionary can store values of different data types.
- Dictionaries
support useful methods such as keys(), values(), items(), update(), pop(),
etc.
7.15 Uses of Library functions :
String Functions (center, upper, lower, Len), Numeric and mathematical (sum,
pow, round, abs, sqrt, Int)
Function
A function in Python is a block
of reusable code that performs a specific task and is executed only
when it is called.
Types of Functions
1. Built-in Functions
Built-in functions are the functions that are already
defined in Python and can be used directly without creating them.
Examples:
- len()
→ returns length of a list or string
- sum()
→ adds all numbers in a list
- print()
→ displays output
numbers = [1, 2, 3]
print(len(numbers)) # 3
print(sum(numbers)) # 6
2. User-defined Functions
User-defined functions are the functions that are created
by the programmer to perform a specific task and can be reused
whenever required.
Example:
def square(x):
return x * x
print(square(4)) # 16
Difference between Built-in and
User-defined Functions
|
Built-in Functions |
User-defined
Functions |
|
Predefined functions
that come with Python. |
Functions created by
the programmer using the def keyword. |
|
Always available to
use directly. |
Available only after
being defined in the program. |
|
Saves time since no
coding is required. |
Gives flexibility to
design your own logic. |
|
print(), len(),
sum(), abs(). |
def add(a, b): return
a+b, def square(x): return x*x. |
Library function
A library function in Python
is a predefined function that is stored in a module (library) and
can be used by importing that module into a program. They are used by importing
the library and help programmers perform common tasks without writing code
from scratch.
Example:
import math
print(math.sqrt(16))
String Function
String functions in Python are built-in methods
used to perform operations on strings, such as changing case, searching
text, and modifying content.
center(width, fillchar): Centers the string within the
given width, padding it with a specified character (default is a space).
Example:
text = "Hello"
print(text.center(10,
"*")) # Output: '**Hello***'
upper( ): Converts string to uppercase.
Example:
text = "hello"
print(text.upper( )) # Output: 'HELLO'
lower( ): Converts string to lowercase.
Example:
text = "hello"
print(text.lower( )) # Output: 'hello'
len(): Returns length of the string. (i.e.,
the number of characters).
Example:
text = "Hello"
print(len(text)) # Output: 5
Numeric Functions
Numeric functions in Python are built-in
functions used to perform operations on numeric values such as
finding maximum, minimum, absolute value, power, and type conversion.
sum(iterable): Returns the sum of all elements
in an iterable (e.g., a list).
Example:
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # Output: 15
abs(x): Returns the absolute value of a
number.
Example:
print(abs(-5)) # Output: 5
print(abs(3.5)) # Output: 3.5
round(x, n): Rounds a number x to n decimal
places (default is 0).
Example:
print(round(3.14159, 2)) # Output: 3.14
print(round(3.5)) # Output: 4
pow(x, y): Returns x raised to the power of
y (i.e., x^y).
Example:
print(pow(2, 3)) # Output: 8 (2^3)
int(x): Converts a number or string to an
integer.
Example:
print(int(3.7)) # Output: 3
print(int("42")) # Output: 42
min( ) and max( )Function: Returns the smallest (minimum) or
largest(maximum) value from the given iterable or from multiple values passed
as arguments.
Example:
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(min(numbers)) # Output: 1
Mathematical Functions (from math
module)
Mathematical functions are predefined functions provided
by Python in the math module to perform advanced mathematical operations
such as square root, power, trigonometry, and rounding.
math.sqrt(x): Returns the square root of x.
Example:
import math
print(math.sqrt(16)) # Output: 4.0
math.factorial(x) : Returns the factorial of a
number x (i.e., x! = x * (x - 1) * (x - 2) * ... * 1).
Example:
import math
print(math.factorial(5)) # Output: 120 (5! = 5 * 4 * 3 * 2 * 1)
math.pi : Provides the mathematical
constant π (approximately 3.14159).
Example:
import math
print(math.pi) # Output: 3.141592653589793
math.sin(x) and math.cos(x): Return the sine and cosine of x
(where x is in radians).
Example:
import math
print(math.sin(math.radians(30))) # Output: 0.5
print(math.cos(math.radians(60))) # Output: 0.5
math.log(x, base): Returns the logarithm of x to the
given base. If the base is not specified, it returns the natural logarithm
(base e).
Example:
import math
print(math.log(10)) # Output: 2.302585092994046 (natural log of
10)
print(math.log(100, 10)) # Output: 2.0 (logarithm base 10 of 100)

No comments:
Post a Comment