unit 1-merged (1)
unit 1-merged (1)
PYTHON PROGRAMMING
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:
# 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
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
• 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
• Bitwise NOT
• Bitwise Shift
• Bitwise AND
• Bitwise XOR
• Bitwise OR
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
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.
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
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.
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)
x = 10
if x > 5:
if x < 15:
print("x is between 5 and 15")
PYTHON PROGRAMMING
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.
b = 7.0
print("\nType of b: ", type(b))
c = 3+ 4j
print("\nType of c: ", type(c))
• 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)
PYTHON PROGRAMMING
PYTHON PROGRAMMING
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:
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")
PYTHON PROGRAMMING
switch_dict = {
'a': "Option A selected",
'b': "Option B selected",
'c': "Option C selected"
}
PYTHON PROGRAMMING
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):
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
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]
If you need the index of each element as well, you can use the
enumerate function:
Code-
fruits = ["apple", "banana", "cherry"]
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]
]
print(student_scores)
PYTHON PROGRAMMING
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
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)