0% found this document useful (0 votes)
35 views44 pages

Introduction to Python Programming Basics

Python is an open-source, high-level programming language known for its user-friendly syntax and extensive libraries. Introduced by Guido van Rossum in 1980, Python has evolved through various versions, with significant features including ease of learning, versatility, and a strong community. The document also covers Python installation on Windows, variable creation, and various types of operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views44 pages

Introduction to Python Programming Basics

Python is an open-source, high-level programming language known for its user-friendly syntax and extensive libraries. Introduced by Guido van Rossum in 1980, Python has evolved through various versions, with significant features including ease of learning, versatility, and a strong community. The document also covers Python installation on Windows, variable creation, and various types of operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit -1

Introduction To Python

Introduction And Basics:


Python is an open-source, object-oriented, high-level programming language. It provides
user-friendly syntax because it resembles the natural English language. It can be integrated into
any project and used to solve advanced problems. Python has a large library of predefined
modules and functions, it provides different frameworks for all sorts of development, whether it
is for the backend or the frontend.

History In
1980, Python was introduced by Guido van Rossum. He was doing research in the Netherlands at
the National Research Institute for Mathematics and Computer Science, where he invented the
Python programming language. Unlike other languages that have hard syntax and are quite tough
to learn, he wanted to create an easy programming language similar to English so it can be easy
to read and write. Though it took him 11 years to launch the first version, and that too had only a
few basic functionalities and data types.

Later on in 1994, it became popular among a group of scientists, and Python 1.0 was released
with more advanced features like map, lambda, and filter functions. The further versions
introduced in Python are as follows:

o In 1997 the Python 1.5 was introduced


o In 2000 Python 2.0 was released
o In 2008, Python 3.0 in was launched with newer functionalities
o In 2022, Python 3.11 was released with more features and functionalities.

Python Syntax

Python has intuitive syntax that is easy to learn and write because of its resemblance to a natural
English language. For beginners who are just entering the programming world, it is very
beneficial.

Let's write a simple code to write a "Hello World" program in Python:

Example

1. # code
2. print("Hello World")
Execute Now
Output:

Hello World

Features of Python

Python has plenty of features that make it the most demanding and popular. Let's read about a
few of the best features that Python has:

o Python is easy to learn, read, write and comprehend.


o It is an interpreted language.
o It is object-oriented programming language.
o Python is Free and open-source for both individuals and businesses.
o It supports multi-platform and therefore can be integrated with any project.
o It has a huge library that consists of different libraries, frameworks, and well-documented
module.
o It is versatile, extensible and flexible programming language
o Python supports GUI.
o It is a dynamically typed language.
o Python has a huge community that is constantly developed, improved, and expanded.

Applications of Python

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.

Setting Up Path Python

Python is among the most widely used programming languages. Due to its user-friendliness,
readability, and extensive library ecosystem, whether you are a novice or an expert developer,
the first step to accomplish this is to install Python on Windows if you wish to write and
execute Python programs.

Here, we are going to learn how to install Python on Windows step-by-step.


In order to install Python on other platforms like Mac, Ubuntu and more, check out the following
links:

o Mac: how-to-install-python-on-mac
o CentOS: how-to-install-python-on-centos
o Ubuntu: how-to-install-python-in-ubuntu
Installing Python on Windows

Python doesn't come with prepackage in Windows, but it doesn't mean that Window user cannot
be flexible with Python. Some operating systems such as Linux come with the Python package
manager that can run to install Python. Below are the steps to install Python in Windows.

Step 1: Downloading the Installer for Python


To install Python on Windows, you first have to take the Python installer from the internet.
Visit the official website of Python:

o Open your favourite web browser, be it Google Chrome, Edge, or Firefox.


o Go to the official site for downloading Python at: [Link]
o The website will automatically check what operating system you are using and provide
the most recent stable version of Python for Windows users
Choose the Correct Version
Selecting the appropriate version

o Latest stable releases, such as Python 3.13.2, are recommended for all users.

o To view the older version, scroll down the page and click on "View all Python releases."
1.3 Installer Download
o To begin, click on the button that has the "Download Python 3.13.2" text.

