Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Btech (1)

Uploaded by

Saurabh Verma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Btech (1)

Uploaded by

Saurabh Verma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Unit-I

Introduction to Python
History of Python Programming Language

🧑‍💻 Creator:

 Guido van Rossum, a Dutch programmer, started working on Python in the late 1980s.
 He officially released it as Python 0.9.0 in February 1991.

🐍 Why the Name 'Python'?

 Guido named it "Python" after the British comedy group Monty Python, not the snake.
He wanted a name that was short, unique, and slightly mysterious.

Timeline of Major Python Versions

✅ 1991 – Python 0.9.0

 Included classes, functions, exception handling, and core data types like str, list, dict.

✅ 1994 – Python 1.0

 First official full release.


 Introduced modules, lambda, map, filter, and reduce.

✅ 2000 – Python 2.0

 Introduced list comprehensions, garbage collection using reference counting and cycle-
detecting GC.
 Python 2 series lasted till Python 2.7 (2010), which was supported until January 1, 2020.

✅ 2008 – Python 3.0

 Known as "Python 3000" or "Py3k".


 Not backward-compatible with Python 2.
 Introduced print() function, better Unicode handling, and new syntax.

🔄 Python Today
 The latest stable version is part of the Python 3 series.
 Python is one of the most popular programming languages due to its simplicity,
versatility, and wide range of applications: web development, AI/ML, data science,
automation, etc.

🧠 Fun Fact:

Python is open-source and has a huge community contributing to its development via PEPs
(Python Enhancement Proposals).

Python is one of the top programming languages in the world, widely used in
fields such as AI, machine learning, data science, and web development.

The simple and English-like syntax of Python makes it a go-to language for
beginners who want to get into coding quickly.

Because Python is used in multiple fields, there is a high demand for Python
developers, with competitive base salaries.

In this guide, we will cover:

Getting Started with Python

Python is a versatile, high-level programming language that is widely


supported across all major operating systems.

You can run Python on your computer using the following two methods:

 Run Python online

 Install Python on your computer

In this tutorial, you will learn both methods.

Run Python Online

To execute Python code, you need to have a Python interpreter installed on


your system. However, if you want to start immediately, you can use our
free online Python editor.
The online editor enables you to run Python code directly in your browser—
no installation required.

Install Python on Your Computer

For those who prefer to install Python on your computer, this guide will walk
you through the installation process on Windows, macOS, and Linux
(Ubuntu).

Windows

To install Python on your Windows, just follow these steps:

1. Install VS Code

2. Download Python Installer File

3. Run the Installer

4. Install Python

5. Verify your installation

Here is a detailed explanation of each of the steps:

Step 1: Install VS Code

Go to the VS Code Official website and download the Windows installer. Once
the download is complete, run the installer and follow the installation
process.

Click Finish to complete the installation process

Step 2: Download the Python Installer File


Go to the official Python website and download the latest version (Python
3.12.2 at the time of writing this tutorial) for Windows.

The website automatically detects your operating system and gives you the
right installer.

Step 3: Run the Installer

Now, go to your download folder and run the installer you just downloaded.
Depending on your security settings, you might be prompted to allow access.

Simply allow it and proceed.

Step 4: Install Python

Once you have run the installer, you will come across this screen.
On the screen, you will see two options: Install Now and Customize
Installation. We suggest you skip all customization steps and simply
click Install Now.

 Check on Add python.exe to PATH as it ensures Python is added to


our system's PATH variable.(Recommended)

 Click Install Now, as it will include all the necessary files needed later.

This makes it easier to run a Python Program from the command prompt
(cmd) directly without specifying the full path of the Python executable.

After using this option, Python will be successfully installed in your device.
Step 4: Verify your installation

After the installation is complete, you can verify whether Python is installed
by using the following command in the command prompt.

python --version

Note: The version number might differ from the one above, depending on
your installed version.

Now, you are all set to run Python programs on your device.
Run Your First Python Program

First open VS Code, click on the File in the top menu and then select New
File.

