0% found this document useful (0 votes)
24 views

Python Note For Class 9th

Python is a popular programming language known for its simplicity, readability, and versatility. It emphasizes code readability through indentation and straightforward syntax, making it easy for beginners to write and understand code. Python has a broad range of applications including web development, data analysis, machine learning, scientific computing, and more due to its extensive libraries and tools.

Uploaded by

pagalaryan3245
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Python Note For Class 9th

Python is a popular programming language known for its simplicity, readability, and versatility. It emphasizes code readability through indentation and straightforward syntax, making it easy for beginners to write and understand code. Python has a broad range of applications including web development, data analysis, machine learning, scientific computing, and more due to its extensive libraries and tools.

Uploaded by

pagalaryan3245
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Introduction to Python language

Python is a popular high-level programming language that was created by Guido van Rossum and
first released in 1991. It is known for its simplicity, readability, and versatility, making it a preferred
language for various applications such as web development, data analysis, machine learning, artificial
intelligence, and scripting.

Python's design philosophy emphasizes code readability, which means that its syntax and structure
are designed to be clear and intuitive, making it easier for programmers to write and understand
code. This readability is achieved through the use of indentation and a straightforward syntax,
making Python an excellent choice for beginners.

Python Programming and its applications


Python programming has a broad range of applications across various domains. Here are some of the
key areas where Python is commonly used:

Web Development: Python provides several frameworks like Django, Flask, and Pyramid, which
simplify web development. These frameworks offer tools and libraries for handling routing,
templating, database interaction, and other web-related tasks.

Data Analysis and Visualization: Python has become a popular language for data analysis and
visualization. Libraries such as NumPy, Pandas, and Matplotlib provide powerful tools for data
manipulation, analysis, and visualization. Additionally, tools like Jupyter Notebook and pandas make
it easy to work with data and create interactive data visualizations.

Machine Learning and Artificial Intelligence: Python has gained significant popularity in the field of
machine learning and AI. Libraries such as scikit-learn, TensorFlow, Keras, and PyTorch offer a wide
range of tools and algorithms for building and training machine learning models. Python's simplicity
and rich ecosystem make it an ideal choice for researchers and practitioners in this field.

Scientific Computing: Python is widely used for scientific computing tasks due to its extensive
libraries and tools. Libraries like SciPy, NumPy, and pandas provide efficient and convenient methods
for scientific calculations, linear algebra, optimization, and more.

Scripting and Automation: Python's easy-to-understand syntax and versatility make it a powerful
scripting language. It is often used for automating repetitive tasks, writing system scripts, and
creating command-line tools.

Game Development: Python has libraries like Pygame and Panda3D that enable game development.
These libraries provide functions for handling graphics, physics, and game logic, making it easier to
develop games.

Internet of Things (IoT): Python's simplicity and support for libraries like Raspberry Pi provide an
excellent platform for IoT projects. Developers can leverage Python's capabilities to interact with
sensors, control devices, and collect data in IoT applications.

Web Scraping: Python's libraries, such as BeautifulSoup and Scrapy, make it easy to extract data from
websites. Web scraping allows you to automate the extraction of information from web pages, which
can be useful for data collection, analysis, or building web applications.

These are just a few examples of Python's applications. The language's versatility and extensive
libraries enable it to be used in various other domains, including networking, cybersecurity, finance,
natural language processing, and more. Python's popularity and active community contribute to its
continuous growth and adoption in diverse fields.
Python Basics
VARIABLES:
In Python, variables are used to store and manipulate data. They serve as containers that
hold values, and the value stored in a variable can change throughout the program
execution. Variables in Python are dynamically typed, meaning you don't need to declare the
variable's type explicitly.
Let's explore the concepts of declaration, definition, and initialization of variables in Python:
Declaration: In Python, you don't need to explicitly declare variables before using them. You
can simply assign a value to a variable, and Python will automatically create and associate
the variable with that value. For example:
x=5
In this case, x is the variable, and it is declared and associated with the value 5 without any
explicit declaration.
Definition: In Python, the definition of a variable happens at the moment when you assign a
value to it. When you assign a value to a variable, you are defining it and associating that
value with the variable name. For example:
x=5
Here, x is defined as a variable and assigned the value 5.
Initialization: Initialization refers to the process of assigning an initial value to a variable
when it is defined. In Python, you can initialize a variable at the time of declaration or later
in the program. For example:
x = 5 # Initialization at the time of declaration
y # Declaration
y = 10 # Initialization later in the program
In the above code snippet, x is initialized with the value 5 at the time of declaration. In
contrast, y is declared without an initial value and later initialized with the value 10.
It's important to note that Python allows variables to change their values dynamically during
program execution. You can assign a new value to a variable at any point in your code, even
after it has been declared and initialized.
python
Copy code
x=5
print(x) # Output: 5
x = 10
print(x) # Output: 10
In this example, the variable x is first assigned the value 5 and then reassigned the value 10.
The output of the two print statements reflects the updated value of x.
Remember that Python is dynamically typed, so you don't need to explicitly specify the type
of a variable. The type of a variable is determined by the value assigned to it, and it can
change if a different value of a different type is assigned to the same variable later in the
program.

