Python WINTER 2023
Python WINTER 2023
String slicing is a technique used to extract a portion of a string based on specified indices. It
utilizes the colon : operator within square brackets [] to define the start and end points of the
slice.
Syntax:
string[start:end:step]
Examples:
1. Basic Slicing:
2. Omitting Indices:
4. Adding a Step:
5. Reversing a String:
# Single-quoted string
string1 = 'Hello'
# Double-quoted string
string2 = "World"
# Triple-quoted string
string3 = """This is a triple-quoted string."""
• Usage: String literals are used to store textual data. Python allows operations like
concatenation and repetition on strings using + and * operators, respectively:
str1 = "Hello"
str2 = "Python"
print(str1 + " " + str2) # Output: Hello Python
print(str2 * 3) # Output: PythonPythonPython
• Checking Boolean Types: The type of Boolean literals can be verified using the
type() function:
• Usage in Expressions: Boolean literals are widely used in conditional statements and
logical operations:
Meet Prajapati : 210170117041
if 3 > 2:
print("True")
else:
print("False")
(c) Write python program to read mark from keyboard and your
program should display equivalent grade according to following
table.
Python Program to Read Marks and Display Equivalent Grade
The following program reads marks from the user and displays the equivalent grade
according to the given table:
Grading Table
Marks Grade
100-80 Distinction
0-34 Fail
Python Program
Explanation
1. Input:
o The program reads the marks as an integer using input().
o The value is stored in the variable marks.
2. Logic:
o The if-elif ladder is used to check which range the marks fall into.
o Based on the range, the corresponding grade is displayed.
o An additional condition handles invalid input (marks not in the range of 0 to 100).
3. Output:
o The print() function is used to display the grade.
Example Execution
1. Case 1:
o Input:
o Output:
Grade: Distinction
2. Case 2:
o Input:
o Output:
3. Case 3:
o Input:
o Output:
4. Case 4:
o Input:
o Output:
Grade: Fail
Meet Prajapati : 210170117041
In Python, Identifiers are the names used to identify variables, functions, classes, modules,
or objects. These names must follow certain rules and conventions to ensure proper
functioning in Python.
1. An identifier can only contain letters (a-z, A-Z), digits (0-9), and underscores (_).
2. An identifier cannot start with a digit.
3. Python keywords cannot be used as identifiers.
4. Identifiers are case-sensitive. For example, Variable and variable are considered
different.
5. The length of an identifier is not limited, but it is advisable to keep it readable and
meaningful.
• total_sum
• age
• variable1
By following these rules, you can ensure your program is free from identifier-related syntax
errors.
Meet Prajapati : 210170117041
To draw a histogram in Python, the matplotlib library can be used. Below is the example
code provided for plotting a bar graph using the matplotlib library:
Code Example:
Explanation:
Output:
A histogram (bar graph) is displayed with the given x-axis and y-axis values.
Slicing is used to access a range of elements in a list using the colon (:) operator.
Syntax:
list_name[start_index : end_index]
Key Points:
Example:
File operations in Python include opening, reading, writing, appending, and closing files.
Files can be handled in text mode or binary mode.
1. Opening a File
Mode Description
b Binary mode.
2. Reading a File
To read a file, open it in read mode (r) and use the read(), readline(), or readlines()
methods.
Example:
f = open("test.txt", "r")
print(f.read()) # Reads entire file
f.close()
Meet Prajapati : 210170117041
3. Writing to a File
f = open("test.txt", "w")
f.write("Hello, GTU!") # Overwrites file content
f.close()
4. Closing a File
After performing operations, always close the file using close() to free resources.
Example:
f = open("test.txt", "r")
f.close()
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
Area = / s(s−a)(s−b)(s−c)
where sss is the semi-perimeter, and a,b,ca, b, ca,b,c are the three sides of the triangle.
Meet Prajapati : 210170117041
Python Code:
import math
Output Example:
yaml
Copy code
Enter the first side: 3
Enter the second side: 4
Enter the third side: 5
The area of the triangle is: 6.0
Meet Prajapati : 210170117041
(c) Write a python program using function to find the sum of first N
even numbers and print the result.
Python Program to Find the Sum of First N Even Numbers Using a Function
Code:
def sum_of_even_numbers(N):
total = 0
for i in range(1, N + 1):
total += 2 * i # Sum of first N even numbers (2, 4, 6, ..., 2*N)
return total
Output Example:
Explanation:
from package_name
Import import module_name import library_name
import module1
The program reads a number between 1 and 7 and displays the corresponding day of the
week.
Code:
elif day_number == 7:
print("SUNDAY")
else:
print("Invalid input! Please enter a number between 1 and 7.")
Output Example:
Explanation:
The program reads the string S = "Hi, I want to go to Beverly Hills for a
vacation" and removes all vowels (a, e, i, o, u) from it.
Code:
def remove_vowels(S):
vowels = "aeiouAEIOU"
result = "".join([char for char in S if char not in vowels])
return result
# Input string
S = "Hi, I want to go to Beverly Hills for a vacation"
Output Example:
Explanation:
The program reads a positive number and calculates its square root using the math module.
Code:
import math
Output Example:
Explanation:
• Unordered Collection: Python dictionaries do not maintain the order of the elements (prior
to Python 3.7).
• Key-Value Pairs: Each dictionary entry consists of a unique key and an associated value.
• Mutable: Dictionaries are mutable, meaning their contents can be changed, values updated,
or items removed.
• Unique Keys: All keys in a dictionary must be unique; however, values can be repeated.
Accessing Values:
Modifying a Dictionary:
# Updating a value
my_dict['age'] = 30
Deleting Items:
del my_dict['city']
print(my_dict) # Output: {'name': 'Alice', 'age': 30}
Dictionary Operations:
• Copying: You can create a shallow copy of a dictionary using the copy() method:
new_dict = my_dict.copy()
• Clearing: The clear() method removes all items from the dictionary:
my_dict.clear()
Example Program:
# Deleting an item
del my_dict['age']
print(my_dict) # Output: {'name': 'John', 'city': 'New York'}
Meet Prajapati : 210170117041
(c) Write python program to find big number from three number
using Nested if statement
Python Program to Find the Biggest Number from Three Numbers Using Nested If Statements
The program uses nested if statements to find the largest number among three given
numbers.
Code:
Output Example:
Explanation:
Q.5 (a) How to read CSV file in python explain with example.
➢ SUMMER 2022 Q 5 (a)
This program accepts a sequence of comma-separated numbers from the user and generates
both a list and a tuple from the input.
Code:
Output Example:
Explanation:
1. The program prompts the user to input a sequence of numbers separated by commas.
2. The split(',') method is used to split the string into a list based on commas.
3. The tuple() function is used to convert the list into a tuple.
4. Both the list and the tuple are printed to the console.
Meet Prajapati : 210170117041
What is MicroPython?
MicroPython is a lean and efficient version of the Python programming language, designed
to run on small microcontrollers and embedded systems. It allows you to write Python code
that interacts directly with hardware, making it ideal for controlling devices like sensors,
motors, LEDs, and more.
GPIO (General Purpose Input/Output) pins are used on microcontrollers to interact with
external devices. In MicroPython, you can control these pins to read inputs (e.g., a button
press) or control outputs (e.g., turning on an LED).
MicroPython provides a machine module, which allows you to interact with the GPIO pins of
a microcontroller.
Let's consider the example of turning an LED on and off using MicroPython.
from machine import Pin # Import the Pin class from the machine module
Explanation:
• Pin(2, Pin.OUT): This initializes GPIO pin 2 as an output pin. You can change 2 to any
other GPIO pin number on your device.
• pin.value(1): This sets the pin to HIGH, turning on the connected device (e.g., an LED).
• pin.value(0): This sets the pin to LOW, turning off the device.
Key Concepts:
• Pin as Input or Output: You can use Pin.IN for input pins (e.g., reading button presses) and
Pin.OUT for output pins (e.g., controlling an LED).
• Reading Pin Value: To read the value of an input pin (e.g., whether a button is pressed), you
can use pin.value().
• Real-Time Control: MicroPython allows real-time control of hardware using simple Python
code.
If you want to read the state of a button (whether it is pressed or not), you can configure the
pin as an input and check its value.