Then, save this file with a .py extension by clicking on File again, then Save
As, and type your filename ending in .py. (Here, we are saving it as
Hello_World.py)

Before you start coding, make sure the Python extension is installed in VS
Code. Open VS Code and click on Extensions on the left sidebar. Then, search
for the Python extension by Microsoft and click on install.
Now, write the following code into your file:

print("Hello World")

Then click on the run button on the top right side of your screen.

You should see Hello World printed to the command prompt.

Note: Type python3 in command prompt for macOS and Linux.

Now that you have set everything up to run Python programs on your
computer, you'll be learning how the basic program works in Python in the
next tutorial.

Your First Python Program

In the previous tutorial, you learned how to install Python on your computer.
Now, let's write a simple Python program.

The following program displays Hello, World! on the screen.

print("Hello, World!")
Output

Hello World!

Note: A Hello World! program includes the basic syntax of a programming


language and helps beginners understand the structure before getting
started. That's why it is a common practice to introduce a new language
using a Hello World! program.

Working of the Program

Congratulations on writing your first Python program. Now, let's see how the
above program works.

In Python, anything inside print() is displayed on the screen.

There are two things to note about print():

 Everything we want to display on the screen is included inside the


parentheses ().

 The text we want to print is placed within double quotes " ".

We can also use single quotes to print text on the screen. For example,

print('Hello World!')

is same as

print("Hello World!")

o be consistent, we will be using double quotes throughout the tutorials.

Next, we will be learning about Python comments.

Python Comments

In the previous tutorial, you learned to write your first Python program. Now,
let's learn about Python comments.
Important!: We are introducing comments early in this tutorial series
because we will be using them to explain the code in upcoming tutorials.

Comments are hints that we add to our code to make it easier to understand.
Python comments start with #. For example,

# print a number

print(25)

Here, # print a number is a comment.

Comments are completely ignored and not executed by code editors.

Important: The purpose of this tutorial is to help you understand comments,


so you can ignore other concepts used in the program. We will learn about
them in later tutorials.

Single-line Comment

