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

unit 1-merged (1)

The document provides an overview of Python programming, including its history, syntax, and key features such as variables, operators, and data types. It explains the use of Python in various programming constructs like blocks, control structures, and functions, highlighting the flexibility and readability of the language. Additionally, it covers different types of operators, including arithmetic, relational, and logical operators, as well as data types like numeric, sequence, and boolean.
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)
4 views

unit 1-merged (1)

The document provides an overview of Python programming, including its history, syntax, and key features such as variables, operators, and data types. It explains the use of Python in various programming constructs like blocks, control structures, and functions, highlighting the flexibility and readability of the language. Additionally, it covers different types of operators, including arithmetic, relational, and logical operators, as well as data types like numeric, sequence, and boolean.
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
You are on page 1/ 129

BCC302/BCC402:

(COMMON TO ALL BRANCH)

PYTHON PROGRAMMING

Explained By- Rashi Daga


Python is a widely used general-purpose, high level programming
language. It was created by Guido van Rossum in 1991 and further
developed by the Python Software Foundation. It was designed with
an emphasis on code readability, and its syntax allows programmers
to express their concepts in fewer lines of code. Python is a
programming language tat lets you work quickly and integrate
systems more efficiently.

To run Python in your IDE (Visual Studio Code)


Download Extensions Python Extension in Your Visual studio Code
# Script Begins

print("GeeksQuiz")

# Scripts Ends

Python Variables
Python Variable is containers that store values. Python is not
“statically typed”.
Statically typed languages are the languages like C, C++, Java, etc, In
this type of language the data type of a variable is known at the
compile time which means the programmer has to specify the data type
of a variable at the time of its declaration. We have to pre-define the
return type of function as well as the type of variable it is taking or
accepting for further evaluations.
We do not need to declare variables before using them or declare
their type. A variable is created the moment we first assign a value
to it. A Python variable is a name given to a memory location. It is
the basic unit of storage in a program.
Example of Variable in Python
An Example of a Variable in Python is a representational name that
serves as a pointer to an object. Once an object is assigned to a
variable, it can be referred to by that name. In layman’s terms, we
can say that Variable in Python is containers that store values.
Here we have stored “Geeksforgeeks” in a variable var, and when we
call its name the stored information will get printed.
Var = "Geeksforgeeks"
print(Var)
Notes:

• The value stored in a variable can be changed during program


execution.
• A Variables in Python is only a name given to a memory location,
all the operations done on the variable effects that memory
location.
Rules for Python variables
• A Python variable name must start with a letter or the underscore
character.
• A Python variable name cannot start with a number.
• A Python variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ ).
• Variable in Python names are case-sensitive (name, Name, and
NAME are three different variables).
• The reserved words(keywords) in Python cannot be used to name
the variable in Python.
Declaration and Initialization of Variables
# declaring the var
Number = 100

# display
print( Number)
Python Operators
In Python programming, Operators in general are used to perform
operations on values and variables. These are standard symbols used
for logical and arithmetic operations.

Python operators.
OPERATORS: These are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
Types of Operators in Python

• Arithmetic Operators
• Comparison Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Identity Operators and Membership Operators
BCC302/BCC402:
(COMMON TO ALL BRANCH)

PYTHON PROGRAMMING

Explained By- Rashi Daga