o An exe file indicative of an executable will be downloaded (for example, python-


[Link]).
Step 2: Running of the Python Installer
After downloading the installer file, you have to run it.
2.1 Finding the Installer

o Go to the directory of the downloaded folder (usually, it is in the Downloads folder).


o To start the installation process, double-click on the exe file.

2.2 Selecting Installation Preferences


Upon the appearance of the setup window of Python, these options will be available: You have
to do these things:
1. There is "Add Python to PATH," which you will be required to check the box next to it.
This step must be done with utmost care as it is very critical.

o Checking this box will ensure that using the command prompt, you can control the use of
Python at any given location or position.
2. Decide from the given options:

o (default) "Install Now" Installs with the default options selected.


o "Customize installation" where you get the freedom to set different options for the
installation.
o From options 1 and 2, if you are a starter, it is best that you click on "Install Now" to
install with the pre-set options.
2.3 Commencing Installation
o To begin the installation, select "Install now."
o At this point, your system will have Python files copied into it.
Step 3: Installation Completion Duration
The whole process might take a few minutes.

o After completing the process, the statement "Setup was successful" will appear.
o To exit the installer, click on the "Close" button.

Step 4: Verify Python Installation


To successfully confirm that Python was installed, kindly follow the procedure listed below:
4.1 Open Command Prompt

o Open the Command Prompt window by pressing Win + R, followed by typing cmd and
pressing Enter.
4.2 Check Python Version

o To check if the application was successfully installed, type the following command and
press enter:
1. $ python --version

o In the event Python was installed properly, it will show the following:

3.9.7 (where the number following 3 is the version number)


In the situation that the command yields an error, it may indicate that Python is not added to the
system PATH.

Step 5: Verify pip Installation


Pip is known as a package manager, which enables the installation and management of Python
libraries.
5.1 Check if pip is Installed

o Command Prompt can be opened by typing:


1. $ pip --version

Step 6: Test Python with the Command Prompt


In an effort to test if Python is working correctly, attempt to run basic Python scripts.
1. Command Prompt (cmd) can be opened.
2. Type:
1. $ python
A Python interactive shell page will open, revealing the Python version with ">>>" following it.
3. Type the following statement:
1. print("Hello World!")
4. Assuming that Python was installed properly, it will show:
1. Hello, World!
5. To close Python, the following command can be used:
1. exit()

variables

Variables are containers for storing data values.

Creating Variables:
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Eg.
x=5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type, and can even change type after
they have been set.

Eg.
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0

Single or Double Quotes?

String variables can be declared either by using single or double quotes:

x = "John"
# is the same as
x = 'John'

Case-Sensitive:

Variable names are case-sensitive.


This will create two variable
a=4
A = "Sally"
#A will not overwrite a

Rules for Python variables:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)
 A variable name cannot be any of the Python keywords.

Legal variable name:


myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Illegal variable name:


2myvar = "John"
my-var = "John"
my var = "John"

Multi Words Variable Names:


Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:

Camel Case:

Each word, except the first, starts with a capital letter:


myVariableName = "John"

Pascal Case:

Each word starts with a capital letter:


MyVariableName = "John"

Snake Case:
Each word is separated by an underscore character:
my_variable_name = "John"

Many Values to Multiple Variables:

Python allows you to assign values to multiple variables in one line:


ExampleGet your own Python Server
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Note: Make sure the number of variables matches the number of values, or else you will get an
error.

One Value to Multiple Variables:

And you can assign the same value to multiple variables in one line:
Eg.
x = y = z = "Orange"
print(x)
print(y)
print(z)

Unpack a Collection

If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.

:fruits = ["apple", "banana", "cherry"]


x, y, z = fruits
print(x)
print(y)
print(z)

Python Operators

Operators are special symbols that perform operations on variables and values. For
example,
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,

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


Operator Operation Example

+ 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

2. Python Assignment Operators:Assignment operators are used to assign values to variables.

For example,a=5
Here, = is an assignment operator that assigns 5 to a.
Here's a list of different assignment operators available in Python.