We use the hash (#) symbol to write a single-line comment. For example,

# declare a variable

name = "John"

# print name

print(name) # John

n the above example, we have used three single-line comments:

 # declare a variable

 # print name

 # John

A single-line comment starts with # and extends up to the end of the line.
We can also use single-line comments alongside the code:

print(name) # John

Note: Remember the keyboard shortcut to apply comments. In most text


editors, it's Ctrl + / if you are on Windows & Cmd + / if you are on a Mac.
Multiline Comments

Unlike languages such as C++ and Java, Python doesn't have a dedicated
method to write multi-line comments.

However, we can achieve the same effect by using the hash (#) symbol at
the beginning of each line.

Let's look at an example.

# This is an example of a multiline comment

# created using multiple single-line commenced

# The code prints the text Hello World

print("Hello, World!")

We can also use multiline strings as comments like:

'''This is an example

of multiline comment'''

print("Hello, World!")

Output

Hello World

Note: Remember you will learn about these programming concepts in


upcoming tutorials. For now. you can just focus on the usage of comments.

Prevent Executing Code Using Comments

Comments are valuable when debugging code.

If we encounter an error while running a program, instead of removing code


segments, we can comment them out to prevent execution. For example,

number1 = 10

number2 = 15

sum = number1 + number2

print("The sum is:", sum)

print("The product is:", product)


Here, the code throws an error because we have not defined
a product variable. Instead of removing the line causing an error, we can
comment it.

For example,

number1 = 10

number2 = 15

sum = number1 + number2

print("The sum is:", sum)

# print('The product is:', product)

Output

The sum is 25

Here, the code runs without any errors.

We have resolved the error using a comment. Now if you need to calculate
the product in the near future, you can uncomment it.

Note: This approach comes in handy while working with large files. Instead
of deleting any line, we can use comments and identify which one is causing
an error.

Why Use Comments?

We should use comments:

 For future references, as comments make our code readable.

 For debugging.

 For code collaboration, as comments help peer developers to


understand each other's code.

Note: Comments are not and should not be used as a substitute to explain
poorly written code. Always try to write clean, understandable code, and
then use comments as an addition.

In most cases, always use comments to explain 'why' rather than 'how' and
you are good to go.
Python Variables and Literals

In the previous tutorial you learned about Python comments. Now, let's learn
about variables and literals in Python.

Python Variables

In programming, a variable is a container (storage area) to hold data. For


example,

number = 10

Here, number is a variable storing the value 10.

Assigning values to Variables in Python

As we can see from the above example, we use the assignment


operator = to assign a value to a variable.

# assign value to site_name variable

site_name = 'Facebook'

print(site_name)

# Output: Facebook

Output

Facebook

In the above example, we assigned the value Facebook to


the site_name variable. Then, we printed out the value assigned
to site_name

Note: Python is a type-inferred language, so you don't have to explicitly


define the variable type. It automatically knows that Facebook is a string and
declares the site_name variable as a string.

Changing the Value of a Variable in Python

site_name = 'Hospital'

print(site_name)

# assigning a new value to site_name

site_name = 'apple.com'
print(site_name)

Output

Hospital

apple.com

Here, the value of site_name is changed from 'Hosital' to 'apple.com'.

Example: Assigning multiple values to multiple variables

a, b, c = 5, 3.2, 'Hello'

print (a) # prints 5

print (b) # prints 3.2

print (c) # prints Hello

If we want to assign the same value to multiple variables at once, we can do


this as:

site1 = site2 = 'Asif'

print (site1) # prints programiz.com

print (site2) # prints programiz.com

Here, we have assigned the same string value 'Asif' to both the
variables site1 and site2.

Rules for Naming Python Variables

1. Constant and variable names should have a combination of letters in


lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore (_). For example:

snake_case

MACRO_CASE

camelCase

CapWords

2. Create a name that makes sense. For example, vowel makes more sense
than v.
3. If you want to create a variable name having two words, use underscore to
separate them. For example:

my_name

current_salary

5. Python is case-sensitive. So num and Num are different variables. For


example,

var num = 5

var Num = 55

print(num) # 5

print(Num) # 55

6. Avoid using keywords like if, True, class, etc. as variable names.

Python Literals

Literals are representations of fixed values in a program. They can be


numbers, characters, or strings, etc. For example, 'Hello,
World!', 12, 23.0, 'C', etc.

Literals are often used to assign values to variables or constants. For


example,

site_name = 'My Name is Asif'

In the above expression, site_name is a variable, and 'My Name is Asif' is a


literal.

There are different types of literals in Python. Let's discuss some of the
commonly used types in detail.

Python Numeric Literals

Numeric Literals are immutable (unchangeable). Numeric literals can belong


to 3 different numerical types: Integer, Float, and Complex.

1. Integer Literals

Integer literals are numbers without decimal parts. It also consists of


negative numbers. For example, 5, -11, 0, 12, etc.

2. Floating-Point Literals

Floating-point literals are numbers that contain decimal parts.


Just like integers, floating-point numbers can also be both positive and
negative. For example, 2.5, 6.76, 0.0, -9.45, etc.

3. Complex Literals

Complex literals are numbers that represent complex numbers.

Here, numerals are in the form a + bj, where a is real and b is imaginary. For
example, 6+9j, 2+3j.

Python String Literals

In Python, texts wrapped inside quotation marks are called string literals..

"This is a string."

We can also use single quotes to create strings.

'This is also a string.'

Python Type Conversion

In programming, type conversion is the process of converting data of one


type to another. For example: converting int data to str.

There are two types of type conversion in Python.

 Implicit Conversion - automatic type conversion

 Explicit Conversion - manual type conversion

Python Implicit Type Conversion


In certain situations, Python automatically converts one data type to another.
This is known as implicit type conversion.

Example 1: Converting integer to float


Let's see an example where Python promotes the conversion of the lower
data type (integer) to the higher data type (float) to avoid data loss.
integer_number = 123

float_number = 1.23
new_number = integer_number + float_number

# display new value and resulting data type

print("Value:",new_number)

print("Data Type:",type(new_number))

Output

Value: 124.23

Data Type: <class 'float'>

In the above example, we have created two


variables: integer_number and float_number of int and float type
respectively.

Then we added these two variables and stored the result in new_number.

As we can see new_number has value 124.23 and is of the float data type.

It is because Python always converts smaller data types to larger data types
to avoid the loss of data.

Note:

 We get TypeError, if we try to add str and int. For example, '12' + 23.
Python is not able to use Implicit Conversion in such conditions.

 Python has a solution for these types of situations which is known as


Explicit Conversion.

Explicit Type Conversion


In Explicit Type Conversion, users convert the data type of an object to
required data type.

We use the built-in functions like int(), float(), str(), etc to perform explicit type
conversion.
This type of conversion is also called typecasting because the user casts
(changes) the data type of the objects.
Example 2: Addition of string and integer Using Explicit Conversion

num_string = '12'

num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion

num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)

print("Data type of num_sum:",type(num_sum))

Output

Data type of num_string before Type Casting: <class 'str'>

Data type of num_string after Type Casting: <class 'int'>

Sum: 35

Data type of num_sum: <class 'int'>

In the above example, we have created two


variables: num_string and num_integer with str and int type values
respectively. Notice the code,

num_string = int(num_string)

Here, we have used int() to perform explicit type conversion of num_string to


integer type.
After converting num_string to an integer value, Python is able to add these
two variables.

Finally, we got the num_sum value i.e 35 and data type to be int.

Key Points to Remember

1. Type Conversion is the conversion of an object from one data type to


another data type.

2. Implicit Type Conversion is automatically performed by the Python


interpreter.

3. Python avoids the loss of data in Implicit Type Conversion.

4. Explicit Type Conversion is also called Type Casting, the data types of
objects are converted using predefined functions by the user.

5. In Type Casting, loss of data may occur as we enforce the object to a


specific data type.

Python Basic Input and Output

Python Output

In Python, we can simply use the print() function to print output. For
example,

print('Python is powerful')

# Output: Python is powerful

Python Basic Input and Output

Python Output

In Python, we can simply use the print() function to print output. For
example,

print('Python is powerful')

# Output: Python is powerful


Here, the print() function displays the string enclosed inside the single
quotation.

Syntax of print()

In the above code, the print() function is taking a single parameter.

However, the actual syntax of the print function accepts 5 parameters

print(object= separator= end= file= flush=)

Here,

 object - value(s) to be printed

 sep (optional) - allows us to separate multiple objects inside print().

 end (optional) - allows us to add add specific values like new line "\n",
tab "\t"

 file (optional) - where the values are printed. It's default value
is sys.stdout (screen)

 flush (optional) - boolean specifying if the output is flushed or


buffered. Default: False

Example 1: Python Print Statement


print('Good Morning!')

print('It is rainy today')

Output

Good Morning!

It is rainy today

In the above example, the print() statement only includes the object to be
printed. Here, the value for end is not used. Hence, it takes the default
value '\n'.

So we get the output in two different lines.

Example 2: Python print() with end Parameter

# print with end whitespace

print('Good Morning!', end= ' ')


print('It is rainy today')

Output

Good Morning! It is rainy today

Notice that we have included the end= ' ' after the end of the
first print() statement.

Hence, we get the output in a single line separated by space.

Example 3: Python print() with sep parameter

print('New Year', 2023, 'See you soon!', sep= '. ')

Output

New Year. 2023. See you soon!

In the above example, the print() statement includes


multiple items separated by a comma.

Notice that we have used the optional parameter sep= ". " inside
the print() statement.

Hence, the output includes items separated by . not comma.

Example: Print Python Variables and Literals

We can also use the print() function to print Python variables. For example,

number = -10.6

name = "Programiz"

# print literals

print(5)

# print variables

print(number)

print(name)

Output

5
-10.6

Programiz

Example: Print Concatenated Strings

We can also join two strings together inside the print() statement. For
example,

print('Programiz is ' + 'awesome.')

Output

Programiz is awesome.

Here,

 the + operator joins two strings 'Programiz is ' and 'awesome.'

 the print() function prints the joined string

Output formatting

Sometimes we would like to format our output to make it look attractive. This
can be done by using the str.format() method. For example,

x=5

y = 10

print('The value of x is {} and y is {}'.format(x,y))

Here, the curly braces {} are used as placeholders. We can specify the order
in which they are printed by using numbers (tuple index).

To learn more about formatting the output, visit Python String format().

Python Input

While programming, we might want to take the input from the user. In
Python, we can use the input() function.

Syntax of input()

input(prompt)

Here, prompt is the string we wish to display on the screen. It is optional.

Example: Python User Input

# using input() to take user input


num = input('Enter a number: ')

print('You Entered:', num)

print('Data type of num:', type(num))

Output

Enter a number: 10

You Entered: 10

Data type of num: <class 'str'>

In the above example, we have used the input() function to take input from
the user and stored the user input in the num variable.

It is important to note that the entered value 10 is a string, not a number.


So, type(num) returns <class 'str'>.

To convert user input into a number we can use int() or float() functions as:

num = int(input('Enter a number: '))

Here, the data type of the user input is converted from string to integer .

Python Operators

Operators are special symbols that perform operations on variables and


values. For example,

print(5 + 6) # 11

Here, + is an operator that adds two numbers: 5 and 6.

Types of Python Operators

Here's a list of different types of Python operators that we will learn in this
tutorial.

1. Arithmetic Operators

2. Assignment Operators

3. Comparison Operators

4. Logical Operators

5. Bitwise Operators
6. Special Operators

1. Python Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like


addition, subtraction, multiplication, etc. For example,

sub = 10 - 5 # 5

Here, - is an arithmetic operator that subtracts two values or variables.

Operat
Operation Example
or

+ Addition 5+2=7

- Subtraction 4-2=2

* Multiplication 2*3=6

/ Division 4/2=2

// Floor Division 10 // 3 = 3

% Modulo 5%2=1

** Power 4 ** 2 = 16

Example 1: Arithmetic Operators in Python

a=7

b=2
# addition

print ('Sum: ', a + b)

# subtraction

print ('Subtraction: ', a - b)

# multiplication

print ('Multiplication: ', a * b)

# division

print ('Division: ', a / b)

# floor division

print ('Floor Division: ', a // b)

# modulo

print ('Modulo: ', a % b)

# a to the power b

print ('Power: ', a ** b)

Output

Sum: 9

Subtraction: 5

Multiplication: 14

Division: 3.5

Floor Division: 3

Modulo: 1

Power: 49

In the above example, we have used multiple arithmetic operators,

 + to add a and b

 - to subtract b from a
 * to multiply a and b

 / to divide a by b

 // to floor divide a by b

 % to get the remainder

 ** to get a to the power b

2. Python Assignment Operators


Assignment operators are used to assign values to variables. For example,

# assign 5 to x

x=5

Here, = is an assignment operator that assigns 5 to x.

Here's a list of different assignment operators available in Python.

Operat
Name Example
or

= Assignment Operator a=7

+= Addition Assignment a += 1 # a = a + 1

-= Subtraction Assignment a -= 3 # a = a - 3

*= Multiplication Assignment a *= 4 # a = a * 4

/= Division Assignment a /= 3 # a = a / 3

%= Remainder Assignment a %= 10 # a = a % 10

**= Exponent Assignment a **= 10 # a = a ** 10


Example 2: Assignment Operators

# assign 10 to a

a = 10

# assign 5 to b

b=5

# assign the sum of a and b to a

a += b #a=a+b

print(a)

# Output: 15

Here, we have used the += operator to assign the sum of a and b to a.

Similarly, we can use any other assignment operators as per our needs.

3. Python Comparison Operators

Comparison operators compare two values/variables and return a boolean


result: True or False. For example,

a=5

b=2

print (a > b) # True


Here, the > comparison operator is used to compare whether a is greater
than b or not.

Operat
Meaning Example
or

== Is Equal To 3 == 5 gives us False

!= Not Equal To 3 != 5 gives us True

> Greater Than 3 > 5 gives us False

< Less Than 3 < 5 gives us True

>= Greater Than or Equal To 3 >= 5 give us False

<= Less Than or Equal To 3 <= 5 gives us True

a=5

b=2

# equal to operator

print('a == b =', a == b)

# not equal to operator

print('a != b =', a != b)

# greater than operator


print('a > b =', a > b)

# less than operator

print('a < b =', a < b)

# greater than or equal to operator

print('a >= b =', a >= b)

# less than or equal to operator

print('a <= b =', a <= b)

Output

a == b = False

a != b = True

a > b = True

a < b = False

a >= b = True

a <= b = False

Note: Comparison operators are used in decision-making and loops. We'll


discuss more of the comparison operator and decision-making in later
tutorials.

4. Python Logical Operators

Logical operators are used to check whether an expression is True or False.


They are used in decision-making. For example,

a=5

b=6

print((a > 2) and (b >= 6)) # True

Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True,
the result is True.
Operat
Example Meaning
or

Logical AND:
and a and b
True only if both the operands are True

Logical OR:
or a or b
True if at least one of the operands is True

Logical NOT:
not not a
True if the operand is False and vice-versa.

Example 4: Logical Operators

# logical AND

print(True and True) # True

print(True and False) # False

# logical OR

print(True or False) # True

# logical NOT

print(not True) # False

Note: Here is the truth table for these logical operators.

5. Python Bitwise operators

Bitwise operators act on operands as if they were strings of binary digits.


They operate bit by bit, hence the name.

For example, 2 is 10 in binary, and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000


0100 in binary)
Operat
Meaning Example
or

& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x >> 2 = 2 (0000 0010)

<< Bitwise left shift x 0010 1000)