Arithmetic Operators in Python
Python provides arithmetic operators for performing basic
mathematical operations like addition, subtraction, multiplication,
and division.In Python 3.x, dividing two numbers yields a floating-
point result by default. In contrast, Python 2.x would return an
integer when dividing two integers. To get an integer result from
division in Python 3.x, you can use the floor division operator (//).

Let’s see some basic Arithmetic Operators in Python.


Division Operators
In Python, division operators are used to divide two numbers and
return a quotient. The first number (on the left) is divided by the
second number (on the right), resulting in a quotient. Python
provides two types of division operators:

• Float Division: This operator returns the quotient as a floating-


point number.
• Floor Division: This operator returns the quotient as an integer,
discarding any fractional part.
Precedence of Arithmetic Operators in Python
The precedence of Arithmetic Operators in Python is as follows:

P – Parentheses
E – Exponentiation
M – Multiplication (Multiplication and division have the same
precedence)
D – Division
A – Addition (Addition and subtraction have the same precedence)
S – Subtraction
Relational Operators

Relational operators in Python are used to compare two values. These


operators evaluate the relationship between the operands and return a
boolean value (either True or False). Here are the commonly used
relational operators in Python:
Precedence of Comparison Operators in Python
In Python, the comparison operators have lower precedence than the
arithmetic operators. All the operators within comparison operators
have the same precedence order .
Logical Operators in Python
Logical operators in Python are used to perform logical operations on
boolean values. These operators are commonly used to combine
multiple conditions and return a boolean result (True or False).
Python provides three logical operators:
Precedence of Logical Operators in Python
The precedence of Logical Operators in Python is as follows:

• Logical not
• logical and
• logical or
Example of Logical Operator
a = True
b = False
print(a and b)
print(a or b)
print(not a)
BCC302/BCC402:
(COMMON TO ALL BRANCH)

PYTHON PROGRAMMING

Explained By- Rashi Daga


Bitwise Operators in Python
Bitwise operators in Python work on the binary form of numbers,
handling each bit individually. They are used to manipulate numbers
at the binary level.
Code – Output
a = 10 0
b=4 14
print(a & b) -11
print(a | b) 14
print(~a) 2
print(a ^ b) 40
print(a >> 2)
print(a << 2)

Precedence of Bitwise Operators in Python


The precedence of Bitwise Operators in Python is as follows:

• Bitwise NOT
• Bitwise Shift
• Bitwise AND
• Bitwise XOR
• Bitwise OR

Assignment Operators in Python


Assignment operators are used to assign values to the variables.
Code – Output -
a = 10 10
b=a 20
print(b) 10
b += a 100
print(b) 102400
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
Identity Operators in Python
In Python, is and is not are identity operators used to check if two
values refer to the same memory location. Two variables being equal
doesn't necessarily mean they are the same object.
is True if the operands are identical
is not True if the operands are not identical
a = 10
Output
b = 20
True
c=a
True
print(a is not b)
print(a is c)
The code uses identity operators to compare variables in Python. It
checks if a is not the same object as b (which is true because they
have different values) and if a is the same object as c (which is true
because c was assigned the value of a).
Membership Operators in Python
In Python, in and not in are the membership operators that are used
to test whether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
x = 27
y = 30 x is NOT present in
list = [10, 20, 30, 40, 50] given list
y is present in given list
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
BCC302/BCC402:
(COMMON TO ALL BRANCH)

PYTHON PROGRAMMING

Explained By- Rashi Daga


Ternary Operator in Python
In Python, ternary operators, also known as conditional expressions,
evaluate something based on whether a condition is true or false.
Added in version 2.5, they allow for testing a condition in a single
line, replacing the multiline if-else statement and making the code
more compact.
Syntax : [on_true] if [expression] else [on_false]

The code assigns values to the variables 'a' and 'b' (10 and 20,
respectively). It then uses a conditional assignment to determine the
smaller of the two values and assigns it to the variable 'min'. Finally,
it prints the value of 'min', which in this case is 10.
a, b = 10, 20
min = a if a < b else b

print(min)

Output-10
What is a Block in Programming?
In programming, a block is a group of statements that are treated as
a single unit.
In general programming, a block is a section of code enclosed within
curly braces {}. Blocks help in organizing code, controlling the flow
of execution, and defining the visibility and lifetime of variables
within a program. It defines a scope where the enclosed statements are
treated as a single unit.
Characteristics of Blocks:
Encapsulation: Blocks encapsulate a set of statements, allowing
them to be treated as a single unit.

Scope: Blocks define a scope, which is a region of code where a


variable can be accessed and manipulated. Variables declared within
a block are typically only accessible within that block.
Control Structures: Blocks are used with control structures such as if,
else, for, while, do-while, and switch to group multiple statements
and control the flow of execution.

Functions and Methods: In programming languages that support


functions and methods, blocks are used to define the body of the
function or method.
Types of Blocks in Programming:
Here are some common types of blocks in programming:

1. Basic Block
A basic block is a series of instructions in a program that has one
entry point and one exit point. It typically does not include any jump
or branch instructions.
x = 30
y = 20
z=x+y

2. Function Block
A function block is comprised of a defined set of instructions that
execute a specific task, beginning with a function definition and
concluding with a return statement.
def add_numbers(a, b):
result = a + b
return result
In Python, def is a keyword used to define a function.

3. Conditional Block
A conditional block contains code that is executed based on a
certain condition. It is usually defined using if, elif, and else
statements.
Code-
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")

4. Loop Block
A loop block is defined using for and while loops. It contains code
that is executed repeatedly as long as a certain condition is true.

For Loop
for i in range(5):
print(i)

While Loop-

x=0
while x < 5:
print(x)
x += 1
BCC302/BCC402:
(COMMON TO ALL BRANCH)

PYTHON PROGRAMMING

Explained By- Rashi Daga


5. Try-Except Block
A try-except block handles exceptions by executing the code inside
the try block and, if an exception occurs, running the code inside
the except block.

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")

6. Class Block
A class block contains the definition of a class in object-oriented
programming. It can contain attributes and methods.

Class: It's like a template or a recipe. Just like a recipe tells you how
to make a dish, a class tells the computer how to create an object.

Attributes: These are the characteristics or properties of the object.


For example, if you have a class called Car, attributes could be color,
make, model, and year. They describe the car.

Methods: These are the actions or behaviors the object can perform.
In the Car class, methods could be start(), drive(), and stop(). They
define what the car can do.
class Dog:
def __init__(self, name):
self.name = name

def bark(self):
print(f"{self.name} says Woof!")
The Dog class in Python is a simple recipe for creating and using dog
objects in a computer program. The class starts with a definition line
(class Dog:) that tells the computer we are defining a new type of
object called Dog. Inside the class, there is a special method called
__init__ that initializes new dog objects with a given name. This
method takes a parameter name and assigns it to the dog's name
attribute (self.name = name), allowing each dog object to store its
unique name. Additionally, the class includes a bark method that,
when called, prints a message indicating the dog’s name followed by
"says Woof!". For example, when a new Dog object is created using
my_dog = Dog("Buddy"), it initializes a dog named "Buddy". Calling
my_dog.bark() makes Buddy bark, resulting in the output "Buddy
says Woof!". This class encapsulates both the properties (name) and
behaviors (barking) of a dog, making it easy to create and interact
with dog objects in the program.

7. Scope Block
A scope block defines the visibility and accessibility of variables
within a program. In Python, indentation is used to define the scope
of variables.
x = 10 # Global variable

def my_function():
y = 20 # Local variable
print(x) # Access global variable
print(y) # Access local variable

my_function()

8. Nested Blocks
Nested blocks refer to blocks that are defined within another block.
They can be found within loops, conditional statements, or function
blocks.
Nested Loops

for i in range(3):
for j in range(3):
print(i, j)

Nested Conditional Statements

x = 10
if x > 5:
if x < 15:
print("x is between 5 and 15")

Python Data Types


Python data types are ways to classify different types of data. They
show what kinds of values you can have and what you can do with
them. In Python, everything is an object, which means data types are
like blueprints (classes), and the values you create are like actual
items (objects) made from those blueprints. Here are the main built-
in data types in Python:
• Numeric
• Sequence Type
• Boolean
• Set
• Dictionary
• Binary Types( memoryview, bytearray, bytes)
BCC302/BCC402:
(COMMON TO ALL BRANCH)

PYTHON PROGRAMMING

Explained By- Rashi Daga


What is Python Data Types?
To define the values ​of various data types of Python and check their
data types we use the type() function.
1. Numeric Data Types in Python
In Python, numeric data types represent values with numeric
characteristics, which can be integers, floating-point numbers, or
complex numbers. These are defined by the int, float, and complex
classes, respectively.

Integers: Represented by the int class, integers include positive or


negative whole numbers without fractions or decimals. In Python,
there is no upper limit on the length of an integer.

Floats: Represented by the float class, these are real numbers with
floating-point representation, denoted by a decimal point.
Additionally, the character e or E followed by an integer (positive or
negative) can be used to indicate scientific notation.

Complex Numbers: Represented by the complex class, these numbers


have a real part and an imaginary part, specified as (real part) +
(imaginary part)j. For example, 2 + 3j.
Code-
a=6
print("Type of a: ", type(a))

b = 7.0
print("\nType of b: ", type(b))

c = 3+ 4j
print("\nType of c: ", type(c))

2. Sequence Data Types in Python


The sequence data type in Python is an ordered collection of similar
or different data types, allowing for the organized and efficient
storage of multiple values. Python includes several sequence data
types:

• Python String
• Python List
• Python Tuple
String Data Type
A string is a collection of one or more characters enclosed in single
quotes, double quotes, or triple quotes. In Python, there is no specific
character data type; a character is simply a string of length one,
represented by the str class.Creating StringsIn Python, strings can be
created using single quotes, double quotes, or triple quotes.
String1 = 'Welcome to Civil Mantra'
print("String with the use of Single Quotes: ")
print(String1)
String1 = “Welcome to Civil Mantra"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
String1 = ‘‘’Welcome to Civil Mantra"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
String1 = ‘‘’Welcome
Civil
Mantra'''
print("\nCreating a multiline String: ")
print(String1)

List Data Type


Lists in Python are similar to arrays in other languages, serving as
an ordered collection of data. They are very flexible because the
items in a list do not need to be of the same type.Creating a List in
PythonLists can be created by simply placing the sequence of items
inside square brackets [].
List = []
print("Initial blank List: ")
print(List)
List = [‘Civil Mantra']
print("\nList with the use of String: ")
print(List)
List = [“Welcome", “Civil", “Mantra]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])
List = [[‘Welcome', ‘Civil'], [‘Mantra']]
print("\nMulti-Dimensional List: ")
print(List)
Tuple Data Type
Like a list, a tuple is also an ordered collection of Python objects. The
key difference is that tuples are immutable, meaning they cannot be
modified after creation. Tuples are represented by the tuple
class.Creating a Tuple in Python In Python, tuples are created by
placing a sequence of values separated by commas, with or without
parentheses for grouping. Tuples can contain any number of elements
and can include various data types (such as strings, integers, lists,
etc.).
Note: Creating a tuple with a single element requires a trailing
comma; simply enclosing one element in parentheses is not enough
to define a tuple.
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
Tuple1 = (‘Civil', ‘mantra')
print("\nTuple with the use of String: ")
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
Tuple1 = tuple(‘Civil Mantra')
print("\nTuple with the use of function: ")
print(Tuple1)
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', ‘Civil Mantra')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
BCC302/BCC402:
(COMMON TO ALL BRANCH)

PYTHON PROGRAMMING

Explained By- Rashi Daga


3. Boolean Data Type in Python
In Python, a data type with two built-in values, True and False, is
called a Boolean. Boolean objects that equate to True are considered
truthy, while those equating to False are falsy. However, non-Boolean
objects can also be evaluated in a Boolean context to determine their
truth value. This data type is represented by the class bool.Note: The
values True and False must be written with a capital 'T' and 'F'
respectively. Otherwise, Python will generate an error. Python is case-
sensitive, meaning it distinguishes between uppercase and lowercase
letters. Thus, 'True' and 'False' are valid Booleans, but 'true' and 'false'
are not.Example: The first two lines of the code will display the type
of the Boolean values True and False as <class 'bool'>. The third line
will result in an error because 'true' is not a recognized keyword in
Python. Ensure to capitalize the first letter of True to use it as a
Boolean value.
Code-
print(type(True))
print(type(False))
print(type(true))

4. Set Data Type in Python


In Python, a Set is a collection of unique elements that is unordered,
changeable, and does not allow duplicates. The elements in a set are
not stored in any particular order, though they can be of different
types.Creating a Set in PythonYou can create a set using the built-in
set() function with an iterable or by placing elements inside curly
braces {}, separated by commas. The elements in a set can be of
different types, meaning you can mix various data types within the
same set.Example: The following code demonstrates how to create
sets using different types of values, such as strings, lists, and mixed
types.
Code-
set1 = set()
print("Initial blank Set: ")
print(set1)
set1 = set(“Welcome to Civil Mantra")
print("\nSet with the use of String: ")
print(set1)
set1 = set([“Welcome", “Civil", “Mantra"])
print("\nSet with the use of List: ")
print(set1)
set1 = set([1, 2, ‘Civil', 4, 'For', 6, ‘Mantra'])
print("\nSet with the use of Mixed Values")
print(set1)
5. Dictionary Data Type in Python
In Python, a dictionary is an unordered collection used to store data
in key-value pairs, functioning similarly to a map. Unlike other
Python data types that hold a single value, a dictionary stores pairs of
keys and values, making it highly efficient. Each key-value pair is
separated by a colon :, and each key is separated by a comma.Creating
a Dictionary in PythonYou can create a dictionary by placing a series
of key-value pairs inside curly braces {}, separated by commas. The
values in a dictionary can be of any data type and can be duplicated,
while the keys must be unique and immutable. You can also create a
dictionary using the built-in dict() function. An empty dictionary is
created by simply using empty curly braces {}. Note: Dictionary keys
are case-sensitive, meaning keys with the same name but different
cases are considered different.
Code-
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict = {1: ‘Civil', 2: 'For', 3: ‘Mantra'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': ‘Civil Mantra', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Dict = dict({1: ‘Civil', 2: 'For', 3: ‘Mantra'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Dict = dict([(1, ‘Civil Mantra'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Ques-What is the difference between list and tuples ?

Ques- In some languages , every statement ends with a semi-


colon (;) . What happens if you put a semi-colon at the end of
a Python Statement ?
In Python, semicolons are not required to terminate statements as
they are in some other languages like C, C++, and Java. Python uses
newline characters to determine the end of a statement. However, you
can use a semicolon to separate multiple statements on a single line.If
you put a semicolon at the end of a Python statement, the code will
still run correctly, and the semicolon will be ignored.
Ques - Mention five benefits of using Python ?
Easy to Read and Write: Python has a simple syntax that is easy to
understand.
Rich Libraries: Offers many libraries for different tasks (e.g.,
NumPy, Pandas).
Versatile: Suitable for web development, data analysis, automation,
and more.
Strong Community: Large community for support, tutorials, and
resources.
Cross-Platform: Works on Windows, macOS, and Linux without
major changes.
Ques- How is Python an Interpreted language ?
Python is an interpreted language because its code is executed line
by line by an interpreter at runtime, without needing a prior
compilation step. This allows for immediate execution and testing of
code, making development easier and more flexible.
Ques- Which type of language is Python ?
Python is a high-level, interpreted, general-purpose programming
language.
Ques - What are local variables and global variables in
Python ?
Local Variables: Variables that are defined inside a function and can
only be accessed within that function.

Global Variables: Variables that are defined outside of all functions


and can be accessed from any part of the code.
Ques - What is the difference between Python Arrays and
Lists?
Python arrays and lists both allow for the storage of multiple items,
but they have key differences. Arrays in Python, available through the
array module, require all elements to be of the same type and are
more efficient for numerical operations. Lists, on the other hand, are
more versatile and can hold elements of different types, making them
more flexible and widely used. Lists come with a variety of built-in
methods and are part of Python's core, while arrays need to be
imported from the array module.
Ques- Define Floor Division with example ?
BCC302/BCC402:
(COMMON TO ALL BRANCH)

PYTHON PROGRAMMING

Explained By- Rashi Daga


What are Control Flow Statements in Programming?
Control flow statements are essential elements of programming
languages that give developers the ability to manage the sequence of
instruction execution in a program. They allow for repeated
execution of a code block, conditional execution of code segments,
and the ability to stop or bypass specific lines of code.
What are the types of control flow statements in a
programming
The types of control flow statements in programming typically
include:
Conditional Statements:

• if statement: Executes a block of code if a specified condition is


true.
• else statement: Executes a block of code if the condition in the if
statement is false.
• else if / elif statement: Tests multiple conditions.
• switch/case statement: Executes one block of code among many
based on the value of a variable.

Looping Statements
• for loop: Repeats a block of code a specified number of times.
• while loop: Repeats a block of code as long as a specified
condition is true.
• do-while loop: Similar to the while loop, but the condition is
tested after the code block is executed, ensuring the code block
runs at least once.

Jump Statements:

• break statement: Terminates the loop or switch statement and


transfers execution to the statement immediately following the
loop or switch.
• continue statement: Skips the current iteration of a loop and
proceeds to the next iteration.
return statement: Exits from a function and optionally returns a
value.
goto statement: Transfers control to a labeled statement within the
same function (less common and generally discouraged in modern
programming
Conditional statements in programming
Conditional statements in programming are used to execute certain
blocks of code based on specified conditions. They are fundamental
to decision-making in programs. Here are some common types of
conditional statements:
1. If Statement in Programming:
The if statement is used to execute a block of code if a specified
condition is true.

Code-
a=5
if a == 5:
print("a is equal to 5")
2. if-else Statement in Programming:
The if-else statement is used to execute one block of code if a
specified condition is true, and another block of code if the condition
is false.
Code-
a = 10
if a == 5:
print("a is equal to 5")
else:
print("a is not equal to 5")

Ques-Explain the role of precedence with an example?


In programming, precedence determines the order in which
operators are evaluated in an expression. Operators with higher
precedence are evaluated before those with lower precedence. For
instance, in the arithmetic expression 3 + 5 * 2, the multiplication
operator * has higher precedence than the addition operator +, so 5 *
2 is evaluated first, resulting in 3 + 10, and thus the final result is 13.
Understanding operator precedence is crucial to writing correct and
predictable code, as it ensures that expressions are evaluated in the
intended order. To control the order of evaluation explicitly,
parentheses can be used; for example, (3 + 5) * 2 forces the addition
to occur first, yielding 16 as the result.
Ques-How do you read an input from a user in Python to be
used as an integer
in the rest of the program? Explain with an example.
In Python, to read an input from a user and use it as an integer in the
rest of the program, you use the input() function combined with the
int() function. The input() function reads the user input as a string, and
int() converts that string into an integer. For example, if you want to
read the user's age, you would write: age = int(input("Enter your age:
")). This prompts the user to enter their age, reads the input as a string,
and then converts it to an integer, storing it in the variable age. You
can then use the age variable in subsequent calculations or logic
throughout your program. Here's a simple example:
age = int(input("Enter your age: "))
years_until_100 = 100 - age
print(f"You will be 100 years old in {years_until_100} years.")
BCC302/BCC402:
(COMMON TO ALL BRANCH)

PYTHON PROGRAMMING

Explained By- Rashi Daga


3. if-else-if Statement in Programming:
The if-else-if statement is used to execute one block of code if a
specified condition is true, another block of code if another condition
is true, and a default block of code if none of the conditions are true.
Code-
a = 15
if a == 5:
print("a is equal to 5")
elif a == 10:
print("a is equal to 10")
else:
print("a is not equal to 5 or 10")
4. Ternary Operator or Conditional Operator in Programming:
In some programming languages, a ternary operator is used to assign
a value to a variable based on a condition.
Code-
a = 10
print("a is equal to 5" if a == 5 else "a is not equal to 5")

5. Switch Statement in Programming:


In languages like C, C++, and Java, a switch statement is used to
execute one block of code from multiple options based on the value of
an expression.
Code-
option = 'b'

switch_dict = {
'a': "Option A selected",
'b': "Option B selected",
'c': "Option C selected"
}

result = switch_dict.get(option, "Invalid option")


print(result)
Looping statements
Looping statements, also referred to as iteration or repetition
statements, are utilized in programming to execute a block of code
multiple times. They are crucial for tasks like iterating over elements
in a list, reading data from a file, or running a set of instructions a
predetermined number of times. Some common types of looping
statements include:
1.For Loop in Programming-
The for loop is used to iterate over a sequence (e.g., a list, tuple,
string, or range) and execute a block of code for each item in the
sequence.
Code-
for i in range(5):
print(i)
While Loop in programming-

The while loop is used to repeatedly execute a block of code as long as


a specified condition is true.
Code-
count = 0
while count < 5:
print(count)
count += 1
Do-While Loop in Programming-

In some programming languages, such as C and Java, a do-while


loop is used to execute a block of code at least once, and then
repeatedly execute the block as long as a specified condition is true.
4. Nested Loops in Programming:
Loops can be nested within one another to perform more complex
iterations. For example, a for loop can be nested inside another for
loop to create a two-dimensional iteration.
Code-
for i in range(2):
for j in range(2):
print(f"i={i} j={j}")
BCC302/BCC402:
(COMMON TO ALL BRANCH)

PYTHON PROGRAMMING

Explained By- Rashi Daga


For Loop using Ranges-

In Python, you can use a for loop with the range() function to iterate
over a sequence of numbers. The range() function can take up to
three arguments: start, stop, and step. Here's a basic explanation and
examples for each case:
1.Basic usage with one argument (stop):

Syntax: range(stop)
Iterates from 0 to stop – 1

Code-
for i in range(5):
print(i)
2.Using two arguments (start, stop):

Syntax: range(start, stop)


Iterates from start to stop - 1.
Code-
for i in range(2, 7):
print(i)
3.Using three arguments (start, stop, step):
Syntax: range(start, stop, step)
Iterates from start to stop - 1,
incrementing by step.
Code-
for i in range(1, 10, 2):
print(i)
For Loop using strings-

In Python, you can use a for loop to iterate over the characters in a
string. Here's a basic example and some variations to demonstrate
how to use a for loop with strings:
1.Basic iteration over a string:
Code-
my_string = "Hello"
for char in my_string:
print(char)
2.Using for loop with enumerate() to get both the index and the
character:
Code-
my_string = "Hello"
for index, char in enumerate(my_string):
print(f"Index: {index}, Character: {char}")
3.Iterating over a string in reverse order:
Code-
my_string = "Hello"
for char in reversed(my_string):
print(char)
4.Using for loop to iterate over substrings:
Code-
my_string = "Hello World"
words = my_string.split()
for word in words:
print(word)
5.Modifying and printing each character:
Code-
my_string = "Hello"
for char in my_string:
print(char.upper())
Ques-Discuss why Python is called as dynamic and strongly
typed language?
Python is called a dynamic and strongly typed language because it
determines the type of a variable at runtime, not in advance, which is
why it is dynamic. This means you don't need to declare variable
types explicitly. It is strongly typed because once a variable is
assigned a type, it cannot be implicitly converted to another type. For
example, adding a string to an integer will result in a type error. This
combination of runtime type determination and strict type
enforcement defines Python's typing system.
Ques-Write a for loop that prints numbers from 0 to 57, using
range function ?

To print numbers from 0 to 57 using a for loop and the range function
in Python, you can use the following code:
for i in range(58):
print(i)
This loop uses range(58), which generates numbers from 0 up to,
but not including, 58. The print(i) statement inside the loop prints
each number in this range.
Ques-What is the difference between Python Arrays and
Lists?
BCC302/BCC402:
(COMMON TO ALL BRANCH)

PYTHON PROGRAMMING

Explained By- Rashi Daga


For Loop using Lists-

In Python, you can use a for loop to iterate over elements in a list.
Here's a basic example to illustrate how it works:
1. Iterating over a List of Numbers
Code-
numbers = [1, 2, 3, 4, 5]

for number in numbers:


print(number)
2: Iterating over a List of Strings
Code-
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:


print(fruit)
3: Using the Index with enumerate:

If you need the index of each element as well, you can use the
enumerate function:
Code-
fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):


print(f"Index {index}: {fruit}")
4: Modifying Elements in a List-

If you want to modify the elements of a list, you can use a for loop
with the index:
Code-
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2

print(numbers)
5: Nested for Loops-

You can also use nested for loops to iterate over lists of lists (2D
lists):
Code-
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

for row in matrix:


for element in row:
print(element, end=' ')
print() # for a new line after each row
For Loop using Dictionaries-

Using a for loop to iterate over dictionaries in Python allows you to


access keys, values, or both. Here are some common ways to do this:
1: Iterating Over Keys
Code-
student_scores = {
"Alice": 85,
"Bob": 90,
"Charlie": 78
}

for student in student_scores:


print(student)
2: Iterating Over Values
Code-
for score in student_scores.values():
print(score)

3: Iterating Over Key-Value Pairs


Code-
for student, score in student_scores.items():
print(f"{student}: {score}")

4: Modifying Values in a Dictionary


If you want to modify the values, you can use a for loop to update the
dictionary:
Code-
for student in student_scores:
student_scores[student] += 5 # Adding 5 bonus points to each
student's score

print(student_scores)

5: Iterating Over Keys and Values Using enumerate


You can use enumerate if you want to have an index along with key-
value pairs (although it's less common with dictionaries):
Code-
for index, (student, score) in enumerate(student_scores.items()):
print(f"{index}: {student} - {score}")
6.Nested for Loops with Dictionaries
You can also use nested for loops if you have a dictionary of
dictionaries:
Code-
class_scores = {
"Class A": {"Alice": 85, "Bob": 90},
"Class B": {"Charlie": 78, "Dave": 92}
}

for class_name, students in class_scores.items():


print(f"{class_name}:")
for student, score in students.items():
print(f" {student}: {score}")
BCC302/BCC402:
(COMMON TO ALL BRANCH)

PYTHON PROGRAMMING

Explained By- Rashi Daga


Use of While Loops in Python-

1. Basic Syntax
The while loop repeatedly executes a block of code as long as a given
condition is true.
Code-
count = 1
while count <= 5:
print(count)
count += 1
2.Infinite Loops
A while loop can run indefinitely if the condition never becomes false.
This is useful for creating loops that should run until an external
condition is met.
Code-
count = 0

while True:
print("This loop will run until count reaches 5.")
count += 1
if count >= 5:
break
Here loop will continue to infinite but we will use break statement
also which break the loop but if we don’t use break statement here
then your loop will be infinite
3.Using break to Exit a Loop
The break statement immediately exits the loop, regardless of the
condition.
Code-
count = 1
while count <= 5:
print(count)
if count == 3:
break
count += 1
4.Using continue to Skip an Iteration
The continue statement skips the rest of the loop body for the
current iteration and proceeds to the next iteration.
Code-
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count)
5.Using Complex Conditions
The loop condition can be a complex expression involving multiple
variables.
Code-
x=0
y = 10
while x < y and y > 5:
print(f"x: {x}, y: {y}")
x += 1
y -= 1
6.Nested while Loops
while loops can be nested inside other loops to perform complex
iterations.
Code-
i=1
while i <= 3:
j=1
while j <= 2:
print(f"i: {i}, j: {j}")
j += 1
i += 1
Ques-Explain the use of break and continue with a suitable
example.
Ques-What do you mean by operator precedence and
associativity. Explain ?
BCC302/BCC402:
(COMMON TO ALL BRANCH)

PYTHON PROGRAMMING

Explained By- Rashi Daga


Pass Statement in Python
The pass statement in Python is used when a statement is needed
syntactically, but no action or code execution is desired. It acts as a
null operation, meaning nothing occurs when it is executed. Pass
statements are useful for creating empty loops or placeholders for
future code. They can also be used in control statements, functions,
and classes where no implementation is currently needed.
Syntax of Pass Statement
function/ condition / loop:
pass
# Python program to demonstrate
# pass statement

s = “civil"

# Empty loop
for i in s:
# No error will be raised
pass

# Empty function
def fun():
pass
# No error will be raised
fun()

# Pass statement
for i in s:
if i == ‘v':
print('Pass executed')
pass
print(i)

You might also like