Operator Name Example

= 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

3. Python Comparison Operators:Comparison operators compare two values/variables and

return a boolean result: True or False. For example,a>b

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

== 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


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)

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

Operator Example Meaning

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.

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)
Operator Meaning Example

& 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 [Link]'s important to note that having two variables with equal values doesn't
necessarily mean they are identical.

Operator Meaning Example

True if the operands are identical (refer to the


is x is True
same object)

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

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


Run Code

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.

Operator Meaning Example

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

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

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
Run Code

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.

Data Types
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

Getting the Data Type

You can get the data type of any object by using the type() function:
Example

Print the data type of the variable x:

x=5
print(type(x))

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

Example Data Type

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range
x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset

x = True bool

x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

x = None NoneType

id () , type(), range() in python

id(): The id() function returns a unique id for the specified object.

All objects in Python has its own unique id.

The id is assigned to the object when it is created.


The id is the object's memory address, and will be different for each time you run the program.
(except for some object that has a constant unique id, like integers from -5 to 256 in some
versions of Python).

Syntax
id(object)
Parameter Values

Parameter Description

object Any object, String, Number, List, Class etc.

Example

Return the unique id of a tuple object:

x = ('apple', 'banana', 'cherry')


y = id(x)
type()

The type() function returns the type of the specified object

Syntax

type(object, bases, dict)


Parameter Values

Parameter Description

object Required. If only one parameter is specified, the type() function


returns the type of this object

bases Optional. Specifies the base classes


dict Optional. Specifies the namespace with the definition for the class

ExampleGet your own Python Server

Return the type of these objects:

a = ('apple', 'banana', 'cherry')


b = "Hello World"
c = 33

x = type(a)
y = type(b)
z = type(c)
range(): The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.
Syntax
range(start, stop, step)
Parameter Values

Parameter Description

start Optional. An integer number specifying at which position to start.


Default is 0

stop Required. An integer number specifying at which position to stop


(not included).

step Optional. An integer number specifying the incrementation. Default


is 1

More Examples
Example

Create a sequence of numbers from 3 to 5, and print each item in the sequence:

x = range(3, 6)
for n in x:
print(n)
Example

Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1:

x = range(3, 20, 2)
for n in x:
print(n)

coding standards in python


Indeed coding and applying logic is the foundation of any programming language but there's
also another factor that every coder must keep in mind while coding and that is the coding
style. Keeping this in mind, Python maintains a strict way of order and format of
[Link] this sometimes mandatory and is a great help on the user's end, to
understand. Making it easy for others to read code is always a good idea, and adopting a nice
coding style helps tremendously for that. For Python, PEP 8 has emerged as the style guide
that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every
Python developer should read it at some point; here are the most important points extracted for
you: 1. Use 4-space indentation and no tabs. Examples:
# Aligned with opening delimiter.
grow = function_name(variable_one, variable_two,
variable_three, variable_four)
# First line contains no argument. Second line onwards
# more indentation included to distinguish this from
# the rest.
def function_name(
variable_one, variable_two, variable_three,
variable_four):
print(variable_one)
The 4 space rule is not always mandatory and can be overruled for continuation line. 2. Use
docstrings : There are both single and multi-line docstrings that can be used in Python.
However, the single line comment fits in one line, triple quotes are used in both cases. These
are used to define a particular program or define a particular function. Example:
def exam():
"""This is single line docstring"""