6. Python Special operators

Python language offers some special types of operators like


the identity operator and the membership operator. They are described
below with examples.

Identity operators

In Python, is and is not are used to check if two values are located at the
same memory location.
It's important to note that having two variables with equal values doesn't
necessarily mean they are identical.

Operat
Meaning Example
or

True if the operands are identical (refer to the same


is x is True
object)

True if the operands are not identical (do not refer x is not
is not
to the same object) True

Example 4: Identity operators in Python

x1 = 5

y1 = 5

x2 = 'Hello'

y2 = 'Hello'

x3 = [1,2,3]

y3 = [1,2,3]

print(x1 is not y1) # prints False

print(x2 is y2) # prints True

print(x3 is y3) # prints False

Here, we see that x1 and y1 are integers of the same values, so they are
equal as well as identical. The same is the case with x2 and y2 (strings).

But x3 and y3 are lists. They are equal but not identical. It is because the
interpreter locates them separately in memory, although they are equal.

Membership operators
In Python, in and not in are the membership operators. They are used to test
whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).

In a dictionary, we can only test for the presence of a key, not the value.

Operat
Meaning Example
or

in True if value/variable is found in the sequence 5 in x

True if value/variable is not found in the 5 not in


not in
sequence x

Example 5: Membership operators in Python

