Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python WINTER 2023

The document covers various Python programming concepts including key features, data types, loops, string slicing, literals, file operations, and exception handling. It provides examples of Python programs for tasks such as calculating grades, finding the area of a triangle, and removing vowels from a string. Additionally, it explains the differences between modules, packages, and libraries in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python WINTER 2023

The document covers various Python programming concepts including key features, data types, loops, string slicing, literals, file operations, and exception handling. It provides examples of Python programs for tasks such as calculating grades, finding the area of a triangle, and removing vowels from a string. Additionally, it explains the differences between modules, packages, and libraries in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Meet Prajapati : 210170117041

Q.1 (a) What are the key features of Python?


➢ WINTER 2022 Q 1 (a)

(b) List out various data types and operators in python.


➢ WINTER 2022 Q 1 (c)

(c) Explain while and for loop in python with example.


➢ WINTER 2022 Q 3 (c)

Q.2 (a) What is string slicing in python?


String Slicing in Python

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]

• start: The starting index of the slice (inclusive).


• end: The ending index of the slice (exclusive).
• step: The interval between characters (optional).

Examples:

1. Basic Slicing:

text = "Python Programming"


print(text[0:6]) # Output: Python

2. Omitting Indices:

print(text[:6]) # Output: Python (starts from index 0)


print(text[7:]) # Output: Programming (ends at the last index)

3. Using Negative Indices:

print(text[-11:-1]) # Output: Programmin


Meet Prajapati : 210170117041

4. Adding a Step:

print(text[::2]) # Output: Pto rgamn (every second character)

5. Reversing a String:

print(text[::-1]) # Output: gnimmargorP nohtyP

(b) How to use string literals and Boolean literals in python


String Literals in Python

• Definition: A string literal is a sequence of characters surrounded by quotes. It can be


enclosed in single, double, or triple quotes.
• Examples:

# 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

Boolean Literals in Python

• Definition: Boolean literals represent one of two values: True or False.


• Examples:

print(3 == 3) # Output: True


print(3 > 5) # Output: False

• Checking Boolean Types: The type of Boolean literals can be verified using the
type() function:

print(type(True)) # Output: <class 'bool'>


print(type(False)) # Output: <class 'bool'>

• 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

60-79 First Class

35-59 Second Class

0-34 Fail

Python Program

# Program to determine grade based on marks

# Step 1: Read marks from the user


marks = int(input("Enter the marks: "))

# Step 2: Determine and display the grade using conditional statements


if 80 <= marks <= 100:
print("Grade: Distinction")
elif 60 <= marks <= 79:
print("Grade: First Class")
elif 35 <= marks <= 59:
print("Grade: Second Class")
elif 0 <= marks <= 34:
print("Grade: Fail")
else:
print("Invalid marks entered.")
Meet Prajapati : 210170117041

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:

Enter the marks: 85

o Output:

Grade: Distinction

2. Case 2:
o Input:

Enter the marks: 72

o Output:

Grade: First Class

3. Case 3:
o Input:

Enter the marks: 45

o Output:

Grade: Second Class

4. Case 4:
o Input:

Enter the marks: 20

o Output:

Grade: Fail
Meet Prajapati : 210170117041

(c) Write python function program to find out factorial of a given


number.
➢ WINTER 2022 Q 3 (b)

Q.3 (a) What is python Identifiers?


Python Identifiers

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.

Rules for Python Identifiers:

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.

Examples of Valid Identifiers:

• total_sum
• age
• variable1

Examples of Invalid Identifiers:

• 1st_variable (starts with a digit)


• for (reserved keyword)
• total-sum (contains special character -)

By following these rules, you can ensure your program is free from identifier-related syntax
errors.
Meet Prajapati : 210170117041

(b) Demonstrate with simple code to draw the histogram in python.


Python Program to Draw a Histogram

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:

import matplotlib.pylab as plt

# x-axis values (data categories)


x = [2, 4, 6]

# y-axis values (frequencies)


y = [5, 10, 8]

# Function to plot a bar graph


plt.bar(x, y)

# Function to display the histogram


plt.show()

Explanation:

1. Importing Library: The matplotlib.pylab library is used for plotting.


2. Data: x represents the categories or bins, while y represents the corresponding frequencies.
3. Bar Plot: plt.bar() is the function used to create the bar graph.
4. Display: plt.show() displays the histogram on the window.

Output:

A histogram (bar graph) is displayed with the given x-axis and y-axis values.

(c) Describe conditional statements in python with example.


➢ WINTER 2022 or Q 3 (c)
Meet Prajapati : 210170117041

Q.3 (a) Explain Slicing of a list.


Slicing of a List

Slicing is used to access a range of elements in a list using the colon (:) operator.

Syntax:

list_name[start_index : end_index]

• start_index: Starting position (inclusive).


• end_index: Stopping position (exclusive).

Key Points:

1. Omitting start_index starts from the beginning.


2. Omitting end_index slices till the end.
3. Omitting both gives the entire list.

Example:

a = [10, 20, 30, 40, 50, 60]

