0% found this document useful (0 votes)
5 views39 pages

Unit 1 Introduction

Uploaded by

dr.anuragkr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views39 pages

Unit 1 Introduction

Uploaded by

dr.anuragkr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

UNIT – 1

INTRODUCTION

Python is a widely used general-purpose, high-level programming language.

It was created by Guido van Rossum in 1991 and further developed by the Python Software
Foundation.

It was designed with an emphasis on code readability, and its syntax allows programmers to
express their concepts in fewer lines of code.

Python is a programming language that lets you work quickly and integrate systems more
efficiently.

Features of Python Programming Language

1. Free and Open Source

Python language is freely available at the official website and you can download it from the
website. It is open-source, this means that source code is also available to the public. So you can
download it, use it as well as share it.

2. Easy to code

Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, Javascript, Java, etc. It is very easy to code in the
Python language and anybody can learn Python basics in a few hours or days. It is also a
developer-friendly language.

3. Easy to Read

As you will see, learning Python is quite simple. As was already established, Python’s syntax is
really straightforward. The code block is defined by the indentations rather than by semicolons
or brackets.

4. Object-Oriented Language

One of the key features of Python is Object-Oriented programming. Python supports object-
oriented language and concepts of classes, object encapsulation, etc.

5. GUI Programming Support


Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk
in Python. PyQt5 is the most popular option for creating graphical apps with Python.

6. High-Level Language

Python is a high-level language. When we write programs in Python, we do not need to


remember the system architecture, nor do we need to manage the memory.

7. Large Community Support

Python has gained popularity over the years. Our questions are constantly answered by the
enormous StackOverflow community.

8. Easy to Debug

Excellent information for mistake tracing. You will be able to quickly identify and correct the
majority of your program’s issues once you understand how to interpret Python’s error traces.
Simply by glancing at the code, you can determine what it is designed to perform.

9. Python is a Portable language

Python language is also a portable language. For example, if we have Python code for Windows
and if we want to run this code on other platforms such as Linux, Unix, and Mac then we do not
need to change it, we can run this code on any platform.

10. Python is an Integrated language

Python is also an Integrated language because we can easily integrate Python with other
languages like C, C++, etc.

11. Interpreted Language:

Python is an Interpreted Language because Python code is executed line by line at a time. like
other languages C, C++, Java, etc. there is no need to compile Python code this makes it easier to
debug our code. The source code of Python is converted into an immediate form called
bytecode.

12. Large Standard Library

Python has a large standard library that provides a rich set of modules and functions so you do
not have to write your own code for every single thing. There are many libraries present in
Python such as regular expressions, unit-testing, web browsers, etc.

13. Dynamically Typed Language


Python is a dynamically-typed language. That means the type (for example- int, double, long,
etc.) for a variable is decided at run time not in advance because of this feature we don’t need to
specify the type of variable.

14. Frontend and backend development

With a new project py script, you can run and write Python codes in HTML with the help of
some simple tags <py-script>, <py-env>, etc. This will help you do frontend development work
in Python like javascript. Backend is the strong forte of Python it’s extensively used for this
work cause of its frameworks like Django and Flask.

15. Allocating Memory Dynamically

In Python, the variable data type does not need to be specified. The memory is automatically
allocated to a variable at runtime when it is given a value. Developers do not need to write int y
= 18 if the integer value 15 is set to y. You may just type y=18

Advantages of Python Programming Language

• Presence of third-party modules


• Extensive support libraries
• Open source and large active community base
• Versatile, easy to read, learn, and write
• User-friendly data structures
• High-level language
• Dynamically typed language
• Object-Oriented and Procedural programming language
• Portable and interactive
• Ideal for prototypes
• Highly efficient
• Internet of Things (IoT) opportunities

Disadvantages of Python Programming Language

1. Performance: Python is an interpreted language, which means that it can be slower than
compiled languages like C or Java. This can be an issue for performance-intensive tasks.

2. Global Interpreter Lock: The Global Interpreter Lock (GIL) is a mechanism in Python
that prevents multiple threads from executing Python code at once. This can limit the
parallelism and concurrency of some applications.
3. Memory consumption: Python can consume a lot of memory, especially when working
with large datasets or running complex algorithms.

4. Dynamically typed: Python is a dynamically typed language, which means that the types
of variables can change at runtime. This can make it more difficult to catch errors and can
lead to bugs.