message = 'Hello world'

dict1 = {1:'a', 2:'b'}

# check if 'H' is present in message string

print('H' in message) # prints True

# check if 'hello' is present in message string

print('hello' not in message) # prints True

# check if '1' key is present in dict1

print(1 in dict1) # prints True

# check if 'a' key is present in dict1

print('a' in dict1) # prints False

Output

True

True

True
False

Here, 'H' is in message, but 'hello' is not present in message (remember,


Python is case-sensitive).

Similarly, 1 is key, and 'a' is the value in dictionary dict1. Hence, 'a' in
y returns False.

Python if...else Statement

In computer programming, the if statement is a conditional statement. It is


used to execute a block of code only when a specific condition is met. For
example,

Suppose we need to assign different grades to students based on their


scores.

1. If a student scores above 90, assign grade A

2. If a student scores above 75, assign grade B

3. If a student scores above 65, assign grade C

These conditional tasks can be achieved using the if statement.

Python if Statement

An if statement executes a block of code only when the specified condition is


met.

Syntax

if condition:

# body of if statement

Here, condition is a boolean expression, such as number > 5, that evaluates


to either True or False.

 If condition evaluates to True, the body of the if statement is executed.

 If condition evaluates to False, the body of the if statement will be


skipped from execution.
Let's look at an example.