print(a[1:4]) # [20, 30, 40]


print(a[:3]) # [10, 20, 30]
print(a[3:]) # [40, 50, 60]
print(a[:]) # [10, 20, 30, 40, 50, 60]

(b) Explain about how Exceptions are handled in python.


➢ SUMMER 2022 Q 5 (c)
Meet Prajapati : 210170117041

(c) Explain python file operations.


Python File Operations

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

Python provides the open() function to open a file.


Syntax:

file_object = open(file_name, mode)

• file_name: Name of the file.


• mode: Mode in which the file is opened.

Modes of File Operation:

Mode Description

r Read mode (default).

w Write mode (overwrites existing content).

x Create mode (fails if file already exists).

a Append mode (adds data at the end of the file).

t Text mode (default).

b Binary mode.

+ Read and Write 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

To write to a file, open it in write mode (w) or append mode (a).


Example:

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

5. Working with CSV Files

For handling CSV files, the csv module is used.


Example:

import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)

Q.4 (a) Write a python program to find the area of Triangle.


Python Program to Find the Area of a Triangle

To calculate the area of a triangle, we use the formula

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

# Input: Three sides of the triangle


a = float(input("Enter the first side: "))
b = float(input("Enter the second side: "))
c = float(input("Enter the third side: "))

# Calculate the semi-perimeter


s = (a + b + c) / 2

# Calculate the area using Heron's formula


area = math.sqrt(s * (s - a) * (s - b) * (s - c))

# Display the result


print("The area of the triangle is:", area)

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

(b) Illustrate the flow chart of if-elif-else statements.


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

# Input from user


N = int(input("Enter the value of N: "))

# Function call and result


result = sum_of_even_numbers(N)
print("The sum of first", N, "even numbers is:", result)

Output Example:

Enter the value of N: 5


The sum of first 5 even numbers is: 30

Explanation:

1. The program defines a function sum_of_even_numbers(N) to calculate the sum.


2. It uses a for loop to add even numbers (2, 4, ..., 2*N).
3. The result is returned and printed.
Meet Prajapati : 210170117041

Q.4 (a) What is the difference between Python’s Module, Package


and Library?
Difference Between Module, Package, and Library in Python
Feature Module Package Library

A single Python file A collection of modules in a A collection of pre-written


Definition containing functions, directory with a special packages and modules for
classes, or variables. __init__.py file. specific purposes.

A folder containing multiple Prebuilt tools/frameworks,


Structure A single .py file.
.py files and __init__.py. often installed via pip.

To reuse and organize To provide ready-to-use


Usage To organize related modules.
code. functionality for development.

math.py (standard MyPackage/ containing NumPy, Pandas, Matplotlib,


Example
module). module1.py. etc.

from package_name
Import import module_name import library_name
import module1

(b) Write python program that read a number from 1 to 7 and


accordingly it should display MONDAY to SUNDAY.
Python Program to Display Days of the Week Based on User Input

The program reads a number between 1 and 7 and displays the corresponding day of the
week.

Code:

# Read user input


day_number = int(input("Enter a number between 1 and 7: "))

# Display the corresponding day of the week


if day_number == 1:
print("MONDAY")
elif day_number == 2:
print("TUESDAY")
elif day_number == 3:
print("WEDNESDAY")
elif day_number == 4:
print("THURSDAY")
elif day_number == 5:
print("FRIDAY")
elif day_number == 6:
print("SATURDAY")
Meet Prajapati : 210170117041

elif day_number == 7:
print("SUNDAY")
else:
print("Invalid input! Please enter a number between 1 and 7.")

Output Example:

Enter a number between 1 and 7: 3


WEDNESDAY

Explanation:

1. The program asks the user to input a number between 1 and 7.


2. Based on the input, it uses if-elif-else statements to display the corresponding day of the
week.
3. If the input is outside the range of 1 to 7, it displays an error message.

(c) Consider the string S =”Hi, I want to go to Beverly Hills for a


vacation”. Write a python program to remove all vowels from the
string.
Python Program to Remove All Vowels from a String

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"

# Function call to remove vowels


modified_string = remove_vowels(S)

# Display the result


print("Original String: ", S)
print("String without vowels: ", modified_string)
Meet Prajapati : 210170117041

Output Example:

Original String: Hi, I want to go to Beverly Hills for a vacation


String without vowels: H, wnt t g t Bvrly Hlls fr vctn

Explanation:

1. The function remove_vowels(S) uses a list comprehension to iterate through each


character in the string and includes it in the result if it's not a vowel.
2. The join() method is used to combine the characters back into a string without the vowels.
3. The result is printed showing the original and modified strings.

Q.5 (a) Write a python program to find square root of a positive


number.
Python Program to Find the Square Root of a Positive Number

The program reads a positive number and calculates its square root using the math module.

Code:

import math

# Read input from user


num = float(input("Enter a positive number: "))

# Check if the number is positive


if num >= 0:
# Calculate the square root
sqrt_num = math.sqrt(num)
print("The square root of", num, "is:", sqrt_num)
else:
print("Please enter a positive number.")