"""This is
a
multiline comment"""
3. Wrap lines so that they don't exceed 79 characters : The Python standard library is
conservative and requires limiting lines to 79 characters. The lines can be wrapped using
parenthesis, brackets, and braces. They should be used in preference to backslashes. Example:
with open('/path/from/where/you/want/to/read/file') as file_one, \
open('/path/where/you/want/the/file/to/be/written', 'w') as file_two:
file_two.write(file_one.read())
4. Use of regular and updated comments are valuable to both the coders and users : There
are also various types and conditions that if followed can be of great help from programs and
users point of view. Comments should form complete sentences. If a comment is a full
sentence, its first word should be capitalized, unless it is an identifier that begins with a lower
case letter. In short comments, the period at the end can be omitted. In block comments, there
are more than one paragraphs and each sentence must end with a period. Block comments and
inline comments can be written followed by a single '#'. Example of inline comments:
geek = geek + 1 # Increment
5. Use of trailing commas : This is not mandatory except while making a tuple. Example:
tup = ("geek",)
5. Use Python's default UTF-8 or ASCII encodings and not any fancy encodings, if it is
meant for international environment. 6. Use spaces around operators and after commas, but
not directly inside bracketing constructs:
a = f(1, 2) + g(3, 4)
7. Naming Conventions : There are few naming conventions that should be followed in order
to make the program less complex and more readable. At the same time, the naming
conventions in Python is a bit of mess, but here are few conventions that can be followed
easily. There is an overriding principle that follows that the names that are visible to the user as
public parts of API should follow conventions that reflect usage rather than implementation.
Here are few other naming conventions:
b (single lowercase letter)

B (single upper case letter)

lowercase
lower_case_with_underscores

UPPERCASE

UPPER_CASE_WITH_UNDERSCORES

CapitalizedWords (or CamelCase). This is also sometimes known as StudlyCaps.


Note: While using abbreviations in CapWords, capitalize all the letters
of the abbreviation. Thus HTTPServerError is better than HttpServerError.

mixedCase (differs from CapitalizedWords by initial lowercase character!)

Capitalized_Words_With_Underscores
In addition to these few leading or trailing underscores are also considered.
Examples: single_leading_underscore: weak "internal use" indicator. E.g. from M import *
does not import objects whose name starts with an
underscore. single_trailing_underscore_: used to avoid conflicts with Python keyword.
Example:
[Link](master, class_='ClassName')
__double_leading_underscore: when naming a class attribute, invokes name mangling.
(inside class FooBar, __boo becomes
_FooBar__boo;). __double_leading_and_trailing_underscore__: "magic" objects or
attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Only
use them as documented. 8. Characters that should not be used for identifiers : 'l'
(lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character
variable names as these are similar to the numerals one and zero. 9. Don’t use non-ASCII
characters in identifiers if there is only the slightest chance people speaking a different
language will read or maintain the code. 10. Name your classes and functions consistently
: The convention is to use CamelCase for classes and lower_case_with_underscores for
functions and methods. Always use self as the name for the first method argument. 11. While
naming of function of methods always use self for the first argument to instance methods
and cls for the first argument to class [Link] a functions argument name matches with
reserved words then it can be written with a trailing comma. For e.g., class_ You can refer to
this simple program to know how to write an understandable code:
# Python program to find the
# factorial of a number provided by the user.

# change the value for a different result


num = 7

# uncomment to take input from the user


#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i

print("The factorial of",num,"is",factorial)


Output:
The factorial of 7 is 5040

Input /output
Meaning:

 Input: Refers to taking data from the user or from an external source into a Python
program.
 Output: Refers to displaying or writing data from a Python program to the user or to an
external destination.

Example:

 Input: Asking the user to enter their name.


 Output: Displaying a greeting message with the user’s name.

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 [Link] (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= '. ')
Run Code

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)
Run Code

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.')
Run Code
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 [Link]() method. For example,

x=5
y = 10

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


Run Code

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))


Run Code

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 .
Control Structures
Decision-making functions as an essential programming language component for most modern
languages. Programming languages enable programs to run specific program sections after
satisfying specific conditions.

Conditional Statements are the statements that allow a program to make decisions based on
conditions. These statements enable the execution of different blocks of code relying on whether
a condition is True or False.

Types of Conditional Statements in Python

Python provides support for the following types of conditional statements:

1. if statement
2. if-else statement
3. Nested if statement
4. if-elif-else statement

Let us discuss these conditional statements in detail.

if Statement

Programs execute the code inside the if block when the condition evaluates as True.

This represents the simplest decision-making construct. Programs can determine dynamic
responses through the if statement because it activates specific actions based on defined
conditions.

Syntax:

1. if condition:
2. # Code to execute if condition is True
Let us consider a simple example showing the implementation of if statement in Python:

Example 1

1. # initializing the age


2. age = 18
3.
4. # if statement: checking if the given age is greater than or equal to 18
5. if age >= 18:
6. # printing a message
7. print("You are eligible to vote.") # This executes because the condition is True
Execute Now
Output:

You are eligible to vote.

Example 2
1. # asking age from the user
2. age = int(input("Enter your age: "))
3.
4. # multiple if blocks
5. if age < 18: # checking if age is less than 18
6. # printing a message
7. print("You are not eligible to vote")
8.
9. if age >= 18: # checking if age is greater than or equal to 18
10. # printing a message
11. print("You are eligible to vote.")
12.
13. if age >= 21: # checking if age is greater than or equal to 21
14. # printing a message
15. print("You are allowed to consume alcohol in some countries.")
16.
17. if age >= 60: # checking if age is greater than or equal to 60
18. # printing a message
19. print("You are eligible for senior citizen benefits.")
20.
21. if age >= 80: # checking if age is greater than or equal to 80
22. # printing a message
23. print("You are a very senior citizen. Take extra care of your health.")
Execute Now
Output:

# Output 1:
Enter your age: 20
You are eligible to vote.
# Output 2:
Enter your age: 65
You are eligible to vote.
You are allowed to consume alcohol in some countries.
You are eligible for senior citizen benefits.

if…else Statement

Programming contains the if…else statement as its core element for making decisions in code
execution. One block of code executes through the if statement when conditions prove true, but a
different block activates with conditions evaluated false.
.

Syntax:

1. Here is the syntax for the if...else statement


2. if condition:
3. # Code to execute if condition is True
4. else:
5. # Code to execute if condition is False
Let us a simple example showing the implementation of the if...else statement in Python:

Example

1. # asking age from the user


2. age = int(input("Enter your age: "))
3.
4. # if-else statement: checking whether the user is eligible to vote or not
5. if age >= 18:
6. # if block
7. print("You are eligible to vote.")
8. else:
9. # else block
10. print("You are not eligible to vote.")
Execute Now
Output:

# Output 1:
Enter your age: 20
You are eligible to vote.
# Output 2:
Enter your age: 16
You are not eligible to vote.

Nested if…else statement


A nested if…else statement places an if…else block within both if statements and else
statements. A program is then able to perform advanced decision-making through this structure
by allowing multiple tests of conditions.

Syntax:

1. Here is the syntax for a nested if...else statement


2. if condition1:
3. if condition2:
4. # Code to execute if both condition1 and condition2 are True
5. else:
6. # Code to execute if condition1 is True but condition2 is False
7. else:
8. # Code to execute if condition1 is False
Let us consider an example showing the implementation of the nested if…else statement in
Python.

Example 1

1. # asking user to enter password


2. password = input("Enter your password: ")
3.
4. # nested if-else statement: checking whether the password is strong or not
5. if len(password) >= 8: # checking the length of the password
6. # outer if block
7. if any([Link]() for char in password): # checking if the password consists of any numeral v
alue
8. # inner if block
9. print("Password is strong.")
10. else:
11. # inner else block
12. print("Password must contain at least one number.")
13. else:
14. # outer else block
15. print("Password is too short. It must be at least 8 characters long.")
Execute Now
Output:

# Output 1:
Enter your password: secure123
Password is strong.
# Output 2:
Enter your password: password
Password must contain at least one number.

Example 2

1. # asking user to enter their marks


2. marks = int(input("Enter your marks: "))
3.
4. # nested if-else statement: checking if the user passed with distinction or not
5. if marks >= 40: # checking if the user got marks greater than or equal to 40
6. # outer if block
7. if marks >= 75: # checking if the user got marks greater than or equal to 75
8. # inner if block
9. print("Congratulations! You passed with distinction.")
10. else:
11. # inner else block
12. print("You passed the exam.")
13. else:
14. # outer else
15. print("You failed the exam. Better luck next time.")
Execute Now
Output:

# Output 1:
Enter your marks: 80
Congratulations! You passed with distinction.
# Output 2:
Enter your marks: 35
You failed the exam. Better luck next time.

if…elif…else Statement

A program requires the if…elif…else statement to evaluate sequential conditions for multiple
tests. A program can check several conditions in succession to locate a condition which produces
a True outcome.
Syntax:

1. Here is the syntax for an if...elif...else statement


2. if condition1:
3. # Code to execute if condition1 is True
4. elif condition2:
5. # Code to execute if condition2 is True
6. elif condition3:
7. # Code to execute if condition3 is True
8. else:
9. # Code to execute if none of the conditions are True
Let us consider an example showing the implementation of the if…elif…else statement in
Python.

Example 1

1. # asking user to enter temperature


2. temperature = int(input("Enter the temperature in Celsius: "))
3.
4. # if-elif-else statement: checking temperature
5. if temperature >= 30: # if temperature is greater than or equal to 30 deg
6. # if block
7. print("It's a hot day.")
8. elif temperature >= 20: # if temperature is greater than or equal to 20 deg
9. # elif block
10. print("The weather is warm.")
11. elif temperature >= 10: # if temperature is greater than or equal to 10 deg
12. # another elif block
13. print("It's a cool day.")
14. else: # if temp is less than 10 deg
15. # else block
16. print("It's a cold day.")
Execute Now
Output:

# Output 1:
Enter the temperature in Celsius: 35
It's a hot day.
# Output 2:
Enter the temperature in Celsius: 22
The weather is warm.

Example 2

1. # asking user to enter their marks


2. marks = int(input("Enter your marks: "))
3.
4. # if-elif-else statement: grading marks
5. if marks >= 85: # if marks is greater or equal to 90, printing A
6. print("Grade: A")
7. elif marks >= 65: # if marks is greater or equal to 80, printing B
8. print("Grade: B")
9. elif marks >= 50: # if marks is greater or equal to 70, printing C
10. print("Grade: C")
11. elif marks >= 33: # if marks is greater or equal to 60, printing D
12. print("Grade: D")
13. else: # if marks is less than 90, printing F
14. print("Grade: F")
Execute Now
Output:

# Output 1:
Enter your marks: 95
Grade: A
# Output 2:
Enter your marks: 64
Grade: C

Iteration Control Structure In Python


Python loops are control flow structures that allow us to execute a block of code repeatedly.
Python provides two main types of loops - for and while. Additionally, there is support
for nested loops in Python, allowing us to loop within loops to perform more complex tasks.
While all these loops offer similar basic functionality, they differ in their syntax and condition-
checking time.

For Loop in Python

In Python, we use for loops for sequential traversal. For example, traversing the elements of
a string, list, tuple, etc. It is the most commonly used loop in Python that allow us to iterate over
a sequence when we know the number of iterations beforehand.

The following is the syntax of Python for Loop:

Syntax:

1. for element in given_sequence:


2. # some block of code
Let us take a look at a basic implementation of the for loop in Python:

Example

1. # example of a for loop in Python


2.
3. # iterating using for loop
4. for i in range(1, 6):
5. print(i)
Execute Now

Output:

1
2
3
4
5

Iterating over a Sequence using Python for Loop

We can use for loop to iterate over strings, lists, tuples, and dictionaries in Python, as shown in
the following example:

Example

1. # python example to show use of for loop in sequential traversal


2.
3. # given string
4. str_1 = "Tpoint Tech"
5.
6. # iterating over string using for loop
7. for i in str_1:
8. print(i)
9.
10. print()
11.
12. # given list
13. list_1 = ["Welcome", "to", "Tpoint", "Tech"]
14.
15. # iterating over list using for loop
16. for i in list_1:
17. print(i)
18.
19. print()
20.
21. # given tuple
22. tuple_1 = ("Python", "for", "Beginners")
23.
24. # iterating over tuple using for loop
25. for i in tuple_1:
26. print(i)
27.
28. print()
29.
30. # given dictionary
31. dict_1 = {
32. 1: "Tpoint",
33. 2: "Tech"
34. }
35.
36. # iterating over dictionary using for loop
37. for i in dict_1:
38. print(i, ":", dict_1[i])
Execute Now