Example: Python if Statement

Example: Python if Statement

number = int(input('Enter a number: '))

# check if number is greater than 0

if number > 0:

print(f'{number} is a positive number.')

print('A statement outside the if statement.')

Sample Output 1

Enter a number: 10

10 is a positive number.

A statement outside the if statement.

If user enters 10, the condition number > 0 evaluates to True. Therefore, the
body of if is executed.

Sample Output 2

Enter a number: -2
A statement outside the if statement.

If user enters -2, the condition number > 0 evaluates to False. Therefore, the
body of if is skipped from execution.

Indentation in Python

Python uses indentation to define a block of code, such as the body of


an if statement. For example,

x=1

total = 0

# start of the if statement

if x != 0:

total += x

print(total)

# end of the if statement

print("This is always executed.")

Here, the body of if has two statements. We know this because two
statements (immediately after if) start with indentation.

We usually use four spaces for indentation in Python, although any number
of spaces works as long as we are consistent.

You will get an error if you write the above code like this:

# Error code

x=1

total = 0

if x != 0:

total += x

print(total)
Here, we haven't used indentation after the if statement. In this case, Python
thinks our if statement is empty, which results in an error.

Python if...else Statement

An if statement can have an optional else clause. The else statement


executes if the condition in the if statement evaluates to False.

