Mid Term
Mid Term
Mid Term
INPUT: OUTPUT:
TASK 2:
def print_details():
print("MY NAME IS HAMID ZAYAN\nMY ROLL NO IS 2024-EE-410\nMY SECTION IS B")
TASK3:
print("MY NAME IS HAMID ZAYAN\n"
"MY ROLL NO IS 2024-EE-410\n"
"MY SECTION IS B")
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:
Str
Dict
b = False
type(b)
VARIABLES IN PYTHON
Variables in Python are used to store data values. They act as containers for storing
data, which can be used and manipulated throughout a program. Unlike many other
programming languages, Python does not require you to declare a variable before using
it. A variable is created the moment you first assign a value to it
To create a variable in Python, you simply assign a value to it using the assignment operator = . For example:
x = 5
y = "John"
print(x) # Output: 5
print(y) # Output: John
There are some rules and conventions for naming variables in Python:
Operators:
• Arithmetic operators (+, -, /, //, %, *, **)
• Assignment operators (=, +=, -=)
• Comparison operators (= =, , !=, <=, => )
• Logical operators (&, |, ~)
1. Python Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc. For example,
sub = 10 - 5 # 5
+ Addition 5 + 2 = 7
- Subtraction 4 - 2 = 2
* Multiplication 2 * 3 = 6
/ Division 4 / 2 = 2
% Modulo 5 % 2 = 1
INPUT:
Output:
= 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
Input:
output is 15
For example,
a = 5
b = 2
Here, the > comparison operator is used to compare whether a is greater than b or not.
Operator Meaning Example
Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True , the result is True .
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.
Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Note: in the result, the line breaks are inserted at the same position as in the code.
However, Python does not have a character data type, a single character is simply a string with a length
of 1.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
for x in "banana":
print(x)
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
Example
Check if "free" is present in the following text:
Use it in an if statement:
Example
Print only if "free" is present:
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
Example
Check if "expensive" is NOT present in the following text:
Use it in an if statement:
Example
print only if "expensive" is NOT present:
CONCATENATION OF STRINGS
String concatenation in Python is the process of joining two or more strings together. Here are some common methods to
concatenate strings:
Repetition
Repeating a string multiple time.
str1 = "Hello"
result = str1 * 3 # Result 'HelloHelloHello'
String Formatting in Python
String formatting in Python allows you to create dynamic strings by combining variables and values. Here are some common
methods:
1. F-Strings (Python 3.6+)
F-strings provide a concise and readable way to include the results of expressions within strings.
name = "Alice"
age = 30
2. format() Method
The format() method allows for more complex string formatting.
name = "Alice"
age = 30
3. % Operator
The % operator is an older method for string formatting.
name = "Alice"
age = 30
3. PRINT DATE MONTH AND YEAR USING ALL STRING FORMAT METHOD
# Define the variables
day = 31
month = 10
year = 2024
Conditional statements in Python allow you to control the flow of your program based on certain conditions. These statements
enable your program to make decisions and execute specific blocks of code depending on whether a condition is true or
false.
If Statement
The if statement is used to execute a block of code if a specified condition is true.
if condition:
# Statements to execute if condition is true
Example
if 10 > 5:
print("10 is greater than 5")
print("Program ended")
Output:
10 is greater than 5
Program ended
1
If-Else Statement
The if-else statement adds an additional block of code that executes if the condition is false.
if condition:
# Executes this block if condition is true
else:
# Executes this block if condition is false
Example:
x = 3
if x == 4:
print("Yes")
else:
print("No")
Output:
No
1
Example:
letter = "A"
if letter == "B":
print("letter is B")
else:
if letter == "C":
print("letter is C")
else:
if letter == "A":
print("letter is A")
else:
print("letter isn't A, B, or C")
Output:
letter is A
1
If-Elif-Else Statement
The if-elif-else statement allows you to check multiple conditions sequentially.
if condition1:
# Executes this block if condition1 is true
elif condition2:
# Executes this block if condition1 is false and condition2 is true
else:
# Executes this block if none of the conditions are true
Example:
letter = "A"
if letter == "B":
print("letter is B")
elif letter == "C":
print("letter is C")
elif letter == "A":
print("letter is A")
else:
print("letter isn't A, B, or C")
Output:
letter is A
While Loop
A while loop executes a block of statements repeatedly as long as a given condition is true. The syntax for a while loop is:
while expression:
statement(s)
Example:
count = 0
count += 1
print("Hello Geek")
Output:
Hello Geek
Hello Geek
Hello Geek
The loop continues until the condition count < 3 becomes false1.
For Loop
A for loop is used for iterating over a sequence (such as a list, tuple, string, or dictionary). The syntax for a for loop is:
for iterator_var in sequence:
statement(s)
Example:
n = 4
for i in range(n):
print(i)
Output:
0
Python allows the use of one loop inside another loop, known as nested loops. This can be useful for iterating over multi-
dimensional data structures. Example:
for i in range(1, 5):
for j in range(i):
print()
Output:
1
2 2
3 3 3
4 4 4 4
print(i)
else:
print("Finally finished!")
Output:
0
The else block will not execute if the loop is stopped by a break statement2.
By mastering loops in Python, you can automate repetitive tasks, iterate over data structures, and build more complex
algorithms efficiently. Loops are essential for any Python programmer and understanding their nuances will greatly enhance
your coding skills.
Functions in Python
A function in Python is a block of reusable code that performs a specific task. Functions help in organizing code, making it
more readable, and promoting code reuse. They can accept inputs (arguments) and return outputs.
Creating a Function
To define a function in Python, use the def keyword followed by the function name and parentheses. Inside the parentheses,
you can specify parameters. The function body is indented and contains the code to be executed.
def greet():
print("Hello, World!")
Calling a Function
To execute the code inside a function, you need to call the function by its name followed by parentheses.
greet() # Output: Hello, World!
Function Arguments
Functions can accept inputs called arguments. These arguments are specified inside the parentheses during the function
definition.
def greet(name):
print(f"Hello, {name}!")
Types of Arguments
1. Positional Arguments: Arguments passed in the correct positional order.
2. Keyword Arguments: Arguments passed with key-value pairs, allowing the order to be ignored.
3. Default Arguments: Arguments that assume a default value if not provided.
4. Arbitrary Arguments: Using *args for non-keyword arguments and **kwargs for keyword arguments.
def add_numbers(num1, num2=5):
print(add_numbers(3)) # Output: 8
def print_args(*args):
print(arg)
print_args(1, 2, 3) # Output: 1 2 3
def print_kwargs(**kwargs):
print(f"{key}: {value}")
Return Statement
Functions can return values using the return statement. This allows the function to send back a result to the caller.
def square(num):
result = square(4)
print(result) # Output: 16
Recursion
A function can call itself, which is known as recursion. Recursion is useful for solving problems that can be broken down into
smaller, repetitive tasks.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
Anonymous Functions
Python supports anonymous functions, also known as lambda functions. These are small, unnamed functions defined using
the lambda keyword.
square = lambda x: x * x
print(square(5)) # Output: 25
Nested Functions
Functions can be defined inside other functions. These are called nested functions and can access variables from the
enclosing scope.
def outer_function():
message = "Hello"
def inner_function():
print(message)
inner_function()
Functions in Python are versatile and powerful, allowing for a wide range of programming techniques and styles. They are
essential for writing clean, efficient, and maintainable code