0% found this document useful (0 votes)
0 views34 pages

Python's Practical File

This document is a practical file for a Programming in Python course, detailing various topics such as data types, control structures, and operators. It includes an index of practical exercises along with an introduction to Python, its features, applications, advantages, and disadvantages. The document serves as a comprehensive guide for students learning Python programming.

Uploaded by

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

Python's Practical File

This document is a practical file for a Programming in Python course, detailing various topics such as data types, control structures, and operators. It includes an index of practical exercises along with an introduction to Python, its features, applications, advantages, and disadvantages. The document serves as a comprehensive guide for students learning Python programming.

Uploaded by

OP ABHIJEET
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Programming in Python

Practical File
Programming in Python

Submitted to: Submitted by:


Dr. Rajdeep Kaur Abhijeet
SCS Department GU-2024-8346
GNA UNIVERSITY BBA 2 (H)

SCS DEPARTMENT
GNA UNIVERSITY

GU-2024-8346
Programming in Python

Index
Sr no. Name of Practical Date Page no.

1. Introduction to Python 10/01/25 1-3


2. Variables & Identifiers 20/01/25 4-5

3. Data Types 31/01/25 6-8


4. Strings 10/02/25 9-10

5. Lists & Tuples 28/02/25 11-14

6. Literals 18/03/25 15-17

7. Control Structure 8/04/25 18-20

8. Operators 11/04/25 21-24

9. Array 15/04/25 25-27

10. Function 21/04/25 28-30

11. File Handling - opening 25/04/25 31-32


file ready and write file

GU-2024-8346
Programming in Python

Introduction to Python
Python: A Versatile and Popular Programming Language
Python is a high-level, interpreted, general-purpose programming language.
Created by Guido van Rossum and first released in 1991, its design philosophy
emphasizes code readability with its notable use of significant indentation. The
name "Python" is a nod to the British comedy group Monty Python.

Key Features of Python:


 Easy to Learn and Use: Python has a simple and clear syntax, making it
beginner-friendly and quick to learn. Its readability enhances code
maintainability.

 Interpreted Language: Python code is executed line by line, which


simplifies debugging and allows for rapid development.

 Dynamically Typed: You don't need to declare the type of a variable


when you assign a value to it, providing flexibility in coding.

 High-Level Language: Python abstracts away many low-level details of


computer hardware, allowing developers to focus on problem-solving.

 Object-Oriented: Python supports object-oriented programming (OOP)


principles, enabling the creation of modular and reusable code. It also
supports other programming paradigms like structured and functional
programming.

Applications of Python:
Python's versatility has led to its widespread adoption in various fields:
 Web Development: Python is popular for backend and full-stack web
development, with powerful frameworks like Django and Flask.

GU-2024-8346 Page 1
Programming in Python

1. Data Science and Analysis: Python is a dominant language in data


science, offering libraries like Pandas, NumPy, and Matplotlib for data
manipulation, analysis, and visualization.

2. Machine Learning and Artificial Intelligence: Python is the go-to


language for AI and machine learning, with libraries such as TensorFlow,
Keras, and scikit-learn.

3. Software Development: Python is used to build a wide range of


applications, from desktop GUI applications (using libraries like Tkinter
and PyQt) to enterprise-level software.

4. Automation and Scripting: Python is excellent for automating tasks,


writing system scripts, and performing web scraping.

5. Game Development: Libraries like Pygame allow for the creation of


simple to complex games.

6. Scientific Computing: Python is widely used in scientific research for


simulations, modeling, and analysis.

7. Education: Python's beginner-friendly syntax makes it an ideal language


for teaching programming concepts.

Advantages:
 Easy to Learn: Python has a simple syntax and is relatively easy to learn,
making it a great language for beginners.

 Versatile: Python can be used for a wide range of applications, including


web development, data analysis, machine learning, automation, and more.

GU-2024-8346 Page 2
Programming in Python

 Large Community: Python has a large and active community, which


means there are many resources available for learning and
troubleshooting.

 Extensive Libraries: Python has a vast collection of libraries and


frameworks that make it easy to perform various tasks, such as data
analysis, web development, and more.

Disadvantages:
 Slow Performance: Python is an interpreted language, which means it
can be slower than compiled languages like C++ or Java.

 Limited Support for Parallel Processing: Python's Global Interpreter


Lock (GIL) can make it difficult to take full advantage of multi-core
processors.

 Memory Intensive: Python's dynamic typing and memory management


can lead to increased memory usage, which can be a problem for large-
scale applications.

 Security: Python's dynamic typing and lack of memory safety features


can make it vulnerable to certain types of attacks.