Output:

T
p
o
i
n
t

T
e
c
h

Welcome
to
Tpoint
Tech

Python
for
Beginners

1 : Tpoint
2 : Tech

Iterating by the Index of Sequence

In Python, we can also use the index of the elements in the given sequence for iteration. The
basic idea for this approach is first to determine the size of the sequence (e.g., list, tuple) and
then iterate over it within the range of the determined length.

Let us take a look at the following example:

Example
1. # python example to iterate over sequence using index
2.
3. # given list
4. fruit_basket = ['apple', 'banana', 'orange', 'mango', 'kiwi']
5.
6. # iterating over the index of elements in the list
7. for i in range(len(fruit_basket)):
8. # printing the index and the item
9. print(i, ":", fruit_basket[i])
Execute Now

Output:

0 : apple
1 : banana
2 : orange
3 : mango
4 : kiwi

Use of else Statement with Python For Loop

In Python, we can also use the else statement with the for loop. The for loop does not consist of
any condition on the basis of which the execution will stop. Thus, the code inside the else block
will only run once the for loop finishes iterations.

The syntax of the else statement with Python for loop is shown below:

Syntax:

1. for element in given_sequence:


2. # some block of code
3. else:
4. # some block of code runs if loop ends without break
Let us see an example of showing how the else statement works with the for loop in Python:

Example

1. # python example to show use of else statement with for loop


2.
3. # given list
4. fruits = ['guava', 'apple', 'orange', 'mango', 'banana', 'melon']
5.
6. # iterating with for loop
7. for item in fruits:
8. # inside for block
9. print(item) # printing items
10. else:
11. # inside else block
12. print("Welcome to else Block.") # printing statement
Execute Now

Output:

guava
apple
orange
mango
banana
melon
Welcome to else Block.

While Loop in Python

A while loop in Python allows us to execute a block of code repeatedly as long as a particular
condition evaluates to True. It is usually utilized when the number of iterations is unknown
beforehand.

The syntax of the while loop is shown below:

Syntax:

1. while given_condition:
2. # some block of code
Let us now see a simple example of the while loop in Python.

Example

1. # example of a for loop in Python


2.
3. # initializing a counter
4. counter = 1
5.
6. # iterating using while loop
7. while counter <= 5:
8. print("Tpoint Tech")
9. # incrementing counter by 1
10. counter += 1
Execute Now

Output:

Tpoint Tech
Tpoint Tech
Tpoint Tech
Tpoint Tech
Tpoint Tech

Use of else Statement with Python While Loop

Similar to the use of the else statement with the for loop, we can use it with Python while loop.
The else block will run only when the loop condition becomes false, implying that the loop
terminates normally.

The syntax of the else statement with Python for loop is shown below:

Syntax:

1. for element in given_sequence:


2. # some block of code
3. else:
4. # some block of code runs if loop ends without break
We will now look at the following example to see the use of the else statement with the while
loop in Python:

Example

1. # python example to show use of else statement with while loop


2.
3. # given list
4. fruits = ['guava', 'apple', 'orange', 'mango', 'banana', 'melon']
5.
6. # initializing a counter
7. counter = 0
8.
9. # iterating with while loop
10. while counter < len(fruits):
11. # inside for block
12. print(fruits[counter])
13. # incrementing counter
14. counter += 1
15. else:
16. # inside else block
17. print("Welcome to else Block.") # printing statement
Execute Now

Output:

guava
apple
orange
mango
banana
melon
Welcome to else Block.

Infinite While Loop in Python

In Python, we can also create a loop to execute a block of code for infinite times using
the while loop, as shown in the following example:

Example

1. # python example on infinite while loop


2.
3. # initializing counter
4. counter = 0
5.
6. # iterating using while loop
7. while counter == 0:
8. print("Tpoint Tech")
9. # no increment statement
Execute Now

Output:

Tpoint Tech
Tpoint Tech
Tpoint Tech
Tpoint Tech
Tpoint Tech
...
Note: It is suggested not to use this type of loop. It is a never-ending loop where the condition
always remains true and we have to terminate the interpreter forcefully.