Syntax

if condition:

# body of if statement

else:

# body of else statement

Here, if the condition inside the if statement evaluates to

 True - the body of if executes, and the body of else is skipped.

 False - the body of else executes, and the body of if is skipped

Let's look at an example.


Example: Python if…else Statement

number = int(input('Enter a number: '))

if number > 0:

print('Positive number')

else:

print('Not a positive number')

print('This statement always executes')

Sample Output 1

Enter a number: 10

Positive number

This statement always executes

If user enters 10, the condition number > 0 evalutes to True. Therefore, the
body of if is executed and the body of else is skipped.

Sample Output 2

Enter a number: 0

Not a positive number

This statement always executes

If user enters 0, the condition number > 0 evalutes to False. Therefore, the
body of if is skipped and the body of else is executed.

Python if…elif…else Statement

The if...else statement is used to execute a block of code among two


alternatives.

However, if we need to make a choice between more than two alternatives,


we use the if...elif...else statement.

Syntax

if condition1:

# code block 1
elif condition2:

# code block 2

else:

# code block 3

Let's look at an example.

Example: Python if…elif…else Statement

number = -5

if number > 0:

print('Positive number')

elif number < 0:

print('Negative number')

else:

print('Zero')

print('This statement is always executed')


Output

Negative number

This statement is always executed

Here, the first condition, number > 0, evaluates to False. In this scenario, the
second condition is checked.

The second condition, number < 0, evaluates to True. Therefore, the


statements inside the elif block is executed.

In the above program, it is important to note that regardless the value


of number variable, only one block of code will be executed.

Python Nested if Statements

It is possible to include an if statement inside another if statement. For


example,

number = 5

# outer if statement

if number >= 0:

# inner if statement

if number == 0:

print('Number is 0')

# inner else statement

else:

print('Number is positive')

# outer else statement

else:

print('Number is negative')

Output
Number is positive

Here's how this program works.

You might also like