0% found this document useful (0 votes)
2 views24 pages

Mid Term

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 24

USING PRINT FUNCTION

INPUT: OUTPUT:

PRINT STATEMENT IN PYTHON


TASK 1:

PRINT NAME ROLL NO AND SECTION IN NEW LINE


print("MY NAME IS HAMID ZAYAN")

print("MY ROLL NO IS 2024-EE-410")

print("MY SECTION IS B")

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

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:

Str

int, float, complex

list, tuple, range

Dict

FLOAT DATA TYPE

Data type with decimal point is called float data type:

Int data type:


Data type without decimal point is called int data type

Str data type


String data type is a data type that contains alphabet

BOOLEAN DATA TYPE:


The Boolean data type is a fundamental data type in programming that represents one of
two values: true or false. These values are used to perform logical operations and control
the flow of a program. The Boolean data type is named after George Boole, who
developed Boolean algebra in the mid-19th century
Python boolean type is one of the built-in data types provided by Python, which represents one
of the two values i.e. True or False. Generally, it is used to represent the truth values of the
expressions.
Example
Input: 1==1
Output: True
Input: 2<1
Output: False
Python Boolean Type
The boolean value can be of two types only i.e. either True or False.
a = True
type(a)

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

Variable Naming Rules

There are some rules and conventions for naming variables in Python:

 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 (e.g., name , Name , and NAME are three different variables)

TASK 1: Print your roll no,name and class using variable

name = "Hamid Zayan"


roll_no = "2024-EE-410"
section = "B"
print(name)
print(roll_no)
print(section)
TASK 2: Take V as variable name, and it is a float type, assign it value of your choice and then print it.
# Define the variable V as a float
V = 3.14
# Print the value of V
print(V)
TASK3: Take any three variables, you can name it as you want (following the rules), assign value to them, and print it using
one print function
# Define the variables
x = 10
y = 20.5
z = "Hello, World!"
# Print the values of the variables using one print function
print(x, y, z)
TASK4: Take two variables of different types then assign them value using only one assignment statement then print each
in new line using only one print function.
# Assign values to two variables of different types in one statement
a, b = 42, "Hello, Python!"
# Print each variable on a new line using one print function
print(f"{a}\n{b}")

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

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

% Modulo 5 % 2 = 1

INPUT:

Output:

2. Python Assignment Operators


Assignment operators are used to assign values to variables. For example,
# assign 5 to x
x = 5

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


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

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

Input:

output is 15

3. Python Comparison Operators


Comparison operators compare two values/variables and return a boolean result: True or False .

For example,
a = 5
b = 2

print (a > b) # True


Run Code

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


Run Code

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.

TASK1: Take a string from a user and print it.


# Take input from the user
user_input = input("Enter a string: ")
# Print the input string
print(user_input)
TASK2: Take an integer from a user and print it.
# Take an integer input from the user
user_input = int(input("Enter an integer: "))
# Print the input integer
print(user_input)
INTRODUCTION TO STRINGS

Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

ExampleGet your own Python Server


print("Hello")
print('Hello')

Quotes Inside Quotes


You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

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:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Or three single 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.

Strings are Arrays


Like many other popular programming languages, strings in Python are arrays of bytes representing
unicode characters.

However, Python does not have a character data type, a single character is simply a string with a length
of 1.

Square brackets can be used to access elements of the string.

Example
Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])

Looping Through a String


Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
Loop through the letters in the word "banana":

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:

txt = "The best things in life are free!"


print("free" in txt)

Use it in an if statement:

Example
Print only if "free" is present:

txt = "The best things in life are free!"