Nested Loops in Python

A nested loop is a loop inside another loop. In Python, we can nest both for and while loops.
Nested loops are useful while working with multi-dimensional data like grids or matrices or
while performing certain complex operations.

The following is the syntax of the Python nested for loop:

Syntax:

1. for outer_var in outer_sequence:


2. # some block of code in outer loop
3. for inner_var in inner_sequence:
4. # some block of code in inner loop
The syntax of the Python nested while loop is given below:

1. while outer_condition:
2. # some block of code in outer loop
3. while inner_condition:
4. # some block of code in inner loop
We can also use one type of loop inside another other type of loop in Python. For example, we
can use a while loop inside a for loop or vice versa.

Let us see an example of a Python nested loop.

Example

1. # python example to print a pattern using nested loop


2.
3. # iterating using for loop
4. for i in range(1, 11):
5. # iterating using nested for loop
6. for j in range(1, i + 1):
7. # printing pattern
8. print("*", end=" ")
9. # new line
10. print()
Execute Now

Output:
*
**
***
****
*****
******
*******
********
*********
**********

Loop Control Statements in Python

In Python, we use loop control statements in order to change the sequence of execution. Once
the execution leaves a scope, the objects created in the same scope are also destroyed
automatically.

Python offers support for the following control statements:

Loop Control Statement Description

Continue It returns the control to the beginning


of the loop

Break It terminates the loop immediately,


even if the condition or sequence is
not finished.

Pass It acts as a placeholder that does


nothing.

Let us take a look at the following example demonstrating the use of these control statements in
Python.

Example

1. # python example to show the use of different loop control statements


2.
3. print("Example with continue statement:")
4. for i in range(1, 6):
5. if i == 3:
6. # continue statement
7. continue # Skip the iteration when i is 3
8. print(i)
9.
10. print("\nExample with break statement:")
11. for i in range(1, 6):
12. if i == 4:
13. # break statement
14. break # Exit the loop when i is 4
15. print(i)
16.
17. print("\nExample with pass statement:")
18. for i in range(1, 4):
19. if i == 2:
20. # pass statement
21. pass # Do nothing when i is 2
22. else:
23. print(i)
Execute Now

Output:

Example with continue statement:


1
2
4
5

Example with break statement:


1
2
3

Example with pass statement:


1
3
or
1) break Statement

The 'break' statement in the 'for' loop permanently stops the current iteration.

Example

1. cars = ["Tata", "Honda", "Mahindra", "BMW"]


2. for brand in cars:
3. if brand == "Mahindra":
4. break # This break statement will stop iteration
5. print(brand)
Compile and Run
Output:

Tata
Honda
Explanation:

In the above example, we used the break statement in the 'for' loop to stop the iterations when the
current iteration value is "Mahindra".

2) continue Statement

The 'continue' statement in the 'for' loop skip the current iteration and move to the next.

Example

1. cars = ["Tata", "Honda", "Mahindra", "BMW"]


2. for brands in cars:
3. if brands == "Mahindra":
4. continue # this statement will stop iteration if Mahindra occurs, continue further
5. print(brands)
Compile and Run
Output:

Tata
Honda
BMW
Explanation:

In this example, we used the continue statement to skip the current iteration of the 'for' loop.

3) pass Statement

In 'for' loop, the 'pass' statement in Python is used as a placeholder. It means that we can use it
when we need to write something in our code but don't want it to do anything or want to leave
space to write something in the future.

Example

1. for n in range(1, 11):


2. if n % 3 == 0:
3. pass # this works as a placeholder
4. else:
5. print(n)
Compile and Run
Output:

1
2
4
5
7
8
10

4) else with for loop

The 'else' statement in the 'for' loop is used to provide an output when the previous condition is
not met or cannot be achieved.

Example

1. for i in range(1, 10):


2. print(i)
3. else:
4. print("Loop Finished")
Compile and Run
Output:

1
2
3
4
5
6
7
8
9
Loop Finished

You might also like