Py Unit 1 - Introduction To Python Programming
Py Unit 1 - Introduction To Python Programming
Syllabus:
Introduction: Installing Python; basic syntax, interactive shell, editing, saving, and running
a script; data types; variables, assignments; numerical types; arithmetic operators and
expressions; Loops and selection statements, Control statements.
String manipulations: subscript operator, indexing, slicing a string; text files:
reading/writing text and numbers from/to a file; creating and reading a formatted file.
Features of Python
● Python is simple and easy to understand.
● It is Interpreted and platform-independent which makes debugging very easy.
● Python is dynamically typed, so no need to declare a data type explicitly.
● Python is an open-source programming language.
● Python provides very big library support. Some of the popular libraries include NumPy,
Tensorflow, Selenium, OpenCV, etc.
● It is possible to integrate other programming languages within python.
Interpreted
● There are no separate compilation and execution steps like C and C++.
● Directly run the program from the source code.
● Internally, Python converts the source code into an intermediate form called bytecodes
which is then translated into native language of a specific computer to run it.
● Python is often considered a scripting language because of its interpreted nature.
Platform Independent
● Python programs can be developed and executed on multiple operating system platforms.
● Python can be used on Linux, Windows, Macintosh, Solaris and many more.
High-level Language
● In Python, no need to take care about low-level details such as managing the memory used
by the program.
Simple
● Closer to English language;Easy to Learn
2
NotesNeo
● More emphasis on the solution to the problem rather than the syntax
Embeddable
● Python can be used within C/C++ program to give scripting capabilities for the program’s
users.
Robust
● Exceptional handling features
● Memory management techniques in built
Installing Python
● You can download Python from the official website ([Link]
and follow the installation instructions for your operating system.
Basic Syntax
● The basic syntax of Python is straightforward and designed to be easy to read and write.
● Here are some key points:
○ Statements are terminated by newline \n character.
○ Python uses indentation (whitespace or tab at the beginning of a line) to indicate the
block of code instead of braces { } or keywords like begin and end.
○ Typically, four spaces are used for each level of indentation.
○ Correct indentation is crucial for code structure.
○ Comments start with the # symbol and continue to the end of the line.
● Example:
print("Hello, World!") # This is a comment
Interactive Shell
● Interactive shell is a user interface that allows user to interact with a programming language
or a software environment in real-time.
● The interactive shell, often referred to as the Python REPL (Read-Evaluate-Print Loop),
allows you to execute Python code line by line interactively.
3
NotesNeo
● You can access it by simply typing python or python3 in your terminal. It provides a way to
experiment with code, test small snippets, and get immediate feedback.
● The command to clear the Python shell depends on the environment. On most systems,
you can use clear (Linux/Mac) or cls (Windows).
● Example:
>>> print("Hello, interactive shell!")
Hello, interactive shell!
import sys
In this example, arg1, arg2, and arg3 are command-line arguments. When the script is
executed, it prints the script name and displays the provided command-line arguments.
Keep in mind that the first element in [Link] is always the script name, and subsequent
elements are the command-line arguments. The script checks if there are additional
arguments and then processes and displays them accordingly.
4
NotesNeo
python [Link]
This executes the Python script, and any output or errors will be displayed in the terminal.
Data Types
● Data types define the nature of data that can be stored and manipulated in Python.
● Python is dynamically typed, meaning you don't need to declare a data type explicitly; it's
determined at runtime.
○ int: Represents integers (whole numbers), e.g., 5, -10.
○ float: Represents floating-point numbers (decimal numbers), e.g., 3.14, -0.5.
○ str: Represents strings, which are sequences of characters enclosed in single (') or
double (") quotes, e.g., "Hello, Python!".
○ list: Represents ordered collections of items, e.g., [1, 2, 3], ["apple", "banana",
"cherry"].
○ tuple: Represents immutable ordered collections, similar to lists but cannot be
modified, e.g., (1, 2, 3).
○ dict: Represents dictionaries, which store key-value pairs, e.g., {"name": "Deep",
"age": 20}.
○ bool: Represents boolean values True and False.
string = "hello"
# string[0] = 'H' # Error since strings are immutable
Integer (int)
● Definition: The int data type represents integers, which are whole numbers. Integers can be
positive, negative, or zero.
● Syntax: Assigning an integer value to a variable.
variable_name = integer_value
5
NotesNeo
● Example:
age = 25
count = -10
population = 7000000000 # 7 billion
String (str)
● Definition: The str data type represents strings, which are sequences of characters. Strings
are enclosed in single (') or double (") quotes.
● Syntax: Assigning a string value to a variable.
variable_name = "string_value"
● Example:
name = "Deepak"
greeting = 'Hello, World!'
List
● Definition: Lists are a data type used to store ordered collections of items. Lists can contain
elements of different data types, and they are mutable, meaning you can modify their
contents.
● Syntax: Creating a list by enclosing items in square brackets [].
variable_name = [item1, item2, item3, ...]
● Example:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "apple", 3.14, True]
Tuple
● Definition: Tuples are similar to lists but are immutable, meaning their contents cannot be
changed after creation. Tuples are defined using parentheses ().
● Syntax: Creating a tuple by enclosing items in parentheses.
variable_name = (item1, item2, item3, ...)
● Example:
dimensions = (10, 20, 30)
coordinates = (5.5, 7.0)
Dictionary (dict)
● Definition: Dictionaries are used to store key-value pairs. Each key in a dictionary is unique,
and you can access values using their keys.
● Syntax: Creating a dictionary by using curly braces {} and specifying key-value pairs.
variable_name = {"key1": value1, "key2": value2, ...}
6
NotesNeo
● Example:
person = {"name": "Alice", "age": 30, "city": "New York"}
student_grades = {"Math": 90, "Science": 85, "History": 88}
Boolean (bool)
● Definition: The bool data type represents boolean values, which can be either True or
False. Booleans are often used in conditional statements and logical operations.
● Syntax: Assigning a boolean value to a variable.
variable_name = True # or False
● Example:
is_adult = True
has_permission = False
Numerical Types
● Python provides two primary numerical types:
○ int (Integer): Represents integers (positive or negative whole numbers).
○ float (Floating-point): Represents floating-point numbers (real numbers with a
decimal point).
7
NotesNeo
● Variables: Containers for storing data.
Identifiers:
Identifiers are names given to entities in Python, such as variables, functions, classes, modules,
etc. They help in uniquely identifying these entities in the code. Here are some rules for identifiers:
● Must begin with a letter (a-z, A-Z) or an underscore (_).
● The subsequent characters can be letters, numbers(0-9), or underscores.
● Case-sensitive (e.g., myVar and MyVar are different identifiers).
● Cannot be a keyword (reserved word).
Examples of identifiers:
variable_name = 42
function_name = "hello"
_class_name = "MyClass"
Keywords:
Keywords are reserved words in Python that have special meanings and cannot be used as
identifiers. They form the core of the language's syntax and structure.
Examples of keywords:
if, else, while, for, break, continue, return, def, class, True, False, None, and,
or, not, import, from, as, with, try, except, finally, global, nonlocal, lambda
x = 10 # Global variable
def func():
y = 5 # Local variable
print(x, y) # Accessible: x (global), y (local) Output: 10 5
func()
# print(y) # Error: y is not defined outside the function
8
NotesNeo
1. Arithmetic Operators:
● Arithmetic Operators are used to perform mathematical operations on numerical data.
● Arithmetic Expressions are combinations of values and arithmetic operators that evaluate
to a single value. These expressions are commonly used in calculations and are essential
in programming.
● Common arithmetic operators include:
○ + (addition)
○ - (subtraction)
○ * (multiplication)
○ / (division)
○ % (modulus, remainder)
○ ** (exponentiation)
○ // (floor division)
● Examples:
#Arithmetic Operations
x = 10
y = 3
result = x + y # Addition: 10 + 3 = 13
result = x - y # Subtraction: 10 - 3 = 7
result = x * y # Multiplication: 10 * 3 = 30
result = x / y # Division: 10 / 3 = 3.333...
result = x % y # Modulus (remainder): 10 % 3 = 1
result = x // y # Floor Division (quotient): 10 // 3 = 3
result = x ** y # Exponentiation: 10^3 = 1000
x = 5
y = 10
print(x == y) # False
print(x != y) # True
print(x < y) # True
print(x > y) # False
print(x <= y) # True
print(x >= y) # False
3. Logical Operators:
● Perform logical operations on Boolean values.
● Example: and (logical AND), or (logical OR), not (logical NOT).
9
NotesNeo
p = True
q = False
print(p and q) # False
print(p or q) # True
print(not p) # False
4. Assignment Operators:
● Assign values to variables and perform assignments with arithmetic operations.
● Example: = (assignment), += (addition assignment), -= (subtraction assignment), *=
(multiplication assignment), /= (division assignment), %= (modulo assignment), **=
(exponentiation assignment), //= (floor division assignment).
x = 5
x += 2 # equivalent to x = x + 2
print(x) # 7
5. Bitwise Operators:
● Perform bit-level operations on integers.
● Example: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift),
>> (right shift).
a = 5 # binary: 0101
b = 3 # binary: 0011
print(a & b) # 1 (bitwise AND)
print(a | b) # 7 (bitwise OR)
print(a ^ b) # 6 (bitwise XOR)
print(~a) # -6 (bitwise NOT)
print(a << 1) # 10 (left shift by 1)
print(a >> 1) # 2 (right shift by 1)
6. Membership Operators:
● Test whether a value is a member of a sequence (e.g., a string, list, or tuple).
● Example: in (True if value is found in the sequence), not in (True if value is not found in the
sequence).
my_list = [1, 2, 3, 4, 5]
print(3 in my_list) # True
print(5 not in my_list) # False
7. Identity Operators:
● Compare the memory locations of two objects.
● Example: is (True if both variables reference the same object), is not (True if variables
reference different objects).
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is b) # False
print(a is not b) # True
10
NotesNeo
print(a is c) # True
9 Bitwise OR ` `
'''
This is a
multi-line comment
'''
11
NotesNeo
Error Messages:
● Python provides error messages to help you identify and fix issues in your code.
● Common types of errors include:
○ SyntaxError: Occurs when there's a syntax mistake in your code.
print("Hello World" # This will raise a SyntaxError
○ NameError: Occurs when you try to use a variable or function that hasn't been
defined.
print(age) # This will raise a NameError
○ TypeError: Occurs when you perform an operation on data of the wrong type, e.g.,
trying to add a string and an integer.
x = 10
y = "5"
result = x + y # This will raise a TypeError
● When you encounter an error, Python will provide an error message that includes a
description of the problem and the line number where it occurred. Understanding these
messages is crucial for debugging your code.
1. if Statement:
● The if statement is used to execute a block of code if a specified condition is true.
if condition:
# Code to run if the condition is True
● Example:
x = 10
if x > 0:
print("Positive")
2. else Statement:
● The else statement is used to specify a block of code to be executed if the condition
in the initial if statement is false.
if condition:
# Code to run if the condition is True
else:
# Code to run if the condition is False
● Example:
x = -5
if x > 0:
print("Positive")
else:
print("Negative")
12
NotesNeo
3. elif Statement (else if ladder):
● The elif statement is used for testing multiple conditions after the initial if statement.
It allows you to check additional conditions if the initial condition is false.
if condition1:
# Code to run if condition1 is True
elif condition2:
# Code to run if condition2 is True
# Additional elif clauses
● Example:
x = 0
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")
while True:
# Get user input for operation
operator = input("Enter an operator (+, -, *, /) or 'exit' to quit:
")
13
NotesNeo
case '-':
result = num1 - num2
print(f"{num1} - {num2} = {result}")
case '*':
result = num1 * num2
print(f"{num1} * {num2} = {result}")
case '/':
if num2 != 0:
result = num1 / num2
print(f"{num1} / {num2} = {result}")
else:
print("Cannot divide by zero.")
case _:
print("Invalid operator. Please enter +, -, *, /, or
'exit'.")
1. for Loop
● The for loop is used for iterating over sequences such as lists, tuples, and strings.
● It executes a block of code for each item in the sequence.
● Syntax:
for item in sequence:
# Code to run for each item in the sequence
● Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
● Example:
for i in range(0, 5):
print(i)
Output:
0
1
2
3
4
2. while Loop
● The while loop is used for repeated execution of a block of code as long as a
specified condition is True.
● Syntax:
14
NotesNeo
while condition:
# Code to run while the condition is True
● Example:
i = 0
while i < 5:
print(i)
i+= 1
Output:
0
1
2
3
4
1. continue:
● The continue statement is used inside a loop to skip the rest of the code inside the
loop for the current iteration and move on to the next iteration. It is often used when
a specific condition is met, and you want to skip the remaining code for that
particular iteration.
● Example:
for i in range(5):
if i == 3:
continue # Skip the iteration when i is 3
print(i)
● In this example, when i is equal to 3, the continue statement is encountered, and the
rest of the loop code for that iteration is skipped. So, the output will be:
0
1
2
4
2. break:
● The break statement is used to exit a loop prematurely, regardless of whether the
loop condition is still true. It is often used when a specific condition is met, and you
want to terminate the loop.
● Example:
for i in range(5):
if i == 3:
break # Exit the loop when i is 3
print(i)
● In this example, when i is equal to 3, the break statement is encountered, and the
loop is terminated. The output will be:
15
NotesNeo
0
1
2
3. pass:
● The pass statement is a no-operation statement. It is used as a placeholder when
syntactically some code is required, but you don't want to perform any action.
● Example:
for i in range(5):
if i == 3:
pass # Do nothing when i is 3
print(i)
Section 9: Strings
String
A string is a sequence of characters enclosed within single (' '), double (" "), or
triple (''' ''' or """ """) quotes in Python. Strings are immutable, which means their values cannot be
changed once they are assigned.
Example:
name = 'Decoders'
print( name) # Output : Decoders
print("Hello " + name) # Output : Hello Decoders
If our string has multiple lines, we can create them like this:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Idexing
Strings can be accessed using the subscript operator [], which uses zero-based indexing. Each
character in a string has a unique index, starting from 0 for the first character and going up to n-1
for the last character. For example, my_string[2] accesses the third character in my_string.
Example:
my_string = "Python"
print(my_string[2]) # Output: 't'
16
NotesNeo
print(str[1]) # Output: 'e'
print(str[6]) # Output: 'D'
print(str[13]) # Output: 's'
print(str[14]) # Output: IndexError: string index out of range
Negative indexing in Python allows you to access elements from the end of a sequence, including
strings. Negative indices count backward from the end, with -1 representing the last element, -2
representing the second-to-last element, and so on.
Example:
str = "Hello Decoders"
print(str[-1]) # Output: 's'
# Similar to print(str[len(str)-1])
print(str[-2]) # Output: 'r'
print(str[-8]) # Output: 'D'
print(str[-14]) # Output: 'H'
Negative indexes are useful when you need to access elements from the end without knowing the
length of the string.
Slicing a String
String slicing in Python allows to extract a portion (sub-string) of a string by specifying a range of
indices. The basic syntax for string slicing is: string[start:stop:step]
● start: The index from which the slicing begins (inclusive).
● stop: The index at which the slicing stops (exclusive).
● step: The jump or increment between the indices.
# Basic slicing
print(str[0:5]) # Hello
print(str[6:14]) # Decoders
print(str[8:13]) # coder
# Using step
print(str[::2]) # HloDcdr
print(str[6:14:2]) # Dcdr
17
NotesNeo
# Similar to print(str[len(str)-14:len(str)-9])
print(str[-8:]) # Decoders
print(str[:-1]) # Hello Decoder
print(str[-6:-1]) # coder
print(str[::-1]) # sredoceD olleH (reverse)
print(str[-1]) # s
String Manipulations
Length of a String
We can find the length of a string using len() function.
Example:
fruit = "Mango"
len1 = len(fruit)
print("Mango is a", len1, "letter word.")
Output:
Mango is a 5 letter word.
print(result)
Output:
Hello World
18
NotesNeo
In this example, the + operator is used to concatenate string1, a space, and string2.
print(result)
Output:
Hello World
In this example, the join() method is used to concatenate string1 and string2 with a space in
between.
Example:
print("Python")
print("Hello", end=" ")
print("World!")
Output:
Python
Hello World!
In this example, the end=" " parameter ensures that the next print() statement continues on the
same line, separated by a space.
Slicing Example:
pie = "ApplePie"
print(pie[:5]) # Slicing from Start
print(pie[5:]) # Slicing till End
print(pie[2:6]) # Slicing in between
print(pie[-8:]) # Slicing using negative index
print(pie[2:6:2]) # Slicing using step
Output:
Apple
Pie
pleP
ApplePie
pe
19
NotesNeo
Output:
A
B
C
D
E
String is Immutable
Strings in Python are immutable, which means that once a string object is created, its contents
cannot be modified or changed. Any operation that appears to modify a string actually creates a
new string object.
my_string = "Hello"
# Attempt to modify the string
my_string[0] = "M" # TypeError: 'str' object does not support item assignment
This error occurs because strings are immutable, and individual characters of a string cannot be
changed directly using indexing and assignment.
String methods
Python provides a set of built-in methods that we can use to alter and modify the strings.
upper() :
The upper() method converts a string to upper case.
Example:
str1 = "AbcDEfghIJ"
print([Link]())
Output:
ABCDEFGHIJ
lower()
The lower() method converts a string to lower case.
Example:
str1 = "AbcDEfghIJ"
print([Link]())
Output:
abcdefghij
strip() :
The strip() method removes any white spaces before and after the string.
Example:
str2 = " Silver Spoon "
print([Link])
Output:
Silver Spoon
rstrip() :
the rstrip() removes any trailing characters. Example:
str3 = "Hello !!!"
20
NotesNeo
print([Link]("!"))
Output:
Hello
replace() :
The replace() method replaces all occurrences of a string with another string. Example:
str2 = "Silver Spoon"
print([Link]("Sp", "M"))
Output:
Silver Moon
split() :
The split() method splits the given string at the specified instance and returns the separated strings
as list items.
Example:
str2 = "Silver Spoon"
print([Link](" ")) # Splits the string at the whitespace " "
Output:
['Silver', 'Spoon']
join() :
The join() method concatenates the given elements of a list into a single string and returns the
resulting string.
Example:
list1 = ['Silver', 'Spoon']
print(" ".join(list1 )) # Joins the list items with a whitespace " "
Output:
Silver Spoon
There are various other string methods that we can use to modify our strings.
capitalize() :
The capitalize() method turns only the first character of the string to uppercase and the rest other
characters of the string are turned to lowercase. The string has no effect if the first character is
already uppercase.
Example:
str1 = "hello"
print([Link]())
str2 = "hello WorlD"
print([Link]())
Output:
Hello
Hello world
title() :
The title() method capitalizes each letter of the word within the string.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print([Link]())
21
NotesNeo
Output:
He'S Name Is Dan. Dan Is An Honest Man.
center() :
The center() method aligns the string to the center as per the parameters given by the user.
Example:
str1 = "Welcome to the Console!!!"
print([Link](50))
Output:
Welcome to the Console!!!
We can also provide padding character. It will fill the rest of the fill characters provided by the user.
Example:
str1 = "Welcome to the Console!!!"
print([Link](50, "."))
Output:
............Welcome to the Console!!!.............
count() :
The count() method returns the number of times the given value has occurred within the given
string.
Example:
str2 = "Abracadabra"
print([Link]("a"))
Output:
4
endswith() :
The endswith() method checks if the string ends with a given value. If yes then return True, else
return False.
Example :
str1 = "Welcome to the Console !!!"
print([Link]("!!!"))
Output:
True
We can even also check for a value in-between the string by providing start and end index
positions.
Example:
str1 = "Welcome to the Console !!!"
print([Link]("to", 4, 10))
Output:
True
find() :
The find() method searches for the first occurrence of the given value and returns the index where
it is present. If the given value is absent from the string then return -1.
Example:
str1 = "He's name is Dan. He is an honest man."
print([Link]("is"))
Output:
22
NotesNeo
10
As we can see, this method is somewhat similar to the index() method. The major difference being
that index() raises an exception if value is absent whereas find() does not.
Example:
str1 = "He's name is Dan. He is an honest man."
print([Link]("Daniel"))
Output:
-1
index() :
The index() method searches for the first occurrence of the given value and returns the index
where it is present. If given value is absent from the string then raise an exception.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print([Link]("Dan"))
Output:
13
As we can see, this method is somewhat similar to the find() method. The major difference being
that index() raises an exception if value is absent whereas find() does not.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print([Link]("Daniel"))
Output:
ValueError: substring not found
isalnum() :
The isalnum() method returns True only if the entire string only consists of A-Z, a-z, 0-9. If any
other characters or punctuations are present, then it returns False.
Example :
str1 = "WelcomeToTheConsole"
print([Link]())
Output:
True
isalpha() :
The isalnum() method returns True only if the entire string only consists of A-Z, a-z. If any other
characters or punctuations or numbers(0-9) are present, then it returns False.
Example :
str1 = "Welcome"
print([Link]())
Output:
True
islower() :
The islower() method returns True if all the characters in the string are lower case, else it returns
False.
Example:
str1 = "hello world"
23
NotesNeo
print([Link]())
Output:
True
isprintable() :
The isprintable() method returns True if all the values within the given string are printable, if not,
then return False.
Example :
str1 = "We wish you a Merry Christmas"
print([Link]())
Output:
True
isspace() :
The isspace() method returns True only and only if the string contains white spaces, else returns
False.
Example:
str1 = " " #using Spacebar
print([Link]())
str2 = " " #using Tab
print([Link]())
Output:
True
True
istitle() :
The istitile() returns True only if the first letter of each word of the string is capitalized, else it
returns False.
Example:
str1 = "World Health Organization"
print([Link]())
Output:
True
Example:
str2 = "To kill a Mocking bird"
print([Link]())
Output:
False
isupper() :
The isupper() method returns True if all the characters in the string are upper case, else it returns
False.
Example :
str1 = "WORLD HEALTH ORGANIZATION"
print([Link]())
Output:
True
24
NotesNeo
startswith() :
The endswith() method checks if the string starts with a given value. If yes then return True, else
return False.
Example :
str1 = "Python is a Interpreted Language"
print([Link]("Python"))
Output:
True
swapcase() :
The swapcase() method changes the character casing of the string. Upper case are converted to
lower case and lower case to upper case.
Example:
str1 = "Python is a Interpreted Language"
print([Link]())
Output:
pYTHON IS A iNTERPRETED lANGUAGE
Binary Numbers
Explanation: Binary numbers are a base-2 numbering system, consisting of only two digits: 0 and
1. In Python, you can represent binary numbers using the 0b prefix.
Example:
binary_num = 0b1010 # Represents the decimal number 10 in binary
Octal Numbers
Explanation: Octal numbers are a base-8 numbering system, using digits 0 through 7. In Python,
you can represent octal numbers using the 0o prefix.
Example:
octal_num = 0o12 # Represents the decimal number 10 in octal
25
NotesNeo
Hexadecimal Numbers
Explanation: Hexadecimal numbers are a base-16 numbering system, using digits 0-9 and letters
A-F to represent values 10-15. In Python, you can represent hexadecimal numbers using the 0x
prefix.
Example:
hex_num = 0x1A # Represents the decimal number 26 in hexadecimal
Conversion of Numbers
● Python supports the conversion of numbers to and from binary, octal, and hexadecimal
representations using built-in functions like bin(), oct(), and hex().
● Example:
num = 42
bin_num = bin(num) # Binary: '0b101010'
oct_num = oct(num) # Octal: '0o52'
hex_num = hex(num) # Hexadecimal: '0x2a'
26
NotesNeo
● Example - Reading from a File:
# Open a file for reading
with open("[Link]", "r") as file:
content = [Link]()
print(content)
In this example, we use the with statement to open the file "[Link]" in read mode ("r"). The
as keyword assigns the file object to the variable file. We then use the .read() method
to read the entire content of the file into the content variable.
The with statement ensures that the file is properly closed after it is no longer needed.
● readline() Method: We can read one line at a time from a text file using the .readline()
method.
Example - Reading One Line at a Time:
with open("[Link]", "r") as file:
line = [Link]()
print(line)
In this example, the with statement is used to open the file in read mode, and .readline()
reads the first line of the file into the line variable. If we call .readline() again, it will read the
next line, and so on until the end of the file is reached.
● Append Mode: To add new content to an existing file without erasing its previous contents,
you can open the file in append mode ('a').
Example - Appending to a Text File:
with open("[Link]", "a") as file:
[Link]("\nAppending more text.")
In this example, we use the 'a' mode to open the file and add the text "Appending more
text." to the end of the file without deleting the existing content.
27
NotesNeo
# Check if the file exists before deleting
if [Link](file_path):
[Link](file_path)
print(f"The file '{file_path}' has been deleted.")
else:
print(f"The file '{file_path}' does not exist.")
CSV Files
Comma-Separated Values (CSV) files are a common way to store structured data. In a CSV file,
data is separated by commas, and each line represents a record. Python has a built-in csv module
to work with CSV files.
CSV files are widely used for storing structured data, such as spreadsheets, databases, or any
data that can be organized into rows and columns. In CSV files, data is separated by commas, and
each line typically represents a row of data.
● Example - Writing to a CSV File:
import csv
data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
[Link](data)
● Example - Reading to a CSV File:
import csv
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
print(row)
Tab-Separated Files
If you want to work with tab-separated files, where data is separated by tabs instead of commas,
you can use the same csv module, but specify the delimiter as a tab character ("\t"):
28
NotesNeo
MDU PYQs
1. What are the key features of the Python ?
2. Explain about the need for learning python programming language and its importance.
3. Is Python scripting language ? Justify it.
4. Name the command to clear the python shell.
5. Explain command line arguments and write a program to demonstrate it.
6. Explain getopt() function in python.
7. What are mutable and immutable datatypes in python ?
8. What are the common built-in datatypes in Python ?
9. How can we declare local and global variable in Python ?
10. Explain the concept of scope and lifetime of variables in Python with example.
11. List the rules to declare a variable in Python. Demonstrate at least three different types of
variable uses with an example program.
12. Explain the Identifiers, Keywords , Statements, Expressions and Variables with examples.
13. Define arithmetic operators and expressions in Python.
14. Describe arithmetic operators, assignment operators, comparison operators, logical
operators and bitwise operators in detail with example.
15. Explain the rules of precedence used by Python to evaluate an expression.
16. Illustrate the different types of control flow statements available in Python with flowcharts.
Explain with suitable examples.
17. Discuss the for and while loop in Python with syntax.
18. Demonstrate the use of break, continue and pass keywords in looping structure.
19. Give a note on each of the below Python constructs :
a. Quotes (single, double and triple)
b. Multiline statements
c. Indentation
20. What is string ? List and explain any two built in string manipulation function supported by
Python.
21. List out all useful string methods which supports in Python.
22. Explain the concept of slicing and indexing with proper examples. What are negative
indexes and why are they need ?
23. Explain string slicing in Python with the example.
24. Explain how to concatenate two strings in Python with examples.
25. How to print in same line in Python explain with suitable example ?
26. Describe why strings are immutable with an example.
27. How to convert the strings to numbers and vice versa in Python ?
28. Write the name of methods used to convert list to string in Python with suitable example.
29. Explain the use of join() and split() string methods with examples.
30. Write the syntax to create, open and close a file. List out different types of modes in python
with suitable example.
31. How to read / write text and numbers from the file in Python?
32. Explain how to delete a file in Python ?
29
NotesNeo
c. Total Marks
36. Write a python program to find the best of two test average marks out of three test marks
accepted from user.
37. Write a program that accepts the lengths of three slides of a triangle as inputs. The program
output should indicate whether or not the triangle is a right triangle.
38. Write a python code to find the factorial of a number.
39. Write a Python program to print all the factorial numbers less than or equal to an input
number n.
40. Write a Python program to check if a three digit number is Armstrong number or not.
41. What is strong number in Python? Consider the number 145 and check whether it is strong
or not.
42. Write a Python code to check whether the given number is strong number. Strong numbers
are numbers whose factorial of digits is equal to the original number.
43. Write a Python program to accept the sentence from the user and display the longest word
of that sentence along with its length.
44. Write a Python code to display the last six characters of the string: “The breakfast is ready”
to the console.
45. Write a Python code to display the last six characters of the string: “waiting for COVID-19
Third Phase” to the console.
46. Assume that the variable data refers to the string “Python rocks!”.
Use a string method to perform the following tasks:
a. Obtain a list of the words in the string.
b. Convert the string to uppercase.
c. Locate the position of the string “rocks”.
d. Replace the exclamation point with a question mark.
47. Write a Python program that reads a text file and changes the file capitalising each
character of the file.
48. Write a Python program to count the frequency of words in a file.
Assignment 1
1. Explain the rules of precedence to evaluate an expression in Python.
2. Explain the built-in string manipulation function methods with examples.
3. Explain the data types in Python using examples?
4. What is the difference between tuples and dictionaries using examples?
5. What are arithmetic operators in Python? (Write code also).
6. Write the algorithm and Python program to check if the number is positive, negative, or
zero.
7. Write a Python program to find the best of two test average marks out of three test marks
accepted by the user.
8. How many types of comments are in Python? Also write the algorithm to find the sum of n
numbers.
9. What are Control statements? Explain with example.
10. Demonstrate the use of break and continue keywords in a looping structure.
11. What is the difference between while and for loop in Python using examples?
30