GU-2024-8346 Page 3
Programming in Python

Variables & Identifiers

 Variables
In Python, variables are names given to memory locations that store values.
Think of them as labeled containers where you can put data. These values can
be of different types, such as numbers, text, or more complex data structures. In
Python, you do not need to declare the type of variable explicitly — Python
automatically determines the type based on the value assigned.

Syntax:

Variable_name = value

Example:

GU-2024-8346 Page 4
Programming in Python

 Identifiers
In Python, an identifier is a name given to a variable, function, or other object.
Identifiers are used to identify and reference these objects in a program. They
are essentially the labels you use to refer to these entities.

Rules for Naming Identifiers:


1. An identifier can contain letters (A–Z, a–z), digits (0–9), and underscores (_).
2. It must not begin with a digit.
3. Python keywords cannot be used as identifiers (e.g., if, class, def, etc.).

Example:

GU-2024-8346 Page 5
Programming in Python

Data Types
In Python, every value has a data type. Data types define what kind of value a
variable can hold and what operations can be performed on it. Python is a
dynamically typed language, meaning you don’t have to declare the type of
variable explicitly.

 Numeric Types:
A) Integer: Represents whole numbers (positive, negative, or zero)
without any decimal point.

Syntax:

Variable_name = integer_value

Example:

GU-2024-8346 Page 6
Programming in Python

B) Floating-piont number: Represents real numbers with a decimal


point.

Syntax:

Variable_name = floating_point_value

Example:

C) Complex number: Represents numbers in the form of a + bj.


Syntax:

Variable_name = complex(real_part, imaginary_part)

Example:

 Boolean Type: Represents one of two possible truth values: True or


False. Boolean values are often the result of logical operations or
comparisons.
Syntax:
Variable_name = True
Or
Variable_name = False

GU-2024-8346 Page 7
Programming in Python

Example:

 Set Types: Represents an unordered collection of unique items. Sets are


mutable and do not allow duplicate elements.

Syntax:
Variable_name = {item1, item2, item3, …}

Example:

 Dictionary: In Python, these are unordered collections of data in a key-


value pair format. They are mutable, meaning you can change, add, or
remove items after the dictionary has been created.
Example:

GU-2024-8346 Page 8
Programming in Python

Strings
In Python, strings are used for representing textual data. A string is a sequence
of characters enclosed in either single quotes ('') or double quotes (“”). The
Python language provides various built-in methods and functionalities to work
with strings efficiently. Strings can include letters, numbers, symbols, and
whitespace characters (like spaces, tabs, and newlines).

1. Characteristics of Strings
 Sequence: Strings are ordered collections of characters, meaning the
position of each character matters.
 Immutable: In many popular languages like Python, Java, and
JavaScript, strings are immutable. This means that once a string is
created, its contents cannot be directly changed.
 Length: A string has a length, which is the number of characters it
contains (including spaces and other symbols).
 Iterable: You can iterate over the characters of a string using loops or
other iteration constructs.

2. Creating Strings

Strings can be created using:

Single quotes: 'Hello'

Double quotes: "Hello"

Triple quotes for multiline: '''Hello''' or """Hello"""

Programming in Python

3. Common String Operations:

GU-2024-8346 Page 9
Most programming languages provide a rich set of built-in functions and
methods for manipulating strings. Some common operations include:

 Concatenation: Combining two or more strings together to form a new


string. This is often done using the + operator or a dedicated concat()
method.

 Length: Determining the number of characters in a string (often using a


len() function or a .length property).

 Splitting: Dividing a string into a list of substrings based on a delimiter


(e.g., using split()).

Programming in Python

Lists & Tuples


GU-2024-8346 Page 10
In Python, lists and tuples are fundamental data structures used to store
collections of items. They are both ordered sequences, meaning the elements
within them maintain a specific order. However, they differ significantly in their
mutability, which dictates how they can be modified after creation.

 Lists: A list is a mutable, ordered sequence of items. This means you


can change its contents after it's created by adding, removing, or
modifying elements. Lists are incredibly versatile and are used
extensively in Python programming.

 Key Characteristics of Lists:

 Ordered: Elements in a list maintain the order in which they were


inserted.
 Mutable: You can modify the contents of a list after it's created (add,
remove, change elements).
 Allow Duplicate Elements: A list can contain multiple occurrences of
the same element.
 Heterogeneous Elements: Lists can store elements of different data
types (integers, floats, strings, booleans, even other lists or tuples) within
the same list.
 Dynamic Size: The size of a list can grow or shrink as you add or remove
elements.

Syntax:

List_name = [element1, element2, element3, element4,…..]

Programming in Python

Important Methods:
GU-2024-8346 Page 11
 append(item) – Add an item to the end.

 insert(index, item) – Add an item at a specific position.

 remove(item) – Remove an item by value.

 pop(index) – Remove an item by index.

 sort() – Sorts list in ascending order.

 reverse() – Reverses the list order.

 extend() – Add multiple items.

Examples:

GU-2024-8346 Page 12
Programming in Python

 Tuples: A tuple is also a built-in data type that can store multiple items
in a single variable. Unlike lists, tuples are immutable, which means once
a tuple is created, its items cannot be changed.

 Key Characteristics of Lists:

 Ordered: Elements in a tuple maintain the order in which they were


defined.
 Immutable: You cannot modify the contents of a tuple after it's created.
 Allow Duplicate Elements: A tuple can contain multiple occurrences of
the same element.
 Heterogeneous Elements: Tuples can store elements of different data
types.
 Fixed Size: The size of a tuple is fixed at the time of creation.

Syntax:

Tuple_name = (element1, element2, element3, element4,…)

Important Notes:
 Tuples are faster than lists because of their immutability.
 Tuples can be used as keys in dictionaries, while lists cannot.
 Single-element tuples need a comma.

Examples:

GU-2024-8346 Page 13
Programming in Python

GU-2024-8346 Page 14
Programming in Python

Literals
In Python, literals are raw values that are fixed and directly written in the source
code. They represent constant values of built-in data types. When you use a
literal in your code, Python knows exactly what value you are referring to.

Types of Literals in Python:

1) Numeric Literals: Used to represent numbers.

Integer Literals: Whole numbers (positive or negative)


Float Literals: Decimal numbers
Complex Literals: Numbers with real and imaginary parts

Examples:

GU-2024-8346 Page 15
Programming in Python

2) String Literals: String literals represent sequences of characters. They are


