Unit 1 Introduction
Unit 1 Introduction
INTRODUCTION
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.
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.
6. High-Level Language
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.
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.
Python is also an Integrated language because we can easily integrate Python with other
languages like C, C++, etc.
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.
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.
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.
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
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.
• 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
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 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.
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:
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
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:
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.
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.
def greet():
print("Hello, World!")
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
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
Ex:
a = 10
b=3
print(a + b) # Output: 13
Comparison operators compare two values and return a boolean ( True or False).
Ex:
a = 10
b=5
3. Assignment Operators
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
4. Logical Operators
Logical operators are used to combine conditional statements and return True or False.
Ex:
a = True
b = False
5. Bitwise Operators
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]
7. Identity Operators
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
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:
• 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.
EX:
single_quote_str = 'Hello'
double_quote_str = "Hello"
triple_quote_str = """Hello
World”””
Basic Operations
str1 = "Hello"
str2 = "World"
str1 = "Hello"
str1 = "Hello"
String Methods
str1 = "hello"
upper_str = str1.upper() # Result: 'HELLO'
str1 = "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.
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 = ()
Accessing Elements
my_tuple = (1, 2, 3)
my_tuple = (1, 2, 3, 4, 5)
Tuple Operations
tuple1 = (1, 2)
tuple2 = (3, 4)
my_tuple = (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.
• 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 = []
Accessing Elements
List Operations
list1 = [1, 2]
list2 = [3, 4]
my_list = [1, 2]
List Methods
my_list = [1, 2, 3]
• .extend(iterable): Adds all elements of an iterable (like another list) to the end of the list
my_list = [1, 2]
my_list = [1, 2, 4]
my_list = [1, 2, 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]
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]
my_list = [1, 2, 2, 3]
• .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 = [1, 2, 3]
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:
You can create a set using curly braces {} or the set() constructor.
my_set = {1, 2, 3, 4}
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)
• Union: Combines two sets and returns a new set with unique elements from both.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
• Difference: Returns elements that are only in the first set and not in the second.
• Membership Test: You can check if an item is present in a set using the in keyword.
if 2 in my_set:
Example:
Dictionary
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.
my_dict = {
'name': 'Alice',
'age': 25,
print(my_dict.get('age')) # Output: 25
• Removing Elements: You can remove elements using the del keyword, the pop()
method, or popitem().
• Looping through a Dictionary: You can loop through keys, values, or both key-value
pairs.
print(key)
print(value)
# Loop through key-value pairs
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:
• Dictionary Length: Use len() to find out how many key-value pairs are in the
dictionary.
Dictionary Methods:
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.
• Opening a File: Use the open() function to open a file. It takes two arguments:
Mode: The mode in which the file is opened (read, write, etc.).
'b': Binary mode (used for reading/writing binary files like images)
• Reading from a File: You can read a file using different methods:
content = file.read()
print(content)
print(line.strip())
• Writing to a File: You can write data to a file using write() or writelines() methods.
file.write("Hello, World!\n")
• Appending to a File: You can add data to the end of an existing file using append
mode 'a'.
• 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.
content = input_file.read()
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:
return result
square = calculate_square(num)
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:
numbers = [3, 8, 1, 9, 6]
# Checking membership
if check_number_in_list(num, numbers):
else:
max_number = numbers[0]
for n in numbers:
if n > max_number:
max_number = n
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):
def is_palindrome(s):
reversed_string = reverse_string(user_string)
if is_palindrome(user_string):
print(f"{user_string} is a palindrome.")
else:
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):
Solution:
# Program to perform operations on a list
def list_operations(lst):
lst.append(12) # Append 12
return lst
# Initial list
my_list = [5, 3, 9, 1, 7]
# Performing operations
updated_list = list_operations(my_list)
Question: Write a Python program to create two sets of integers and perform the following
operations:
union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Performing operations
print(f"Union: {union}")
print(f"Intersection: {intersection}")
print(f"Difference: {difference}")
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:
def calculate_total_marks(students):
totals = {}
total = sum(marks)
totals[name] = total
return totals
students = {
total_marks = calculate_total_marks(students)
Solution:
# Program to read numbers from a file, calculate sum, and write to another file
def read_numbers_and_calculate_sum(input_file):
return sum(numbers)
input_file = 'numbers.txt'
output_file = 'sum_result.txt'
# Calculating sum
total_sum = read_numbers_and_calculate_sum(input_file)
write_sum_to_file(output_file, total_sum)