5. Packaging and versioning: Python has a large number of packages and libraries, which
can sometimes lead to versioning issues and package conflicts.

Applications of Python Programming Language

• Web Development
• Data Science and Data Analysis
• Machine Learning and Artificial Intelligence
• Automation and Scripting
• Game Development
• Desktop GUI Applications
• Network Programming
• Scientific and Numeric Computing
• Robotics and IoT
• Web Scraping
• Cybersecurity
• Natural Language Processing (NLP)
• Software Prototyping and Development
• Enterprise Applications

There are two major Python versions: Python 2 and Python 3.

Difference Between Python 2 and Python 3

The main difference between Python 2.x and Python 3.x lies in improvements to make the
language more consistent and efficient. Python 3.x introduced significant changes that are not
backward compatible with Python 2.x. Below are the key differences:
Key Difference Python 2.x Python 3.x
Python 2.x: print is a Python 3.x: print() is a
statement, not a function. function, so parentheses are
Parentheses are optional. mandatory.
Print Function
Ex: print "Hello, World!" # print("Hello, World!") #
No parentheses needed Parentheses required
Python 2.x: Division between Python 3.x: Division between
two integers truncates the two integers results in a float.
result to an integer. Python 3.x introduced // for
floor division (integer result).
Integer Division Ex: print 7 / 2 # Outputs 3
(truncated division) Ex: print(7 / 2) # Outputs 3.5
(true division)
print(7 // 2) # Outputs 3

Python 2.x: Exceptions are Python 3.x: The syntax for


handled with an old-style exceptions has changed,
syntax. requiring parentheses.
Error Handling
Ex: try: # code except Ex: try: # code except
Exception, e: # No Exception as e: # Requires 'as'
parentheses print e print(e)
Python 2.x: Most major Python 3.x: Actively
libraries have dropped support maintained, with continued
Libraries and Community
for Python 2, as Python 2 development and new features
Support
officially reached the end of being added.
life on January 1, 2020.

• Python 3.x introduces cleaner syntax and better support for modern programming needs, like
Unicode and memory-efficient functions.
• Python 2.x is outdated and no longer officially supported.
• If you're starting new projects, Python 3.x is the way to go, as it is the future of the language.
KEY CONCEPTS:

Python Identifiers

Python Identifier is the name we give to identify a variable, function, class, module or other
object. That means whenever we want to give an entity a name, that’s called identifier.

It helps a programmer to distinguish one entity from another entity.

Rules for Naming Identifiers:

1. Allowed Characters: Identifiers can contain letters (a-z, A-Z), digits (0-9), and
underscores (_).
2. Cannot Start with a Digit: Identifiers must start with a letter or an underscore, not a
digit.
o Example: _variable, age_1 are valid; 1variable is not.
3. Case-Sensitive: Python identifiers are case-sensitive. For example, Variable and
variable are treated as different names.
4. No Keywords: Identifiers cannot be the same as Python’s reserved keywords, like if,
else, class, etc.
5. No Special Characters: Identifiers cannot contain special characters like @, #, $, etc.

Examples:

• Valid: my_var, count1, _temp


• Invalid: 1st_variable, my-var, for

Keywords

Python keywords are reserved words in Python that have special meanings and cannot be used
as identifiers (e.g., variable names, function names).

As of Python 3.10, there are 35 keywords in Python. However, the number may vary slightly
depending on the Python version you're using. You can check the current list of keywords for
your version using the following code:

import keyword

print(len(keyword.kwlist)) # Total number of keywords

print(keyword.kwlist) # List of keywords


• Keywords are case-sensitive.

• They cannot be used as variable names or function names.

Indentations

Indentation is a very important concept of Python because without properly indenting the Python
code, you will end up seeing IndentationError and the code will not get compiled.

Python indentation refers to adding white space before a statement to a particular block of code.
In other words, all the statements with the same space to the left, belong to the same code block.

Examples:
Correct Indentation:

Incorrect Indentation (will raise IndentationError):

Comments in Python

A comment in Python is a piece of text within the code that is not executed by the interpreter.

It is used to explain the code, make it more readable, or leave notes for future reference.

Comments are essential for documentation and improving code maintainability.

Types of Comments in Python:

1. Single-Line Comment:
• A single-line comment starts with the # symbol. Everything after the # on that line is
ignored by the Python interpreter.
• It is often used to explain a single line or part of the code.

2. Multi-Line Comment (Block Comment):


• Python does not have an explicit syntax for multi-line comments. However, you can
create block comments by using # at the beginning of each line.

# This is a block comment.

# It spans multiple lines.


# Each line starts with a hash symbol.

3. Docstrings (Documentation Strings):


• Docstrings are used to document functions, classes, or modules. They are written
inside triple quotes ( ''' or """) and can span multiple lines.
• Docstrings can also serve as multi-line comments when used outside of a function or
class, although they are typically reserved for documentation.

def greet():

""" This is a docstring.

It describes what the function does. """

print("Hello, World!")

Why Use Comments?

1. Code Explanation: Comments help to explain what the code is doing, especially when
the logic is complex.
2. Readability: Well-placed comments make the code more readable and easier to
understand for other developers or for yourself when revisiting the code later.
3. Temporary Debugging: Comments can be used to temporarily disable parts of the code
during debugging or testing.

Operators

An operator in Python is a symbol that performs an operation on one or more operands


(variables or values). Operators are essential for performing arithmetic, logical, comparison,
assignment, and other operations in Python.

Types of Operators in Python:

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations.

Ex:

a = 10

b=3

print(a + b) # Output: 13

print(a ** b) # Output: 1000 (a raised to the power of b)

2. Comparison (Relational) Operators

Comparison operators compare two values and return a boolean ( True or False).
Ex:

a = 10

b=5

print(a > b) # Output: True

print(a == b) # Output: False

3. Assignment Operators

Assignment operators are used to assign values to variables.

Ex:

x = 10 # Assigns 10 to x

print(x) # Output: 10

x=5

x += 3 # Equivalent to x = x + 3

print(x) # Output: 8

x=5
x -= 2 # Equivalent to x = x - 2

print(x) # Output: 3

x=4

x *= 3 # Equivalent to x = x * 3

print(x) # Output: 12

x = 10

x /= 2 # Equivalent to x = x / 2

print(x) # Output: 5.0

4. Logical Operators

Logical operators are used to combine conditional statements and return True or False.

Ex:

a = True

b = False

print(a and b) # Output: False

print(a or b) # Output: True

5. Bitwise Operators

Bitwise operators perform bit-level operations on integers.


Bitwise operators in Python are used to perform operations on binary representations of
numbers. These operators work directly on bits and are often used in low-level programming, but
they can also be useful in various computational tasks.

Ex:
6. Membership Operators

Membership operators are used to check if a value is a member of a sequence (like a list, tuple,
or string).

Ex:

my_list = [1, 2, 3, 4]

print(3 in my_list) # Output: True

print(5 not in my_list) # Output: True

7. Identity Operators

Identity operators compare the memory locations of two objects.

Using is operator:

a = [1, 2, 3]

b=a

c = [1, 2, 3]

print(a is b) # Output: True, since 'b' refers to the same object as 'a'

print(a is c) # Output: False, even though 'a' and 'c' have the same content, they are
different objects

Using is not operator:

a = [1, 2, 3]

b = [1, 2, 3]

print(a is not b) # Output: True, since 'a' and 'b' are different object.
Data Types

• Primitive Types:

• String: strings are classified as a primitive data type. Although strings are sequences of
characters, and you can think of them as collections in some contexts, they are generally
considered primitive because they are a fundamental, built-in data type provided by the
language.
• Numeric: Includes int, float, and complex. These types represent numbers, whether
they are integers, floating-point numbers, or complex numbers with both real and
imaginary parts.
• Boolean: Includes bool, which represents truth values ( True or False).

• Collection Types:

• List: An ordered and mutable collection of items.


• Tuple: An ordered but immutable collection of items.
• Set: An unordered collection of unique items.
• Dictionary: An unordered collection of key-value pairs.

• Special Types:

• NoneType: Represents the absence of a value with the single instance None.
• Bytes: Includes bytes (immutable sequence of bytes) and bytearray (mutable sequence
of bytes).

String

In Python, strings are sequences of characters enclosed in quotes. They are one of the most
commonly used data types for handling textual data.

String Creation

Strings can be created using single quotes ( '), double quotes ( "), or triple quotes ( ''' or """) for
multi-line strings.

• Single Quotes: 'Hello'


• Double Quotes: "Hello"
• Triple Quotes:
o Single Line: '''Hello'''
o Multi-Line: """Hello\nWorld"""

EX:
single_quote_str = 'Hello'

double_quote_str = "Hello"

triple_quote_str = """Hello

World”””

Basic Operations

• Concatenation: Joining two or more strings using the + operator.

str1 = "Hello"

str2 = "World"

result = str1 + " " + str2 # Result: "Hello World"

• Repetition: Repeating a string using the * operator.

str1 = "Hello"

result = str1 * 3 # Result: "HelloHelloHello"

• Indexing: Accessing individual characters using zero-based indexing.

str1 = "Hello"

first_char = str1[0] # Result: 'H'

• Slicing: Extracting a substring using slicing notation [start:stop:step].

str1 = "Hello World"

substring = str1[1:5] # Result: 'ello'

String Methods

Python provides a rich set of string methods for various operations:

.upper(): Converts all characters to uppercase.

str1 = "hello"
upper_str = str1.upper() # Result: 'HELLO'

.lower(): Converts all characters to lowercase.

str1 = "HELLO"

lower_str = str1.lower() # Result: 'hello'

.title(): Capitalizes the first letter of each word.

str1 = "hello world"

title_str = str1.title() # Result: 'Hello World'

.strip(): Removes leading and trailing whitespace.

str1 = " hello "

stripped_str = str1.strip() # Result: 'hello'

Example:
Tuple

a tuple is an ordered, immutable collection of items. Tuples are used to group related pieces of
data together, and their immutability means that once a tuple is created, its contents cannot be
modified.

Key Characteristics of Tuples

1. Ordered: Tuples maintain the order of elements as they are defined. This means you can
access elements by their position (index).
2. Immutable: Once a tuple is created, you cannot change its elements, add new elements,
or remove existing elements. This immutability makes tuples useful for storing fixed
collections of items.
3. Heterogeneous: A tuple can contain elements of different data types (e.g., integers,
strings, lists).
4. Indexable: You can access elements using zero-based indexing.
5. Hashable: Tuples can be used as keys in dictionaries if all their elements are hashable.
This is because tuples are immutable.

Creating Tuples

• Basic Tuple: A tuple is created by placing elements inside parentheses (), separated by
commas.

my_tuple = (1, 2, 3)

• Single Element Tuple: To create a tuple with a single element, include a trailing comma.

single_element_tuple = (5,)

• Empty Tuple: An empty tuple is created with empty parentheses.

empty_tuple = ()

• Nested Tuples: Tuples can contain other tuples.

nested_tuple = (1, (2, 3), 4)

Accessing Elements

• Indexing: Access elements by their index.

my_tuple = (1, 2, 3)

first_element = my_tuple[0] # Result: 1


• Slicing: Extract a part of the tuple.

my_tuple = (1, 2, 3, 4, 5)

slice = my_tuple[1:4] # Result: (2, 3, 4)

Tuple Operations

• Concatenation: Combine two tuples into one.

tuple1 = (1, 2)

tuple2 = (3, 4)

combined = tuple1 + tuple2 # Result: (1, 2, 3, 4)

• Repetition: Repeat the tuple a specified number of times.

my_tuple = (1, 2)

repeated = my_tuple * 3 # Result: (1, 2, 1, 2, 1, 2)

Example:
List

a list is an ordered, mutable collection of items that can be of different data types. Lists are one
of the most versatile and commonly used data structures in Python due to their flexibility and the
wide range of operations and methods they support.

Key Characteristics of Lists

• Ordered: Lists maintain the order of elements as they are defined. This means that
elements can be accessed by their index.
• Mutable: Lists can be modified after creation. You can add, remove, or change elements.
• Heterogeneous: A list can contain elements of different data types, including other lists.
• Indexable: You can access elements using zero-based indexing.

Creating Lists

• Basic List: Created using square brackets [] with elements separated by commas.

my_list = [1, 2, 3, 4, 5]

• Empty List: An empty list is created with empty square brackets.

empty_list = []

• Nested Lists: Lists can contain other lists.

nested_list = [1, [2, 3], 4]

Accessing Elements

• Indexing: Access elements by their index.

my_list = [10, 20, 30]

first_element = my_list[0] # Result: 10

• Slicing: Extract a portion of the list.

my_list = [10, 20, 30, 40, 50]


sub_list = my_list[1:4] # Result: [20, 30, 40]

List Operations

• Concatenation: Combine two lists.

list1 = [1, 2]

list2 = [3, 4]

combined = list1 + list2 # Result: [1, 2, 3, 4]

• Repetition: Repeat the list a specified number of times.

my_list = [1, 2]

repeated = my_list * 3 # Result: [1, 2, 1, 2, 1, 2]

List Methods

Python provides a range of built-in methods for manipulating lists:

• .append(item): Adds an item to the end of the list.

my_list = [1, 2, 3]

my_list.append(4) # Result: [1, 2, 3, 4]

• .extend(iterable): Adds all elements of an iterable (like another list) to the end of the list

my_list = [1, 2]

my_list.extend([3, 4]) # Result: [1, 2, 3, 4]

• .insert(index, item): Inserts an item at a specified index.

my_list = [1, 2, 4]

my_list.insert(2, 3) # Result: [1, 2, 3, 4]


• .remove(item): Removes the first occurrence of an item.

my_list = [1, 2, 3, 2]

my_list.remove(2) # Result: [1, 3, 2]

• .pop(index): Removes and returns the item at the specified index. If no index is
provided, it removes and returns the last item.

my_list = [1, 2, 3]

last_item = my_list.pop() # Result: 3, list: [1, 2]

• .clear(): Removes all items from the list.

my_list = [1, 2, 3]

my_list.clear() # Result: []

• .index(item, start, end): Returns the index of the first occurrence of the item between
start and end. Raises a ValueError if the item is not found.

my_list = [1, 2, 3]

index = my_list.index(2) # Result: 1

• .count(item): Returns the number of occurrences of the item in the list.

my_list = [1, 2, 2, 3]

count = my_list.count(2) # Result: 2

• .sort(key=None, reverse=False): Sorts the list in ascending order by default. You can
specify a key function for custom sorting and reverse=True to sort in descending order.

my_list = [3, 1, 2]

my_list.sort() # Result: [1, 2, 3]

• .reverse(): Reverses the order of the elements in the list.

my_list = [1, 2, 3]

my_list.reverse() # Result: [3, 2, 1]

Example:
Set

a set is an unordered collection of unique elements. Sets are useful when you want to store items
that must not repeat, and they allow operations like union, intersection, and difference, which are
common in mathematical sets.

Key Characteristics:

Unordered: The items in a set have no defined order.

Unique Items: Duplicate values are automatically removed.


Creating a Set:

You can create a set using curly braces {} or the set() constructor.

# Example 1: Creating a set with curly braces

my_set = {1, 2, 3, 4}

# Example 2: Creating a set using the set() function

my_set2 = set([5, 6, 7])

Common Operations on Sets:

• Adding elements: Use the add() method to add elements to a set.

my_set.add(5)

• Removing elements: Use the remove() method to remove a specific item (will raise an
error if the item is not present) or discard() (won't raise an error if the item is not
present).

my_set.remove(3)

my_set.discard(10) # No error even if 10 is not in the set

• Union: Combines two sets and returns a new set with unique elements from both.

set1 = {1, 2, 3}

set2 = {3, 4, 5}

union_set = set1.union(set2) # Output: {1, 2, 3, 4, 5}


• Intersection: Returns elements that are present in both sets.

intersection_set = set1.intersection(set2) # Output: {3}

• Difference: Returns elements that are only in the first set and not in the second.

difference_set = set1.difference(set2) # Output: {1, 2}

• Membership Test: You can check if an item is present in a set using the in keyword.

if 2 in my_set:

print("2 is in the set")

Example:
Dictionary

a dictionary is a collection of key-value pairs. Each key in a dictionary is unique, and it is


associated with a value. Dictionaries are often used to store data in a way that is easy to search
and modify based on unique keys.

Key Characteristics:

• Unordered: Before Python 3.7, dictionaries were unordered. From Python 3.7+, they
maintain the insertion order.
• Unique Keys: Each key must be unique, but the values can be duplicated.
• Mutable: You can modify, add, or remove elements from a dictionary.

Creating a Dictionary:

You can create a dictionary using curly braces {} or the dict() constructor.

# Example 1: Creating a dictionary using curly braces

my_dict = {

'name': 'Alice',

'age': 25,

'city': 'New York'

# Example 2: Creating a dictionary using the dict() constructor

my_dict2 = dict(name='Bob', age=30, city='Los Angeles')

Common Operations on Dictionaries:

• Accessing Values: You can access a value by using its key.

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


You can also use the get() method, which returns None (or a default value) if t he key is
not found.

print(my_dict.get('age')) # Output: 25

print(my_dict.get('job', 'Not Found')) # Output: Not Found

• Adding/Updating Elements: You can add or update elements by assigning a value to


a key.

my_dict['age'] = 26 # Update existing key

my_dict['job'] = 'Engineer' # Add new key-value pair

• Removing Elements: You can remove elements using the del keyword, the pop()
method, or popitem().

del my_dict['city'] # Remove key 'city'

job = my_dict.pop('job') # Remove and return value of 'job'

last_item = my_dict.popitem() # Remove and return the last inserted item

• Looping through a Dictionary: You can loop through keys, values, or both key-value
pairs.

# Loop through keys

for key in my_dict:

print(key)

# Loop through values

for value in my_dict.values():

print(value)
# Loop through key-value pairs

for key, value in my_dict.items():

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

• Checking Key Existence: You can check if a key exists in a dictionary using the in
keyword.

if 'name' in my_dict:

print("Name exists in the dictionary")

• Dictionary Length: Use len() to find out how many key-value pairs are in the
dictionary.

print(len(my_dict)) # Output: 2 (if 'city' was removed earlier)

Dictionary Methods:

• keys(): Returns a list of all the keys.


• values(): Returns a list of all the values.
• items(): Returns a list of key-value pairs.
• clear(): Removes all items from the dictionary.
Example:

File input/output

file input/output (I/O) allows you to interact with files to read from or write to them. You can
perform various operations on files like reading data, writing data, appending data, and more.
Python provides built-in functions like open(), read(), write(), and close() for file handling.

File Handling Basics

• Opening a File: Use the open() function to open a file. It takes two arguments:

File Name: The name (and path) of the file.

Mode: The mode in which the file is opened (read, write, etc.).

file = open('filename.txt', 'mode')


Common modes:

'r': Read (default mode)

'w': Write (overwrites the file if it exists)

'a': Append (adds data to the end of the file)

'b': Binary mode (used for reading/writing binary files like images)

'+': Read and write

• Reading from a File: You can read a file using different methods:

read(): Reads the entire file content.

readline(): Reads one line at a time.

readlines(): Reads all lines and returns them as a list.

# Example: Reading the entire file content

with open('example.txt', 'r') as file:

content = file.read()

print(content)

# Example: Reading line by line

with open('example.txt', 'r') as file:

for line in file:

print(line.strip())

• Writing to a File: You can write data to a file using write() or writelines() methods.

write(): Writes a string to the file.

writelines(): Writes a list of strings to the file.


# Example: Writing to a file

with open('output.txt', 'w') as file:

file.write("Hello, World!\n")

file.write("Python file handling is simple.")

• Appending to a File: You can add data to the end of an existing file using append
mode 'a'.

# Example: Appending to a file

with open('output.txt', 'a') as file:

file.write("\nThis line is added to the existing file.")

• Closing a File: After completing file operations, it is a good practice to close the file
using close(). However, using the with statement automatically closes the file after the
block is executed.

file.close()

Example:

Here is a complete example of reading from one file and writing the contents to another file.

# Reading from one file and writing to another

with open('input.txt', 'r') as input_file:

content = input_file.read()

with open('output.txt', 'w') as output_file:

output_file.write(content)
Lab Practice Question 1: Python Identifiers, Keywords, and Indentation

Question: Write a Python program to calculate the square of a number entered by the user.
Follow proper naming conventions for variables, and ensure correct indentation.

Solution:

# Program to calculate the square of a number

def calculate_square(number): # Identifier for the function

result = number ** 2 # Identifier for the variable

return result

# Taking input from the user

num = int(input("Enter a number: ")) # 'int' and 'input' are keywords

square = calculate_square(num)

# Displaying the result

print(f"The square of {num} is {square}.")

Lab Practice Question 2: Operators and Membership Operator

Question: Write a Python program to check if a number is present in a given list using
membership operators. Also, use arithmetic and comparison operators to find the maximum
number in the list.

Solution:

# Program to check for membership and find the maximum number

def check_number_in_list(number, lst):

return number in lst # Membership operator


# List of numbers

numbers = [3, 8, 1, 9, 6]

# Taking input from the user

num = int(input("Enter a number to check: "))

# Checking membership

if check_number_in_list(num, numbers):

print(f"{num} is in the list.")

else:

print(f"{num} is not in the list.")

# Finding the maximum number using comparison operators

max_number = numbers[0]

for n in numbers:

if n > max_number:

max_number = n

print(f"The maximum number in the list is {max_number}.")

Lab Practice Question 3: String Manipulation

Question: Write a Python program to reverse a string entered by the user and check whether the
string is a palindrome (reads the same forwards and backward).

Solution:
# Program to reverse a string and check for palindrome

def reverse_string(s):

return s[::-1] # Slicing to reverse the string

def is_palindrome(s):

return s == reverse_string(s) # Checking if original is equal to reverse

# Taking input from the user

user_string = input("Enter a string: ")

# Reversing and checking for palindrome

reversed_string = reverse_string(user_string)

if is_palindrome(user_string):

print(f"{user_string} is a palindrome.")

else:

print(f"{user_string} is not a palindrome.")

print(f"Reversed String: {reversed_string}")

Lab Practice Question 4: Tuples

Question: Write a Python program to take five numbers as input from the user, store them in a
tuple, and calculate the sum and average of the numbers.

Solution:
# Program to calculate sum and average of numbers in a tuple

def calculate_sum_and_average(numbers):

total = sum(numbers) # Summing up the numbers

avg = total / len(numbers) # Calculating the average

return total, avg

# Taking input from the user

numbers = tuple(int(input(f"Enter number {i+1}: ")) for i in range(5))

# Calculating sum and average

total, average = calculate_sum_and_average(numbers)

print(f"The sum of the numbers is {total} and the average is {average}.")

Lab Practice Question 5: Lists

Question: Write a Python program to perform the following operations on a list:

Append a number to the list.

Insert a number at a specific position.

Remove a number from the list.

Sort the list in ascending order.

Solution:
# Program to perform operations on a list

def list_operations(lst):

lst.append(12) # Append 12

lst.insert(2, 15) # Insert 15 at index 2

lst.remove(5) # Remove 5 from the list

lst.sort() # Sort the list in ascending order

return lst

# Initial list

my_list = [5, 3, 9, 1, 7]

# Performing operations

updated_list = list_operations(my_list)

print(f"Updated List: {updated_list}")

Lab Practice Question 6: Sets

Question: Write a Python program to create two sets of integers and perform the following
operations:

Find the union of the two sets.

Find the intersection of the two sets.

Find the difference between the two sets.


Solution:

# Program to perform set operations

def set_operations(set1, set2):

union_set = set1.union(set2)

intersection_set = set1.intersection(set2)

difference_set = set1.difference(set2)

return union_set, intersection_set, difference_set

# Creating two sets

set1 = {1, 2, 3, 4, 5}

set2 = {4, 5, 6, 7, 8}

# Performing operations

union, intersection, difference = set_operations(set1, set2)

print(f"Union: {union}")

print(f"Intersection: {intersection}")

print(f"Difference: {difference}")

Lab Practice Question 7: Dictionaries

Question: Write a Python program to create a dictionary with three students' names and their
marks in three subjects. Then, calculate the total marks for each student and display them.
Solution:

# Program to calculate total marks for students

def calculate_total_marks(students):

totals = {}

for name, marks in students.items():

total = sum(marks)

totals[name] = total

return totals

# Dictionary of students with their marks

students = {

'Alice': [85, 90, 88],

'Bob': [78, 82, 89],

'Charlie': [92, 88, 95]

# Calculating total marks

total_marks = calculate_total_marks(students)

# Displaying total marks

for student, total in total_marks.items():

print(f"{student}: {total} marks")

Lab Practice Question 8: File Input/Output


Question: Write a Python program to read a file containing a list of numbers (one per line),
calculate their sum, and write the result to another file.

Solution:

# Program to read numbers from a file, calculate sum, and write to another file

def read_numbers_and_calculate_sum(input_file):

with open(input_file, 'r') as file:

numbers = [int(line.strip()) for line in file]

return sum(numbers)

def write_sum_to_file(output_file, total):

with open(output_file, 'w') as file:

file.write(f"The sum of numbers is: {total}\n")

# Input and Output file names

input_file = 'numbers.txt'

output_file = 'sum_result.txt'

# Calculating sum

total_sum = read_numbers_and_calculate_sum(input_file)

# Writing the result to the output file

write_sum_to_file(output_file, total_sum)

print(f"Sum of numbers written to {output_file}.")

You might also like