enclosed in single quotes ('), double quotes ("), or triple quotes (''' or """).

Examples:

3) Boolean Literals: Boolean literals represent truth values. There are only two
boolean literals in Python:
* True: Represents the truth value true (often numerically equivalent to 1).
* False: Represents the truth value false (often numerically equivalent to 0).

Examples:

4) Special Literals: None is a special literal that represents the absence of a


value or a null value. It is often used to indicate that a variable has not been
assigned a value or that a function does not return anything explicitly.

Examples:

GU-2024-8346 Page 16
Programming in Python

5) Collection Literals: Python provides literals for its built-in collection data
types:
a) Lists
b) Tuples
c) Dictionary
d) Sets

Examples:

GU-2024-8346 Page 17
Programming in Python

Control Structure
In Python, Control structures allow you to manage the flow of your program's
execution based on conditions and [Link]'re the backbone of any
program. Let's dive into them in detail. There are three main types of control
structures in Python:

1) Sequential Control Structure:


The default structure where code executes line by line, from top to bottom, in
the order it's written.
Example:

2) if statement:
Executes a block of code if a condition is true.
Example:

3) if-else statement:
Executes one block of code if the condition is true and another block if it's false.
Example:

GU-2024-8346 Page 18
Programming in Python

4) if-elif-else statement:
It checks multiple conditions in sequence. If one condition is true, its
corresponding block is executed, and the rest are skipped. If none are true, the
else block (if present) is executed.
Example:

5) Looping Structures: for and while:


Loops allow you to execute a block of code repeatedly. Python offers two main
types of loops: for and while.

5.1) For Loop: The for loop in Python is primarily used to iterate over a
sequence (like a list, tuple, string, or range) or other iterable objects.
Example:

GU-2024-8346 Page 19
Programming in Python

5.2) While Loop: The while loop executes a block of code as long as a
specified condition is True.
Example:

GU-2024-8346 Page 20
Programming in Python

Operators
In Python, operators are special symbols or keywords used to perform
operations on variables and values. Python has a rich set of built-in operators
categorized based on their functionality.

1) Arithmetic Operators: Python Arithmetic operators are used to perform


basic mathematical operations like addition, subtraction,
multiplication and division.
Example:

GU-2024-8346 Page 21
Programming in Python

2) Relational Operators: These operators compare two values and return a


Boolean result (True and False).
Example:

3) Logical Operators: In Python, Logical operators perform AND , OR and


NOT operations. It is used to combine conditional statements.
Example:

GU-2024-8346 Page 22
Programming in Python

4) Bitwise Operators: In Python, Bitwise operators act on bits and perform bit-
by-bit operations. These are used to operate on binary numbers. Bitwise
Operators in Python are as follows:
Bitwise AND
Bitwise OR
Bitwise NOT
Bitwise XOR
Example:

GU-2024-8346 Page 23
Programming in Python

5) Assignment Operators: In Python, Assignment operators are used to assign


values to the variables. This operator is used to assign the value of the right side
of the expression to the left side operand.
Example:

GU-2024-8346 Page 24
Programming in Python

Array
In Python, an array is used to store multiple values or elements of the same
datatype in a single variable. The extend() function is simply used to attach an
item from iterable to the end of the array. In simpler terms, this method is used
to add an array of values to the end of a given or existing array.

Key characteristics of the array module:


 Homogeneous data type: All elements in an array must be of the same
type, as specified by the typecode.
 Memory efficiency: For large numerical datasets of the same type, array
objects can be more memory-efficient than standard Python lists because
the type of each element is fixed.
 Limited functionality: The array module offers fewer built-in methods
compared to Python lists or NumPy arrays. It's primarily designed for
basic storage and manipulation of numerical sequences.

1) Using Lists as Arrays (Most Common):


Python doesn't have built-in support for arrays like other languages, but lists
serve a similar purpose.

Syntax:

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

Example:

GU-2024-8346 Page 25
Programming in Python

2. Using array module:


If you only need to store numeric data, the array module is more efficient.

Syntax:

import array
arr = [Link](typecode, [elements])

Typecodes:
Specifies the data type of the elements in the array. Some common typecodes
include:

GU-2024-8346 Page 26
Programming in Python

o 'b': signed char


o 'B': unsigned char
o 'i': signed int
o 'I': unsigned int
o 'f': float
o 'd': double

Here are a few examples of creating arrays with different data types:
Programming in Python

Function
GU-2024-8346 Page 27
In Python, a function is a block of code that can be executed multiple times
from different parts of a program. Functions are used to organize code, reduce
repetition, and make programs more modular and reusable.

Syntax:

def function_name(parameters):
# function body
# optional return statement

Explanation:
 def: Keyword to define a function.
 function_name: The name you give to the function.
 parameters: Inputs to the function (can be optional).
 Indicates: the start of the function body.
 return: (Optional) Used to send back a result from the function.

Types of Functions in Python:


 Built-in Functions: Python has many built-in functions, such as len(),
range(), and print().
 User-defined Functions: You can define your own functions using the
def keyword.

1) Function Without Parameters:


def greet():
print("Hello! Welcome to Python.")
# Calling the function
Programming in Python

greet()
2) Function With Parameters:
GU-2024-8346
def greeta(): Page 28
print("Hello! Welcome to Python.")

# Calling the function


greet()

3) Function With Multiple Parameters:


def greet(name):
print(f"Hello, {name}! Welcome to Python.")

greet("Aman")

4) Function With Return Value:


def greet():
print("Hello! Welcome to Python.")

# Calling the function


greet()
# the sum is 8

4) Function With Default Parameter Value:


def greet_with_title(name, title="Mr."):
print(f"Hello, {title} {name}!")

greet_with_title("Bob") # Output: Hello, Mr. Bob!


Programming in Python

greet_with_title("Eve", "Ms.") # Output: Hello, Ms. Eve!


5) Function with keyword arguments:
def describe_person(**kwargs):
GU-2024-8346 Page 29
for key, value in [Link]():
print(f"{key}: {value}")

describe_person(name="Charlie", age=30, city="New York")


# Output:
# name: Charlie
# age: 30
# city: New York
Programming in Python

File Handling - Opening file and Writing file


GU-2024-8346 Page 30

 Opening file
The open() function is used to open a file in Python. It takes two primary
arguments: the file name and the mode.
Example:

o [Link]: The name of the file to be opened.


o mode: A string specifying the mode in which the file is opened. Common
modes include:
 'r': Read mode (default). Opens the file for reading.
 'w': Write mode. Opens the file for writing. If the file exists, it will be
overwritten. If it doesn't, a new file will be created.
 'a': Append mode. Opens the file for appending. If the file exists, new
data will be added to the end. If it doesn't, a new file will be created.
 'x': Exclusive creation mode. Creates a new file, but raises an error if the
file already exists.
 'b': Binary mode. Used for binary files (e.g., images, audio).
 't': Text mode (default). Used for text files.
 '+': Update mode (read and write).
Programming in Python

GU-2024-8346 Page 31

 Writing file
The write() method is used to write to a file.

Methods to Write:

 [Link]("text") – Writes a string to the file.

 [Link](list_of_strings) – Writes a list of strings.

Example:

Using With:

GU-2024-8346 Page 32

You might also like