Output Example:

Enter a positive number: 25


The square root of 25.0 is: 5.0

Explanation:

1. The program first checks if the entered number is positive.


2. It uses the math.sqrt() function to calculate the square root of the number.
3. If the number is negative, it prompts the user to enter a positive number.
Meet Prajapati : 210170117041

(b) Discuss in brief python “Dictionaries” with example


Python Dictionaries

A Dictionary in Python is an unordered collection of items stored as key-value pairs. Each


key in the dictionary must be unique, and it is associated with a specific value.

Key Features of Dictionaries:

• 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.

Syntax to Create a Dictionary:

# Using curly braces to create a dictionary


my_dict = {1: 'Apple', 2: 'Banana', 3: 'Cherry'}

# Using the dict() constructor to create a dictionary


my_dict = dict({1: 'Apple', 2: 'Banana', 3: 'Cherry'})

Accessing Values:

Values in a dictionary are accessed using the keys:

my_dict = {'name': 'Alice', 'age': 25}


print(my_dict['name']) # Output: Alice

Modifying a Dictionary:

You can update values or add new key-value pairs:

# Updating a value
my_dict['age'] = 30

# Adding a new key-value pair


my_dict['city'] = 'New York'

print(my_dict) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}


Meet Prajapati : 210170117041

Deleting Items:

To remove an item from a dictionary, you can use del:

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

• Length: Use len() to get the number of items in a dictionary:

print(len(my_dict)) # Output: 2 (if there are two items)

Iterating Over a Dictionary:

You can iterate over keys, values, or key-value pairs:

for key, value in my_dict.items():


print(key, value)

Example Program:

my_dict = {'name': 'John', 'age': 22}


print(my_dict) # Output: {'name': 'John', 'age': 22}

# Adding a new key-value pair


my_dict['city'] = 'New York'
print(my_dict) # Output: {'name': 'John', 'age': 22, 'city': 'New York'}

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

# Input: Three numbers from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Nested if statement to find the largest number


if num1 >= num2:
if num1 >= num3:
largest = num1
else:
largest = num3
else:
if num2 >= num3:
largest = num2
else:
largest = num3

# Display the largest number


print("The largest number is:", largest)

Output Example:

Enter the first number: 12


Enter the second number: 25
Enter the third number: 18
The largest number is: 25.0

Explanation:

1. The program asks the user to input three numbers.


2. It uses a nested if statement to compare the first number (num1) with the second and third
numbers. If num1 is greater than or equal to both, it's the largest. If not, it checks the next
number using a nested if condition.
3. The result (the largest number) is displayed at the end.
Meet Prajapati : 210170117041

Q.5 (a) How to read CSV file in python explain with example.
➢ SUMMER 2022 Q 5 (a)

(b) Write a Python program which accepts a sequence of comma


separated numbers from the user and generate a list and a tuple
with those numbers.
Python Program to Accept a Sequence of Comma-Separated Numbers and Generate a List
and a Tuple

This program accepts a sequence of comma-separated numbers from the user and generates
both a list and a tuple from the input.

Code:

# Input: Sequence of comma-separated numbers


user_input = input("Enter numbers separated by commas: ")

# Generate list by splitting the input string by commas


number_list = user_input.split(',')

# Generate tuple from the list


number_tuple = tuple(number_list)

# Display the results


print("List:", number_list)
print("Tuple:", number_tuple)

Output Example:

Enter numbers separated by commas: 1,2,3,4,5


List: ['1', '2', '3', '4', '5']
Tuple: ('1', '2', '3', '4', '5')

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

(c) What is Mycro-Python ? How it is used to do programing for


GPIO device
MicroPython and GPIO Programming

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.

• Lightweight: MicroPython is optimized to run on microcontrollers with limited resources like


memory and processing power.
• Python Syntax: It retains most of the standard Python syntax, making it easy to use for
Python developers.
• Real-time Control: It is used to program devices in real-time, such as turning on/off lights,
reading sensor data, etc.

How is MicroPython Used for GPIO Programming?

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.

Example Code to Control GPIO Pins:

Let's consider the example of turning an LED on and off using MicroPython.

1. Import the necessary library:


o We use the Pin class from the machine module to control the GPIO pins.
2. Configure the Pin:
o Define the pin number and set it as an output pin.
3. Control the Pin:
o Use pin.value(1) to turn the LED on and pin.value(0) to turn it off.
Meet Prajapati : 210170117041

from machine import Pin # Import the Pin class from the machine module

# Set up GPIO pin 2 as an output pin


pin = Pin(2, Pin.OUT)

# Turn on the LED (set pin to HIGH)


pin.value(1)

# Turn off the LED (set pin to LOW)


pin.value(0)

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.

Example: Reading a Button Input

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.

from machine import Pin

# Set up GPIO pin 5 as an input pin (for button)


button = Pin(5, Pin.IN)

# Read the button state


if button.value() == 1:
print("Button is pressed")
else:
print("Button is not pressed")

You might also like