Python operators
Python provides a wide range of operators that allow you to perform various
operations on data. Here are some commonly used operators in Python along
with examples:
Arithmetic Operators:
Addition (+): Adds two values together.
a=5+3
print(a) # Output: 8
Subtraction (-): Subtracts one value from another.
b = 10 - 4
print(b) # Output: 6
Multiplication (*): Multiplies two values.
c=2*5
print(c) # Output: 10
Division (/): Divides one value by another (result is a float).
d = 15 / 3
print(d) # Output: 5.0
Floor Division (//): Divides one value by another and rounds down to the
nearest integer.
e = 15 // 4
print(e) # Output: 3
Modulo (%): Returns the remainder after division.
f = 15 % 4
print(f) # Output: 3
Exponentiation (**): Raises a value to the power of another.
g = 2 ** 3
print(g) # Output: 8
Comparison Operators:
Equal to (==): Checks if two values are equal.
a = 5 == 5
print(a) # Output: True
Not equal to (!=): Checks if two values are not equal.
b = 5 != 3
print(b) # Output: True
Greater than (>): Checks if the left value is greater than the right value.
c=8>6
print(c) # Output: True
Less than (<): Checks if the left value is less than the right value.
d=4<7
print(d) # Output: True
Greater than or equal to (>=): Checks if the left value is greater than or equal to
the right value.
e = 8 >= 8
print(e) # Output: True
Less than or equal to (<=): Checks if the left value is less than or equal to the
right value.
f = 4 <= 6
print(f) # Output: True
Assignment Operators:
Assignment (=): Assigns a value to a variable.
a=5
Addition assignment (+=): Adds a value to the variable and assigns the result to
the variable.
b=3
b += 2 # Equivalent to b = b + 2
print(b) # Output: 5
Subtraction assignment (-=): Subtracts a value from the variable and assigns
the result to the variable.
c = 10
c -= 4 # Equivalent to c = c - 4
print(c) # Output: 6
Multiplication assignment (*=): Multiplies the variable by a value and assigns
the result to the variable.
d=2
d *= 5 # Equivalent to d = d * 5
print(d) # Output: 10
Division assignment (/=): Divides the variable by a value and assigns the result
to the variable.
e = 15
e /= 3 # Equivalent to e = e / 3
print(e) # Output: 5.0
Logical Operators:

Logical AND (and): Returns True if both operands are True.


a = True and False
print(a) # Output: False
Logical OR (or): Returns True if at least one of the operands is True.
b = True or False
print(b) # Output: True
Logical NOT (not): Returns the opposite of the operand's value.
c = not True
print(c) # Output: False
These are just a few examples of the operators available in Python. There are
more operators, such as bitwise operators, membership operators, and identity
operators, which you can explore as you dive deeper into Python programming.
Membership Operator:
In Python, membership operators are used to test whether a value is a member
of a sequence or collection. They evaluate the membership of a value in a
sequence and return a Boolean value (True or False) based on the result. The
two membership operators available in Python are:
in operator: The in operator checks if a value is present in a sequence or
collection. It returns True if the value is found, and False otherwise.
fruits = ['apple', 'banana', 'orange']
print('apple' in fruits) # Output: True
print('grape' in fruits) # Output: False
In the above example, the in operator is used to check if the strings 'apple' and
'grape' are members of the fruits list. The first check returns True because
'apple' is present in the list, while the second check returns False as 'grape' is
not present.
not in operator: The not in operator checks if a value is not present in a
sequence or collection. It returns True if the value is not found, and False
otherwise.
numbers = [1, 2, 3, 4, 5]
print(6 not in numbers) # Output: True
print(3 not in numbers) # Output: False
In the above example, the not in operator is used to check if the numbers 6 and
3 are not members of the numbers list. The first check returns True because 6
is not present in the list, while the second check returns False as 3 is present.
Membership operators are commonly used when you want to check if a value
exists in a list, tuple, set, or any other sequence or collection. They provide a
convenient way to test for membership without the need for iterating through
the elements manually.
Identity Operator
In Python, identity operators are used to compare the identity of two objects,
i.e., whether two objects refer to the same memory location. Identity operators
evaluate the identity relationship between two operands and return a Boolean
value (True or False) based on the comparison result. There are two identity
operators in Python:
is operator: The is operator checks if two objects refer to the same memory
location. It returns True if the operands have the same identity, and False
otherwise.
x = [1, 2, 3]
y=x
z = [1, 2, 3]
print(x is y) # Output: True
print(x is z) # Output: False
In the above example, the is operator is used to compare the identities of
different objects. The first check returns True because x and y refer to the same
list object. However, the second check returns False because x and z are
different list objects, even though they have the same values.
is not operator: The is not operator checks if two objects do not refer to the
same memory location. It returns True if the operands have different identities,
and False if they refer to the same memory location.
a=5
b = 10
print(a is not b) # Output: True
print(a is not a) # Output: False
In the above example, the is not operator is used to compare the identities of
variables a and b. The first check returns True because a and b have different
values and therefore different identities. The second check returns False
because a is the same object as itself.
Identity operators are typically used to compare objects, especially mutable
objects like lists or dictionaries, to determine if they are the same object or if
they refer to different objects in memory. It is important to note that identity
comparison is different from value comparison. Even if two objects have the
same values, they may still be different objects with different identities.
What is expression?
In Python, an expression is a combination of values, variables, operators, and
function calls that can be evaluated to produce a result. It represents a
computation or a calculation that can be performed.
Expressions can be as simple as a single value or variable, or they can involve
complex combinations of operators and operands. Here are some examples of
expressions in Python:
Numeric Expressions:
x=5
y=3
z = x + y * 2 # An expression involving addition and multiplication
String Expressions:
name = "John"
greeting = "Hello, " + name # An expression concatenating strings
Boolean Expressions:
age = 25
is_adult = age >= 18 # An expression using a comparison operator
Function Call Expressions:
import math
sqrt_value = math.sqrt(16) # An expression calling a function
List and Dictionary Expressions:
numbers = [1, 2, 3, 4, 5]
doubled_numbers = [2 * num for num in numbers] # An expression using list
comprehension
Expressions can be used in various contexts, such as assignments, function
arguments, conditional statements, loops, and more. They are evaluated by the
Python interpreter, and the result of the evaluation can be assigned to a
variable, printed, used in further computations, or utilized in other parts of the
program.
Data types of pythons
Python has several built-in data types that are used to represent different kinds
of values. Here are some commonly used data types in Python:
Numeric Types:
int: Represents integer values, such as 1, 10, -5.
float: Represents floating-point values with decimal points, such as 3.14, -0.5.
String Type:
str: Represents sequences of characters enclosed in single quotes ('') or double
quotes (""). For example, "Hello, World!".
Boolean Type:
bool: Represents Boolean values, which can be either True or False. Used for
logical operations and control flow.
Sequence Types:
list: Represents ordered collections of items enclosed in square brackets ([]).
Lists can contain values of different data types and are mutable (can be
modified).
tuple: Represents ordered collections of items enclosed in parentheses (()).
Tuples are similar to lists but are immutable (cannot be modified).
range: Represents a sequence of numbers within a specified range.
Mapping Type:
dict: Represents key-value pairs enclosed in curly braces ({}). Dictionaries are
mutable and allow efficient access to values based on unique keys.
Set Types:
set: Represents an unordered collection of unique elements. Sets are enclosed
in curly braces ({}).
frozenset: Similar to sets but immutable.
Other Types:
None: Represents the absence of a value or a null value.
These are some of the fundamental data types in Python. Additionally, Python
allows for creating custom data types using classes and object-oriented
programming concepts.
To determine the data type of a value or variable, you can use the type()
function:
x=5
print(type(x)) # Output: <class 'int'>
name = "John"
print(type(name)) # Output: <class 'str'>
is_valid = True
print(type(is_valid)) # Output: <class 'bool'>
The type() function returns the data type of the provided value or variable.
Type conversion in python
In Python, type conversion refers to the process of converting a value from one
data type to another. Type conversion can be done implicitly or explicitly.
Implicit Type Conversion (Coercion):
Implicit type conversion, also known as coercion, is performed by Python
automatically when it encounters expressions or operations involving different
data types. It is done to ensure compatibility and consistency in the evaluation
of expressions. For example, when you perform operations between different
numeric types, Python automatically converts one type to another based on a
set of rules known as "type coercion rules."
a=5
b = 2.0
c = a + b # Implicit conversion of 'a' from int to float
print(c) # Output: 7.0
In the above example, the addition operation (a + b) involves an integer (a) and
a float (b). Python implicitly converts the integer a to a float before performing
the addition.
Implicit type conversion can also occur in other scenarios, such as combining
strings with other data types, comparing different data types, or performing
operations with mixed data types.
Explicit Type Conversion (Type Casting):
Explicit type conversion, also known as type casting or type conversion, is the
process of converting a value from one data type to another explicitly using
predefined functions or constructors. In Python, you can use functions like
int(), float(), str(), etc., to explicitly convert values to the desired data type.
x = 10
y = str(x) # Explicit conversion of 'x' from int to str
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'str'>
In the above example, the str() function is used to explicitly convert the integer
x to a string y. The resulting value y is of type string.
Python provides several built-in functions for explicit type conversion, such as:
int(): Converts a value to an integer.
float(): Converts a value to a float.
str(): Converts a value to a string.
list(): Converts a sequence or iterable to a list.
tuple(): Converts a sequence or iterable to a tuple.
set(): Converts a sequence or iterable to a set, removing duplicate elements.
It's important to note that explicit type conversion may result in loss of data or
unexpected behavior if the conversion is not valid. Therefore, it's advisable to
handle type conversions carefully and ensure that the conversion is appropriate
for the given data.
Use of print() and input() functions
Sure! print() and input() are two commonly used functions in Python for
displaying output and receiving input from the user. Here's a simple
explanation of what they do:
print() function:
The print() function is used to display or print output to the console.
You pass one or more values or expressions to print() as arguments, separated
by commas.
It takes those values or expressions and prints them as text on the console.
Example:
print("Hello, World!") # Output: Hello, World!
In the above example, the print() function is used to display the text "Hello,
World!" on the console.
input() function:
The input() function is used to receive input from the user through the console.
It displays a prompt (optional) and waits for the user to enter some text.
The text entered by the user is treated as a string and can be stored in a
variable for further processing.
Example:
name = input("Enter your name: ")
print("Hello, " + name + "!") # Output: Hello, [name]!
In the above example, the input() function prompts the user to enter their
name. The entered name is then stored in the variable name. The print()
function is used to display a greeting message using the entered name.
It's important to note that the input() function waits for the user to provide
input before proceeding with the program execution. It's also worth
mentioning that the input provided through input() is always treated as a
string, even if the user enters a number. If you need to perform operations on
the entered value as a different data type, you'll need to explicitly convert it
using appropriate type conversion functions.
What is mutable and immutable datatype
In Python, data types can be classified as either mutable or immutable. This
classification refers to whether the values of a data type can be changed
(mutable) or not (immutable) after they are created. Let's explore the concepts
of mutable and immutable data types:
Mutable Data Type:
A mutable data type allows modification of its values after they are created.
Any changes made to the value of a mutable object directly modify the object
itself, without creating a new object.
Examples of mutable data types in Python include:
List: A collection of ordered and changeable elements.
Set: An unordered collection of unique elements.
Dictionary: A collection of key-value pairs.
Here's an example demonstrating the mutability of a list:
fruits = ['apple', 'banana', 'orange']
fruits[0] = 'mango' # Modifying the first element of the list
print(fruits) # Output: ['mango', 'banana', 'orange']
In the above example, the value of the list fruits is modified by replacing the
first element ('apple') with 'mango'. The change is made in-place, directly
modifying the original list.
Immutable Data Type:
An immutable data type does not allow modification of its values after they are
created.
Any operation that seems to modify the value of an immutable object actually
creates a new object with the modified value.
Examples of immutable data types in Python include:
Integer: Represents whole numbers.
Float: Represents floating-point numbers.
String: Represents a sequence of characters.
Tuple: An ordered collection of elements.
Here's an example demonstrating the immutability of a string:
message = "Hello"
new_message = message + ", World!" # Concatenating a string
print(new_message) # Output: Hello, World!
print(message) # Output: Hello
In the above example, the concatenation operation (message + ", World!")
creates a new string object with the combined value. The original string object
assigned to message remains unchanged.
Immutable data types provide advantages such as simplicity, thread-safety, and
hashability, while mutable data types offer flexibility and the ability to modify
data in-place. Understanding the mutability or immutability of a data type is
important for correctly handling and manipulating data in Python.
Python list
In Python, a list is a built-in data type that represents an ordered collection of
elements. Lists are mutable, which means their elements can be modified after
creation. Lists are created by enclosing comma-separated values within square
brackets ([]). Each value in the list is called an element, and the elements can
be of different data types. Here's an overview of Python lists and some
common operations:
Creating a List:
fruits = ['apple', 'banana', 'orange']
empty_list = []
In the above example, a list fruits is created with three elements: 'apple',
'banana', and 'orange'. An empty list empty_list is also created.
Accessing Elements:
Elements in a list can be accessed using their index, starting from 0 for the first
element.
print(fruits[0]) # Output: 'apple'
print(fruits[1]) # Output: 'banana'
Modifying Elements:
Elements in a list can be modified by assigning a new value to a specific index.
fruits[0] = 'mango'
print(fruits) # Output: ['mango', 'banana', 'orange']
List Operations:
Adding Elements:
append(): Adds an element to the end of the list.
insert(): Inserts an element at a specific index.
Removing Elements:
remove(): Removes the first occurrence of a specified element.
pop(): Removes and returns the element at a specific index.
Other Operations:
len(): Returns the number of elements in the list.
index(): Returns the index of the first occurrence of a specified element.
List Slicing:
List slicing allows you to extract a portion of a list.
You can specify a range of indices to extract a sublist.
numbers = [1, 2, 3, 4, 5]
sublist = numbers[1:4] # Output: [2, 3, 4]
List Comprehension:
List comprehension is a concise way to create lists based on existing lists.
numbers = [1, 2, 3, 4, 5]
doubled_numbers = [2 * num for num in numbers] # Output: [2, 4, 6, 8, 10]
Lists are versatile and widely used in Python for storing and manipulating
collections of data. They provide various methods and operations to add,
remove, modify, and access elements, making them a powerful tool for
working with ordered data.
Python String
In Python, a string is a sequence of characters enclosed in either single quotes
('') or double quotes (""). Strings are immutable, which means their values
cannot be changed after they are created. Here's an overview of Python strings
and some common operations:
1. Creating a String:
message = "Hello, World!" empty_string = ''
In the above example, a string message is created with the value "Hello,
World!". An empty string empty_string is also created.
2. Accessing Characters: Individual characters in a string can be accessed
using their index, starting from 0 for the first character.
pythonCopy code
print(message[0]) # Output: 'H' print(message[7]) # Output: 'W'
3. String Operations:
 Concatenation: Strings can be concatenated using the + operator.
pythonCopy code
name = "Alice" greeting = "Hello, " + name print(greeting) # Output: "Hello,
Alice"
 Repetition: Strings can be repeated using the * operator.
pythonCopy code
separator = "-" * 5 print(separator) # Output: "-----"
4. String Methods: Python provides several built-in methods for
manipulating strings. Some commonly used methods include:
 len(): Returns the length (number of characters) of a string.
 upper(), lower(): Converts a string to uppercase or lowercase.
 split(): Splits a string into a list of substrings based on a delimiter.
 strip(): Removes leading and trailing whitespace characters from a
string.
 replace(): Replaces occurrences of a specified substring with
another substring.
Example:
text = " Hello, World! " print(len(text)) # Output: 18 print(text.upper()) #
Output: " HELLO, WORLD! " print(text.strip()) # Output: "Hello, World!"
5. String Formatting: Python provides multiple ways to format strings,
including:
 Using the % operator:
pythonCopy code
name = "Alice" age = 25 message = "My name is %s and I am %d years old." %
(name, age) print(message) # Output: "My name is Alice and I am 25 years
old."
 Using f-strings (formatted string literals):
pythonCopy code
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."
Strings are extensively used in Python for storing and manipulating text-based
data. They provide a rich set of methods for string manipulation, formatting,
and transformation.
Python dictionary
In Python, a dictionary is a built-in data type that represents a collection of key-
value pairs. Dictionaries are also known as associative arrays or hash maps in
other programming languages. Dictionaries are mutable, meaning their
elements can be modified after creation. Here's an overview of Python
dictionaries and some common operations:
Creating a Dictionary:
Dictionaries are created by enclosing comma-separated key-value pairs within
curly braces ({}) or by using the dict() constructor.
python
Copy code
student = {'name': 'Alice', 'age': 25, 'grade': 'A'}
empty_dict = {}
In the above example, a dictionary student is created with three key-value
pairs: 'name': 'Alice', 'age': 25, and 'grade': 'A'. An empty dictionary empty_dict
is also created.

Accessing Values:
Dictionary values can be accessed using their corresponding keys.
print(student['name']) # Output: 'Alice'
print(student['age']) # Output: 25
Modifying Values:
Dictionary values can be modified by assigning a new value to a specific key.

python
Copy code
student['age'] = 26
print(student['age']) # Output: 26
Dictionary Operations:

Adding Elements:
Assigning a new value to a new key.
Using the update() method to add multiple key-value pairs.
Removing Elements:
Using the del keyword to remove a specific key-value pair.
Using the pop() method to remove and return a value associated with a specific
key.
Other Operations:
len(): Returns the number of key-value pairs in the dictionary.
keys(): Returns a list of all keys in the dictionary.
values(): Returns a list of all values in the dictionary.
Dictionary Iteration:

Dictionaries can be iterated using loops to access keys or values.


python
Copy code
for key in student:
print(key, student[key])

# Output:
# name Alice
# age 26
# grade A
Dictionary Methods:
Python provides various built-in methods for working with dictionaries. Some
commonly used methods include:

get(): Returns the value associated with a given key, or a default value if the key
is not found.
keys(): Returns a view object of all keys in the dictionary.
values(): Returns a view object of all values in the dictionary.
items(): Returns a view object of all key-value pairs in the dictionary.
Example:

python
Copy code
print(student.get('name')) # Output: 'Alice'
print(student.keys()) # Output: dict_keys(['name', 'age', 'grade'])
print(student.values()) # Output: dict_values(['Alice', 26, 'A'])
print(student.items()) # Output: dict_items([('name', 'Alice'), ('age', 26),
('grade', 'A')])
Dictionaries are commonly used in Python to store and retrieve data based on
specific keys. They provide a flexible and efficient way to organize and
manipulate data, making them useful for various applications.
Python selection (conditional) statement’s
In Python, the if statement allows you to execute different blocks of code based
on different conditions. Apart from the basic if statement, there are three
additional forms of if statements that provide more flexibility in controlling the
flow of your program. Here's an explanation of all four forms of if statements in
Python:

Basic if statement:
The basic if statement allows you to execute a block of code if a condition is
true. It follows this syntax:

python
Copy code
if condition:
# Code block to execute if the condition is true
If the condition is true, the code block under the if statement is executed. If the
condition is false, the code block is skipped. Here's an example:

python
Copy code
age = 20
if age >= 18:
print("You are an adult.")
In this example, the code block print("You are an adult.") is executed because
the condition age >= 18 is true.
if-else statement:
The if-else statement allows you to execute one block of code if a condition is
true and another block of code if the condition is false. It follows this syntax:

python
Copy code
if condition:
# Code block to execute if the condition is true
else:
# Code block to execute if the condition is false
If the condition is true, the code block under the if statement is executed. If the
condition is false, the code block under the else statement is executed. Here's
an example:

python
Copy code
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
In this example, because the condition age >= 18 is false, the code block
print("You are a minor.") is executed.

if-elif-else statement:
The if-elif-else statement allows you to test multiple conditions and execute
different blocks of code based on the first condition that evaluates to true. It
follows this syntax:
python
Copy code
if condition1:
# Code block to execute if condition1 is true
elif condition2:
# Code block to execute if condition1 is false and condition2 is true
else:
# Code block to execute if all conditions are false
The conditions are evaluated in order. If the first condition is true, its
corresponding code block is executed, and the rest of the elif and else blocks
are skipped. If none of the conditions are true, the code block under the else
statement is executed. Here's an example:

python
Copy code
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
In this example, because the condition score >= 80 is true, the code block
print("Grade: B") is executed.

Nested if statement:
You can nest if statements within other if statements to create more complex
conditions.

You might also like