if "free" in txt:
print("Yes, '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:

txt = "The best things in life are free!"


print("expensive" not in txt)

Use it in an if statement:

Example
print only if "expensive" is NOT present:

txt = "The best things in life are free!"


if "expensive" not in txt:
print("No, '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:

1. Using the + Operator:


2. str1 = "Hello"
3. str2 = "World"
4. result = str1 + " " + str2
5. print(result) # Output: Hello World
6. Using the += Operator:
7. str1 = "Hello"
8. str1 += " World"
9. print(str1) # Output: Hello World
10. Using the join() Method:
11. str_list = ["Hello", "World"]
12. result = " ".join(str_list)
13. print(result) # Output: Hello World
14. Using the format() Method:
15. str1 = "Hello"
16. str2 = "World"
17. result = "{} {}".format(str1, str2)
18. print(result) # Output: Hello World
19. Using f-Strings (Python 3.6+):
20. str1 = "Hello"
21. str2 = "World"
22. result = f"{str1} {str2}"
23. print(result) # Output: Hello World

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

print(f"Name: {name}, Age: {age}")

2. format() Method
The format() method allows for more complex string formatting.
name = "Alice"

age = 30

print("Name: {}, Age: {}".format(name, age))

3. % Operator
The % operator is an older method for string formatting.
name = "Alice"

age = 30

print("Name: %s, Age: %d" % (name, age))


Considerations

 F-Strings are preferred for their readability and performance1.


 The format() method is useful for more complex formatting needs2.
 The % operator is less commonly used in modern Python but may be seen in legacy code
1. PRINT I AM CODING 10 TIMES
for _ in range(10):
print("I am coding")
2. Take a string from the user and print it in reverse order. Hint slicing method will be used.
# Take input from the user
user_input = input("Enter a string: ")

# Print the string in reverse order using slicing


print(user_input[::-1])

3. PRINT DATE MONTH AND YEAR USING ALL STRING FORMAT METHOD
# Define the variables
day = 31
month = 10
year = 2024

# Using f-string (formatted string literals)


print(f"Date: {day:02d}/{month:02d}/{year}")

CONDITIONAL STATEMENTS IN PYTHON

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.

Types of Conditional Statements

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

Nested If-Else Statement


Nested if-else statements allow you to place an if-else statement inside another if statement.
if condition1:
if condition2:
# Statements to execute if both conditions are true
else:
# Statements to execute if condition1 is true and condition2 is false
else:
# Statements to execute if condition1 is false

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

CHECK IF NO IS EVEN OR ODD


number = int(input("Enter a number: "))
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
CHECK NO IS POSITIVE OR NEGATIVE
number = int(input("Enter a number: "))
if number > 0:
print(f"{number} is positive.")
elif number < 0:
print(f"{number} is negative.")
else:
print(f"{number} is zero.")
CHECK FIRST NO IS SMALLER THAN SECOND NO
first_number = int(input("Enter the first number: "))
second_number = int(input("Enter the second number: "))
if first_number < second_number:
print(f"{first_number} is smaller than {second_number}.")
else:
print(f"{first_number} is not smaller than {second_number}.")
CHECK IF THE LETTER IS VOWEL OR NOT
letter = input("Enter a letter: ").lower()
if letter in 'aeiou':
print(f"{letter} is a vowel.")
else:
print(f"{letter} is not a vowel.")
PRINT GRADE ON TEST BASE
score = int(input("Enter your test score (0-100): "))
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Loops in Python
Loops are fundamental constructs in Python that allow you to execute a block of code repeatedly. Python provides two
primary types of loops: for loops and while loops. Each type of loop serves different purposes and has its own syntax and
use cases.

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

while count < 3:

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

The loop iterates over the values from 0 to 32.


Nested Loops

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(i, end=' ')

print()

Output:
1

2 2

3 3 3

4 4 4 4

This creates a triangular pattern of numbers1.


Loop Control Statements

Python provides several control statements to alter the flow of loops:


 Continue Statement: Skips the current iteration and continues with the next iteration. for letter in
'geeksforgeeks': if letter == 'e' or letter == 's': continue print('Current Letter:',
letter) Output: Current Letter: g Current Letter: k Current Letter: f Current Letter: o Current
Letter: r Current Letter: g Current Letter: k
 Break Statement: Exits the loop prematurely. for letter in 'geeksforgeeks': if letter == 'e' or letter ==
's': break print('Current Letter:', letter) Output: Current Letter: g
 Pass Statement: Does nothing and is used as a placeholder. for letter in 'geeksforgeeks': pass print('Last
Letter:', letter) Output: Last Letter: s
Using Else with Loops
Both for and while loops can have an else clause that executes after the loop completes normally (i.e., not terminated by
a break statement). Example:
for i in range(6):

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}!")

greet("John") # Output: Hello, John!

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

return num1 + num2

print(add_numbers(3)) # Output: 8

print(add_numbers(3, 4)) # Output: 7

def print_args(*args):

for arg in args:

print(arg)

print_args(1, 2, 3) # Output: 1 2 3

def print_kwargs(**kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")

print_kwargs(name="John", age=30) # Output: name: John age: 30

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

return num * 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)

print(factorial(5)) # Output: 120

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

outer_function() # Output: Hello

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

1. Write a function called add_numbers(a, b) that takes two


numbers and returns their sum.
def add_numbers(a, b):
return a + b
2. Write a function called area_of_rectangle(length, width)
that takes the length and width of a rectangle and returns
its area.
def area_of_rectangle(length, width):
return length * width
3. Write a function called is_even(number) that returns True
if the number is even and False if it is odd.
def is_even(number):
return number % 2 == 0
4. Write a function called fahrenheit_to_celsius(f) that takes
a temperature in Fahrenheit and returns the temperature
in Celsius using the formula
def fahrenheit_to_celsius(f):
return (5/9) * (f - 32)
5. Write a function called calculator(a, b, operator) that
takes two numbers a and b and an operator as input. It
should return the result of the operation (+, -, *, /). If the
operator is not valid, return "Invalid operator"
def calculator(a, b, operator):
if operator == '+':
return a + b
elif operator == '-':
return a - b
elif operator == '*':
return a * b
elif operator == '/':
if b != 0:
return a / b
else:
return "Error: Division by zero!"
else:
return "Invalid operator"
6. Write a function called factorial(n) that returns the
factorial of a number n. The factorial of n is defined as
n×(n−1)×(n−2)×⋯×1
def factorial(n):
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result

You might also like