Getting started with Python, Strings

Unit 1 - Introduction to Python

                                                  UNIT- 1

 Introduction to Python

Python is a powerful open-source, high–level, object–oriented programming language created by "Guido Van Rossum" and first released in 1991. It is further developed by the Python Software Foundation. It is one of the widely used, popular, and powerful programming languages. It has simple, easy–to–use syntax, making it the perfect language for someone trying to learn computer programming for the first time, and it is also a good language to have in any programmer’s stack as it can be used for everything from web development to software development and scientific applications.

Features of Python: 

1) Easy to Learn and Use

  • Python is easy to learn as compared to other programming languages.
  • Its syntax is straightforward and much the same as the English language.
  • There is no use of the semicolon or curly-bracket; the indentation defines the code block. 

2) Expressive Language 

  • Python can perform complex tasks using a few lines of code.
  • A simple example, the Hello World program you simply type print("Hello World").
  • It will take only one line to execute, while Java or C takes multiple lines. 

3) Interpreted Language

  • Python is an interpreted language; it means the Python program is executed one line at a time.
  • The advantage of being interpreted language, it makes debugging easy and portable. 

4) Cross-platform Language

  • Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc.
  • So, we can say that Python is a portable language.
  • It enables programmers to develop the software for several competing platforms by writing a program only once. 
5) Free and Open Source
  • Python is freely available for everyone.
  • It is freely available on its official website, www.python.org. 
  • It has a large community across the world that is dedicated to making new Python modules and functions. 
  • The open-source means, "Anyone can download its source code without paying a penny."
6) Object-Oriented Language
  • Python supports an object-oriented language, and concepts of classes and objects come into existence.
  • It supports inheritance, polymorphism, and encapsulation etc. 
  • The object-oriented procedure helps to programmers to write reusable code and develop applications with less code. 
7) Extensible
  • It implies that other languages such as C/C++ can be used to compile the code and thus it can be used further in our Python code.
  • It converts the program into byte code, and any platform can use that byte code.  
8) Large Standard Library
  • It provides a vast range of libraries for the various fields such as machine learning, web developer, and also for the scripting.
  • There are various machine learning libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc.
  • Django, flask, pyramids are the popular framework for Python web development.
9) GUI Programming Support
  • Graphical User Interface is used for the developing Desktop application.
  • PyQT5, Tkinter, Kivy are the libraries which are used for developing the web application.
10) Integrated
  • It can be easily integrated with languages like C, C++, and JAVA, etc. 
  • Python runs code line by line like C,C++ Java. It makes easy to debug the code.
11) Embeddable
  •  The code of the other programming language can use in the Python source code.
  • We can use Python source code in another programming language as well.
12) Dynamic Memory Allocation
  • In Python, we don't need to specify the data-type of the variable.
  • When we assign some value to the variable, it automatically allocates the memory to the variable at run time. 
  • Suppose we are assigned integer value 15 to x, then we don't need to write int x = 15. Just write x = 15. 

Keywords:

  • Keywords are the reserved words in the Python programming language. 
  •  All keywords are designated with a special meaning.
  •  The meaning of all keywords is fixed, and it cannot be modified or removed.
  •  All the keywords need to be used as they have been defined (Lower case or Upper case).
  •  In Python, there are 35 keywords.
  •  All the keywords in Python are listed in the following table with their meaning: 
S.No   Keyword      Description
1 False Boolean false value
2 None Represents absence of value
3 True Boolean true value
4 and Logical AND operator
5 as Alias (e.g. in import, with statements)
6 assert Assert condition for debugging
7 async Defines an async function
8 await Awaits result of an async operation
9 break Exit loop early
10 class Defines a class structure
11 continue Skip to next loop iteration
12 def Define a function
13 del Delete a variable or element
14 elif Else-if in conditional chains
15 else Fallback in conditionals or try blocks
16 except Catch exceptions
17 finally Always-run clause in try-except blocks
18 for For-loop construct
19 from Import specific items from modules
20 global Declare a global variable
21 if Conditional branching
22 import Import a module
23 in Membership test
24 is Identity comparison
25 lambda Define anonymous (single-expression) function
26 nonlocal Declare non-local (enclosing scope) variable
27 not Logical NOT operator
28 or Logical OR operator
29 pass No-op placeholder
30 raise Raise an exception
31 return Return from a function
32 try Start a try-except block
33 while While-loop construct
34 with Context manager usage
35 yield Generate values from a generator

You can use the built-in keyword module in Python to display all the current keywords.

import keyword
for kw in keyword.kwlist:
    print(kw)


Identifiers

  • Identifiers in Python are names used to identify a variable, function, class, module, or other objects.
  • An identifier can only contain letters, digits, and underscores, and cannot start with a digit. 
  • In Python, identifiers are case-sensitive, meaning that swathi and SWATHI are considered to be two different identifiers. 
Rules for Identifiers in Python:

These are the rules for identifiers in Python:
  • Keywords cannot be used as identifiers in Python (because they are reserved words).
  • The names of identifiers in Python cannot begin with a number.
  • All the identifiers in Python should have a unique name in the same scope.
  • The first character of identifiers in Python should always start with an alphabet or underscore, and then it can be followed by any of the digits, characters, or underscores.
  • Identifier name length is unrestricted.
  • Names of identifiers in Python are case sensitive, meaning ‘car’ and ‘Car’.
  • Special characters such as ‘%’, ‘#’,’@’, and ‘$’ are not allowed as identifiers in python.
Valid Identifiers: 

These are examples of valid identifiers in Python.
  • yourname It contains only lowercase letters. 
  • Name_school It contains only ‘_’ as a special character.
  • Id1 Here, the numeric digit comes at the end.
  •  roll_2 It starts with a lowercase letter and ends with a digit. 
  •  _classname contains lowercase alphabets and an underscore, and it starts with an underscore ‘_’.

Invalid Identifiers:

These are examples of valid invalid identifiers in Python. 
  • (for, while, in) - These are the keywords in Python that cannot be used as identifiers in Python.
  • 1myname - Invalid identifier because it begins with a digit.
  • \$myname - Invalid identifier because it starts with a special character 
  • a b - Invalid identifier because it contains a blank space.
  • (a/b and a+b) - Invalid identifiers because they contain special characters.

Variable:

  • In Python, a variable is a named memory where a programmer can store data and retrieve it for future use using the same name.
  • In Python, variables are created without specifying any data type. 
  • There is no specific keyword used to create a variable.
  • Variables are created directly by specifying the variable name with a value. 
We use the following syntax to create a variable:
Syntax:
 variable_name = value
 
When a variable is defined, we must create it with a value. 

roll_number = 101
print(f'Student roll number is {roll_number}') 
Output:
Student roll number is 101

Declaring multiple variables in a single statement
  • In Python, it is possible to define more than one variable using a single statement.
  • When multiple variables are created using a single statement, the variables and their corresponding value must be separated with a comma.  
Python code to illustrate variable declaration :
name, roll_number = ('Saranya', 101) 
print(f'{name}'s roll number is {roll_number}') 
Output: Saranya's roll number is 101 

Assigning a single value to multiple variables:
x=y=z=50 
print(x)
print(y) 
print(z) 
Output: 50 50 50 

Displaying the data type of a variable 

  • In Python, the data type of a variable never fixed to a particular data type and it keeps changing according to the value assigned to it. 
  • A variable in Python stores value of any data type. 
  • It can change its data type dynamically. 
  • The Python programming language provides a built-in function type( ) to display the data type of a variable.
Let's consider the following Python code:
a = 105
print(type(a)) 
a = 10.66 
print(type(a)) 
a = 'Ashaz' 
print(type(a))
Output: 
<class 'int'>
<class 'float'>
<class 'str'>

Comments

  • Comments are essential for defining the code and help us and other to understand the code.
  • By looking the comment, we can easily understand the intention of every line that we have written in code.
  • We can also find the error very easily, fix them, and use in other applications.
  • In Python, we can apply comments using the # hash character.
  • The Python interpreter entirely ignores the lines followed by a hash character.
  • A good programmer always uses the comments to make code under stable.

Types of Comments in Python

1. Single-Line Comments
  • Begin with the # symbol.
  • Used for brief explanations or notes.
  • Applies only to one line.
Syntax:
# This is a single-line comment
print("Sri")

Output:
Sri

2. Multi-Line (Block) Comments
  • Multiple single-line comments used together to create block comments.
  • Python doesn't support block comments like /* */, so # is used at the beginning of each line.
Syntax:

# This type of comment can serve
# both as a single line as well
# as a multi-line (block) comment

Example:

# Read name from keyboard
# variable name is myName
myName = input("Enter your Name: ")
# Display data on the output screen
print("Hello,", myName)

Output:

Enter your Name: Swathi
Hello, Swathi

3. Inline Style Comments
  • Placed on the same line as a statement.
  • Used to explain the statement.
Example:

# Find the product of two numbers
x = 5   # value 3 stored in x
y = 7   # value 7 stored in y
z = x * y  # product stored in z
print("Product is:", z)

Output:

Product is: 35

4. Docstring Comments (Documentation Strings)
  • Written using triple quotes ''' or """.
  • Used to describe the purpose of a function, class, or module.
  • Not exactly comments, but act like them when not assigned to a variable.

Example:

"""
Read two values through command line arguments
Then find the sum with data type conversion
"""
import sys
x = int(sys.argv[1])  # Read and convert x
y = int(sys.argv[2])  # Read and convert y
sum = x + y
print("Sum of two numbers is:", sum)

Command Line Output:

> python docstring.py 15 6
Sum of two numbers is: 21



Indentation

In Python, indentation refers to the spaces at the beginning of a code line. Unlike other programming languages like C, C++, or Java that use curly braces {} to define code blocks, Python uses indentation as a part of its syntax.

Indentation is mandatory in Python—it defines the structure and flow of the code. Without proper indentation, a Python program will not execute and will raise an IndentationError.

Key Points About Python Indentation:

  • Indentation defines blocks of code.
  • The number of spaces used for indentation can vary, but consistency within a block is crucial.
  • All statements at the same indentation level belong to the same code block.
  •  Python does not use curly braces to denote code blocks (like functions, loops, classes, etc.).
Example:

def greet(name):
    if name:
        print("Hello, " + name)
    else:
        print("Hello, Stranger!")

In this example:

  • The print() statements are indented inside their respective if and else blocks.

  • The if and else blocks are themselves indented inside the function.

It's recommended to use 4 spaces per indentation level (PEP 8 recommendation).


Datatypes

In Python, everything is an object, and every object has a data type.
A data type defines the type of value a variable can hold and the operations that can be performed on it.

Classification of Python Built-in Data Types:

➤ 1. Numeric Data Types

These represent numbers and are of three types:

a) int
  • Used to store whole numbers.
  • Can be positive or negative.
  • There is no limit to the size of the integer.
Example:

a = 291
print(type(a))  # <class 'int'>

b) float
  • Used to store decimal (floating point) numbers.
  • It can also store values in scientific notation using e or E.
Example:

b = 267.0
print(type(b))  # <class 'float'>

c) complex
  • Used to represent complex numbers.
  • Syntax: real + imaginary j

Example:

c = 231 + 27j
print(type(c))  # <class 'complex'>


➤ 2. Sequence Data Types

Sequences store a collection of items in a specific order.

a) str (String)
  • A string is a sequence of Unicode characters.
  • Defined using single, double, or triple quotes.
  • No separate character data type in Python. A character is a string of length 1.
Example:

s = "Swathi"
print(type(s))  # <class 'str'>

b) list
  • Ordered, mutable (can change after creation).
  • Allows duplicate values.
  • Can hold elements of different types.
Creating a list:

lst = ["Hello", "Swathi", 71, 2025, 6.0, 'K']

Accessing list elements:

print(lst[0])     # 'Hello'
print(lst[-1])    # 'K' (last item)
print(type(lst[2]))  # <class 'int'>

c) tuple
  • Ordered, immutable (cannot change once created).
  • Can contain elements of different data types.
Creating a tuple:

tpl = ('Hello', 'Swathi')
tpl2 = tuple([60.5, 27, 2025, 11, "Earth", "K"])

Nested tuple:

tpl3 = (tpl2, tpl)

Accessing elements:

print(tpl3[0][2])  # 2025

➤ 3. Boolean Type

  • Has only two values: True and False
  • Used in logical operations, conditions, and comparisons.
  • Internally, True is treated as 1 and False as 0.

Example:

print(type(True))   # <class 'bool'>
print(type(False))  # <class 'bool'>

➤ 4. Set

  • Unordered collection of unique items.
  • Cannot have duplicates.
  • Mutable – we can add or remove elements.
  • Does not support indexing.
Creating a set:

set1 = set()
set2 = {68.0, 27, 2025, 'K', 'Swathi', 'S'}

Accessing elements:

for i in set2:
    print(i)  # Iterates through set elements

➤ 5. Dictionary

  • Stores key-value pairs.
  • Unordered, mutable, and does not allow duplicate keys.
  • Keys must be immutable (like numbers, strings, or tuples).
Creating a dictionary:

dic = {"name": "Chinnu", "age": 2, 5: "Swathi"}

Accessing values:

print(dic['name'])     # Chinnu
print(dic[5])          # Swathi
print(dic.get('age'))  # 2



Operators

  • In Python, an operator is a symbol used to perform arithmetical and logical operations. 
  • In other words, an operator can be defined as a symbol used to manipulate the value of an operand. 
  • Here, an operand is a value or variable on which the operator performs its task. 
  • For example, '+' is a symbol used to perform the mathematical addition operation. Consider the expression a = 10 + 30. 
  • Here, variable 'a', values '10' and '30' are known as Operands, and the symbols '=' and '+' are known as Operators.

Types of Operators in Python

In Python, there is a rich set of operators, and they are classified as follows.
  • Arithmetic Operators ( +, -, *, /, %, **, // ) 
  • Assignment Operators ( =, +=, -=, *=, /=, %=, **=, //= ) 
  • Comparison Operators ( <, <=, >, >=, ==, != ) 
  • Logical Operators ( and, or, not ) 
  • Identity Operators ( is, is not ) 
  • Membership Operators ( in, not in )

Arithmetic Operators 
  • In Python, the arithmetic operators are the operators used to perform a basic arithmetic operation between two variables or two values. 
  • The following table presents the list of arithmetic operations in Python along with their description. 
  • To understand the example, let's consider two variables, a with value 10 and b with value 3.
Operator Meaning      DescriptionExample
+AdditionAdds the values on both sides of the operatora + b = 13
-SubtractionSubtracts the right-hand operand from the left-hand operanda - b = 7
*MultiplicationMultiply values on both sides of the operatora * b = 30
/DivisionDivides the left-hand operand by the right-hand operanda / b = 3.33
%ModulusReturns the remainder of the division of the left operand by the right operanda % b = 1
**ExponentiationRaises the left operand to the power of the right operanda ** b = 100000
//Floor DivisionDivides and returns the largest whole number less than or equal to the resulta // b = 3

Example - Arithmetic Operators in Python

a = 10
b = 3
print(f"a + b = {a + b}")    # Addition
print(f"a - b = {a - b}")    # Subtraction
print(f"a * b = {a * b}")    # Multiplication
print(f"a / b = {a / b}")    # Division
print(f"a % b = {a % b}")    # Modulus
print(f"a ** b = {a ** b}")  # Exponentiation
print(f"a // b = {a // b}")  # Floor Division

Output:
a + b = 13
a - b = 7
a * b = 30
a / b = 3.3333333333333335
a % b = 1
a ** b = 1000
a // b = 3

Assignment Operators
  • In Python, the assignment operators are the operators used to assign the right-hand side value to the left-hand side variable. 
  • The following table presents the list of assignment operations in Python along with their description.
Operator Meaning Description Example
= Assignment Assigns the value on the right to the variable on the left x = 5
+= Add and Assign Adds the right operand to the left operand and assigns the result to the left operand x += 3x = x + 3
-= Subtract and Assign Subtracts the right operand from the left operand and assigns the result to the left operand x -= 2x = x - 2
*= Multiply and Assign Multiplies the left operand by the right and assigns the result to the left operand x *= 4x = x * 4
/= Divide and Assign Divides the left operand by the right and assigns the result to the left operand x /= 2x = x / 2
%= Modulus and Assign Takes modulus using left and right operands, assigns the result to the left operand x %= 3x = x % 3
**= Exponent and Assign Raises the left operand to the power of the right operand and assigns it to the left operand x **= 2x = x ** 2
//= Floor Divide and Assign Performs floor division and assigns the result to the left operand x //= 3x = x // 3


Example:

a = 10
b = 3

a += b
print(f"a += b => {a}")  # a = 13

a -= b
print(f"a -= b => {a}")  # a = 10

a **= b
print(f"a **= b => {a}")  # a = 1000 

a //= b
print(f"a //= b => {a}")  # a = 333

a *= b
print(f"a *= b => {a}")  # a = 999

a /= b
print(f"a /= b => {a}")  # a = 333.0

a %= b
print(f"a %= b => {a}")  # a = 0.0

a **= b
print(f"a **= b => {a}")  # a = 0.0

Output:

a += b => 13
a -= b => 10
a **= b => 1000
a //= b => 333
a *= b => 999
a /= b => 333.0
a %= b => 0.0
a **= b => 0.0

Comparison Operators
  • In Python, the comparison operators are used to compare two values. 
  • In other words, comparison operators are used to check the relationship between two variables or values. 
  • The comparison operators are also known as Relational Operators. 
To understand the example let's consider two variables a with value 10 and b with value 3.

Operator Meaning Description Example Result
< Less than Returns True if the left value is smaller than the right value, else False a < b False
<= Less than or Equal to Returns True if the left value is smaller than or equal to the right value, else False a <= b False
> Greater than Returns True if the left value is larger than the right value, else False a > b True
>= Greater than or Equal to Returns True if the left value is larger than or equal to the right value, else False a >= b True
== Equal to Returns True if the left value is equal to the right value, else False a == b False
!= Not equal to Returns True if the left value is not equal to the right value, else False a != b True

Example:

a = 10
b = 3
print(a < b)   # False
print(a <= b)  # False
print(a > b)   # True
print(a >= b)  # True
print(a == b)  # False
print(a != b)  # True

Output:

False
False
True
True
False
True

Logical Operators 
  • In Python, the logical operators are used to merge multiple conditions into a single condition.
  • In Python, the logical operators are used to merge multiple conditions into a single condition. 
Operator Meaning  Description
and      Logical AND   Returns True if both conditions are True. Otherwise, False.
or Logical OR Returns True if at least one condition is True.
not Logical NOT Reverses the logical state of the condition.
 
Example:

a = 10
b = 3 
print(a < b and a > c)   # False and False → False
print(a < b or a > c)    # False or False → False
print(not a > b)         # not True → False

Output:
False
False
False


Identity Operators 
  • In Python, identity operators are used to comparing the memory locations of two objects or variables.
  • The following table presents the list of identity operations in Python along with their description. 
Operator Meaning Description
is Is identical Returns True if both variables point to the same object in memory.
is not Is not identical Returns True if both variables do not point to the same object in memory.

Example: 

a = 10
b = 3
print(a is b)    10 is 3 → False
print(a is not b)    10 is not 3 True

Output:
False
True


Membership Operators
  • In Python, the membership operators are used to test whether a value is present in a sequence.Here the sequence may be String, List, or Tuple.
  • The following table presents the list of membership operations in Python along with their description.
Operator Meaning Description
in In Returns True if the value is found in the given sequence.
not in Not in Returns True if the value is not found in the sequence.


Example: 
a = 10
list1 = [1, 5, 10, 15]
print(a in list1)       # True → 10 is in list1
print(a not in list1)   # False → 10 is in list1, so not in is False

Output:
True
False

Operator Precedence

Operator precedence determines the order in which operations are performed in an expression when multiple operators are used.
For example:
result = 10 + 5 * 2
Here, 5 * 2 is evaluated before 10 + because * has higher precedence than +.

The following table lists all operators from highest precedence to lowest:
Precedence Operators Description
1 (Highest) () Parentheses
2 ** Exponentiation
3 +x, -x, ~x Unary plus, minus, bitwise NOT
4 *, /, //, % Multiplication, division, etc.
5 +, - Addition, subtraction
6 <<, >> Bitwise shift operators
7 & Bitwise AND
8 ^ Bitwise XOR
9 ` `
10 ==, !=, >, <, >=, <= Comparison operators
11 is, is not, in, not in Identity & membership operators
12 not Logical NOT
13 and Logical AND
14 or Logical OR
15 (Lowest) =, +=, -=, etc. Assignment operators


Example

a = 10
b = 5
c = 2

result1 = a + b * c           # Multiplication before addition
result2 = (a + b) * c         # Parentheses first
result3 = a > b and b > c     # Comparisons before 'and'
result4 = not a < b or b == 5 # 'not' has higher precedence than 'or'

print("a + b * c =", result1)        # 10 + 5*2 = 10 + 10 = 20
print("(a + b) * c =", result2)      # (10 + 5)*2 = 15*2 = 30
print("a > b and b > c =", result3)  # True and True = True
print("not a < b or b == 5 =", result4) # not (10 < 5) or True → True or True → True

Output
a + b * c = 20
(a + b) * c = 30
a > b and b > c = True
not a < b or b == 5 = True


Input and Output Functions

Python uses two main functions to interact with the user:

Input Functions:
The input() function in Python is used to take input from the user during program execution. It always returns the input as a string.

Syntax:
variable = input("Enter your message here: ")

Example:
name = input("Enter your name: ")
print("Hello", name)

Output:
Enter your name: Swathi
Hello Swathi

Output Functions:
The print() function in Python is used to display output to the console. It can print strings, numbers, variables, and even formatted text.

Syntax:
print(object1, object2, ..., sep=' ', end='\n')

sep: defines the separator between printed items (default is space ' ').
end: defines what to print at the end (default is a newline \n).

Example:
print("Hello", "World")              # Hello World
print("A", "B", "C", sep="-")        # A-B-C
print("Hello", end=" ")              
print("Python")                      # Hello Python (on same line)

An f-string is a string literal that is prefixed with f or F. It allows you to embed expressions or variables directly inside the string using curly braces {}.
Syntax:
f"Your text {variable_or_expression}"

Example:
name = "Swathi"
age = 24
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Swathi and I am 24 years old.


The format() function is a string method that inserts values into placeholders {} within a string.
Syntax:
"Your text {} and {}".format(value1, value2)

Example:
name = "Swathi"
age = 24
print("My name is {} and I am {} years old.".format(name, age))

Output:
My name is Swathi and I am 24 years old.



Type Conversion

Type conversion means changing the data type of a value from one type to another, like from int to float, or from str to int.
We have two types of type conversion in Python:

1. Implicit Type Conversion (Automatic)
  • The Python interpreter automatically converts one data type to another without any user involvement. 
  • It happens when you mix different types in an expression.

  • Python converts smaller types to larger types to avoid data loss.

Example
x = 5
y = 2.0
z = x + y     # int + float → float
print(z)      # Output: 7.0
print(type(z))  # Output: <class 'float'>

2. Explicit Type Conversion (Type Casting)
  • It is done manually by the programmer as per requirement.

  • You use built-in functions to convert between types.

Function Converts to Example
int(x) Integer int("5")5
float(x) Floating-point float("5")5.0
str(x) String str(5)"5"
bool(x) Boolean bool(0)False
list(x) List list("abc")['a','b','c']
tuple(x) Tuple tuple([1,2])(1, 2)
set(x) Set set([1,2,2]){1,2}

Example

a = "100"
b = int(a)        # string to integer
c = float(b)      # integer to float
d = str(c)        # float to string
e = bool(b)       # int to boolean

print("a =", a, type(a))
print("b =", b, type(b))
print("c =", c, type(c))
print("d =", d, type(d))
print("e =", e, type(e))

Output
a = 100 <class 'str'>
b = 100 <class 'int'>
c = 100.0 <class 'float'>
d = 100.0 <class 'str'>
e = True <class 'bool'>


Debugging

Debugging is the process of finding and fixing errors (bugs) in your Python code to ensure it runs correctly.
Python provides a built-in module for debugging called pdb (Python Debugger). It comes with the Python Standard Library and is used to help find and fix errors in your code.

Features of pdb:
pdb supports:
  • Setting breakpoints – pause code execution at specific lines.
  • Stepping through code – execute code line by line to observe behavior.
  • Viewing stack traces – examine the call stack when an error occurs.
  • Source code listing – see parts of your source code in the debugger.
To begin debugging:

1. Insert this line into your code where you want to pause execution:
import pdb; pdb.set_trace()
This sets a manual breakpoint and drops you into the debugger interface.

2. From Python 3.7+, you can also use:
breakpoint()
This is a cleaner and recommended way to insert a breakpoint.

3. After that, run your script as usual. When it reaches the set_trace() or breakpoint(), execution will pause, and you’ll be able to enter debugger commands.

Common debugging commands:

Command Description
n (next) Execute the next line of code
s (step) Step into a function call
c (continue) Continue execution until next breakpoint
q (quit) Exit the debugger
p Print the value of an expression or variable
l List the current location in the code
b Set a breakpoint
h Help – list all commands

Example:

import pdb
def greet(name):
    message = f"Hello, {name}"
    pdb.set_trace()
    print(message)
    return message
greet("Swathi")

When you run it, it will show:

> file.py(5)greet()
-> print(message)
(Pdb)

Now you can type:
p name → Swathi
n → moves to print(message)
c → continues program


Flow of Control

Flow of Control refers to the order in which statements are executed in a Python program.

By default, Python executes code line by line from top to bottom. However, we can change this flow using:

  1. Conditional Statements

  2. Looping Statements

  3. Loop Control Statements

Conditional Statements
Conditional statements allow a program to make decisions and execute specific blocks of code based on whether a condition is True or False.

StatementDescription
ifExecutes a block if the condition is true
elifElse if — checks another condition
elseExecutes if all above are false

if statements

The if statement executes a block of code only if the condition is true.

Flowchart:




Syntax:
if condition:
    # Code block (runs if condition is true)

Example:
age = 20
if age >= 18:
    print("You are an adult.")

Output:
You are an adult.

elif statements

elif stands for "else if". It checks another condition if the previous if was False. 

Flowchart:


Syntax:
if condition1:
    # Code block 1
elif condition2:
    # Code block 2

Example:
marks = 75
if marks >= 90:
    print("Grade A")
elif marks >= 70:
    print("Grade B")

Output:
Grade B

else statements

The else block executes if none of the previous conditions are true.

Flowchart:


Syntax:
if condition1:
    # Code block 1
elif condition2:
    # Code block 2
else:
    # Code block 3

Example:
temperature = 15
if temperature > 30:
    print("Hot day")
else:
    print("Cold day")

Output:
Cold day

Looping Statements

Loops are used to execute a block of code repeatedly as long as a specified condition is true. Instead of writing the same code multiple times, you use loops to automate repetition.

for loop

A for loop in Python is used to iterate over a sequence such as a list, tuple, string, or a range of numbers.
It repeats a block of code for each item in the sequence.

Flowchart:



Syntax:

for variable in sequence:
     # Code block (executed for each item)

variable: A temporary name that holds the current item from the sequence.
sequence: A collection (like a list or range()) that the loop will go through.

Example:

Looping through a list

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:
apple
banana
cherry

Using range()

for i in range(5):
    print("Value of i:", i)

Output:
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4

Looping through String

for letter in "Python":
    print(letter)

Output:
P
y
t
h
o
n

while loop

A while loop repeats a block of code as long as a given condition is true.
Unlike a for loop (which iterates over a sequence), the while loop is used when the number of iterations is not known in advance.

Syntax:
while condition:
    # code block to execute
  • The condition is evaluated before each iteration.

  • The loop runs as long as the condition is True.

  • Make sure to change a variable inside the loop to avoid an infinite loop!

Flowchart:



Example:

count = 5
while count > 0:
    print("Counting down:", count)
    count -= 1

Output
Counting down: 5
Counting down: 4
Counting down: 3
Counting down: 2
Counting down: 1


password = ""
while password != "secret":
    password = input("Enter the password: ")
print("Access granted!")

Output
Enter the password: pass
Enter the password: 1234
Enter the password: secret
Access granted!

Infinite loop
x = 1
while x > 0:
    print("This will run forever!")  # unless x is changed or loop is broken

Always make sure your loop has an exit condition.


Jumping Statements

Jumping statements are used to control the flow of loops — they allow you to:

  • Exit a loop early

  • Skip an iteration

  • Do nothing but satisfy syntax

Statement Description
break Exits the loop immediately
continue Skips current iteration, moves to next
pass Does nothing, used as a placeholder

break statement

It is used to exit a loop (both for and while) immediately when a condition is met.

Syntax:
break;

Flowchart:


Example:
for i in range(10):
    if i == 5:
        break
    print(i)

Output:
0
1
2
3
4

continue statement

It skips the current iteration and moves to the next one, without executing the rest of the loop body.

Syntax:
continue;

Flowchart:



Example:
for i in range(6):
    if i == 3:
        continue
    print(i)

Output:
0
1
2
4
5

pass statement

Used as a placeholder where a statement is syntactically required but you don’t want to execute any code.

Syntax:
pass;

Flowchart:



Example:
x = 5
if x > 0:
    pass  # Placeholder for future code
print("This runs normally.")

Output:
This runs normally.


Nested Loops

Nested for loop:

A nested for loop is a for loop inside another for loop. It allows you to iterate over multiple dimensions, such as rows and columns, or combinations of elements.

Syntax:
for outer_var in outer_sequence:
    for inner_var in inner_sequence:
        # Code block that uses outer_var and inner_var

Examples:

for i in range(1, 5):
    for j in range(i):
        print("*", end=" ")
    print()

Output:

* * 
* * * 
* * * * 


rows = 4
for i in range(1, rows + 1):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()

Output:
1
1 2
1 2 3
1 2 3 4


rows = 4
for i in range(1, rows + 1):
    for j in range(i):
        print(i, end=" ")
    print()

Output:
1
2 2
3 3 3
4 4 4 4


rows = 4
for i in range(rows, 0, -1):
    for j in range(i, 0, -1):
        print(j, end=" ")
    print()

Output:
4 3 2 1
3 2 1
2 1
1


rows = 4
for i in range(1, rows + 1):
    print(" " * (rows - i), end="")  # spaces
    for j in range(1, i + 1):
        print(j, end=" ")
    print()

Output:
   1
  1 2
 1 2 3
1 2 3 4


rows = 4
for i in range(rows, 0, -1):
    for j in range(i):
        print("*", end=" ")
    print()

Output:
* * * *
* * *
* *
*

#Floyd's Triangle
rows = 4
num = 1
for i in range(1, rows + 1):
    for j in range(i):
        print(num, end=" ")
        num += 1
    print()

Output:
1
2 3
4 5 6
7 8 9 10


rows = 4
cols = 5
for i in range(rows):
    for j in range(cols):
        if i == 0 or i == rows - 1 or j == 0 or j == cols - 1:
            print("*", end=" ")
        else:
            print(" ", end=" ")
    print()

Output:
* * * * *
*        *
*        *
* * * * *


rows = 4
for i in range(1, rows + 1):
    print("  " * (rows - i), end="")  # spaces
    for j in range(i, 0, -1):
        print(j, end=" ")
    print()

Output:
       1
    2 1
  3 2 1
4 3 2 1


rows = 4
# upper half
for i in range(1, rows + 1):
    print(" " * (rows - i), end="")
    print("* " * i)
# lower half
for i in range(rows - 1, 0, -1):
    print(" " * (rows - i), end="")
    print("* " * i)

Output:

   *
  * *
 * * *
* * * *
 * * *
  * *
   *

Nested while loop:

A nested while loop means having a while loop inside another while loop.

It is used when you need to:

  • Repeat a group of statements within another loop

  • Work with rows and columns, grids, or patterns

Syntax:
while outer_condition:
    # Outer loop block
    while inner_condition:
        # Inner loop block

Examples:

i = 1
while i <= 4:
    j = 1
    while j <= i:
        print("*", end=" ")
        j += 1
    print()
    i += 1

Output:
*
* *
* * *
* * * *

i = 1
while i <= 4:
    j = 1
    while j <= i:
        print(j, end=" ")
        j += 1
    print()
    i += 1

Output:
1
1 2
1 2 3
1 2 3 4


Programs:

Check if a number is prime

num = int(input("Enter a number: "))
if num > 1:
    for i in range(2, num):
        if num % i == 0:
            print(num, "is not a prime number.")
            break
    else:
        print(num, "is a prime number.")
else:
    print(num, "is not a prime number.")

Prime numbers within a range

start = 10
end = 50

print("Prime numbers between", start, "and", end, "are:")
for num in range(start, end + 1):
    if num > 1:
        for i in range(2, num):
            if num % i == 0:
                break
        else:
            print(num, end=" ")

Armstrong number

num = int(input("Enter a number: "))
digits = len(str(num))
temp = num
sum = 0

while temp > 0:
    digit = temp % 10
    sum += digit ** digits
    temp //= 10

if sum == num:
    print(num, "is an Armstrong number.")
else:
    print(num, "is not an Armstrong number.")

Fibonacci series

n = int(input("Enter how many terms: "))
a, b = 0, 1
count = 0

while count < n:
    print(a, end=" ")
    a, b = b, a + b
    count += 1

Factorial of a number

num = int(input("Enter a number: "))
fact = 1

for i in range(1, num + 1):
    fact *= i

print("Factorial of", num, "is", fact)

Strong number

import math

num = int(input("Enter a number: "))
temp = num
sum = 0

while temp > 0:
    digit = temp % 10
    sum += math.factorial(digit)
    temp //= 10

if sum == num:
    print(num, "is a Strong number.")
else:
    print(num, "is not a Strong number.")

Palindrome number

num = int(input("Enter a number: "))
rev = int(str(num)[::-1])

if num == rev:
    print(num, "is a Palindrome.")
else:
    print(num, "is not a Palindrome.")


#Alternate logic

num = int(input("Enter a number: "))
temp = num
rev = 0

while temp > 0:
    digit = temp % 10
    rev = rev * 10 + digit
    temp //= 10

if num == rev:
    print(num, "is a Palindrome.")
else:
    print(num, "is not a Palindrome.")



Strings

A string in Python is a sequence of characters (letters, numbers, symbols, whitespace, etc.) enclosed in either:
  • Single quotes ' ', or
  • Double quotes " "
You can also use triple quotes (''' ''' or """ """) for multi-line strings.

Example:
string1 = 'Hello'
string2 = "World"
string3 = '''Multi-line
String'''

Immutability

Strings are immutable in Python. Once a string is created, you cannot modify its characters.
text = "Hello"
text[0] = 'h'   # Error: TypeError: 'str' object does not support item assignment

Instead, you can create a new string:
text = "Hello"
new_text = 'h' + text[1:]   # 'hello'
 

Indexing

Each character in a string has an index (position):

  • Positive Indexing: Starts from 0
  • Negative Indexing: Starts from -1 (last character)
name = "Swathi"
print(name[0])     # 'S'
print(name[-1])    # 'i'

Slicing

Use string[start:end] to get a substring.
  • start: Starting index (inclusive)
  • end: Ending index (exclusive)
print(name[1:5])   # 'wath'
print(name[:4])    # 'Swat'
print(name[3:])    # 'thi'

String Operations:

Concatenation
Joins two or more strings using (+)

first = "Hello"
second = "World"
result = first + " " + second

Repetition
Repeats a string multiple times using (*)

word = "Hi"
print(word * 3)   # HiHiHi

Membership(in, not in)
Checks if a substring exists within another string.

"Sw" in "Swathi"     # True
"x" not in "Swathi"   # True

Traversing a String:

You can loop through each character using:
  • for loop
for char in "Swathi":
    print(char)

  • while loop 

i = 0
name = "Swathi"
while i < len(name):
    print(name[i])
    i += 1

Why String Operators Are Important?

  1. Text Manipulation – slicing, repetition, concatenation, etc.
  2. Data Processing – useful for handling and cleaning textual data.
  3. Code Efficiency – helps write cleaner, shorter code.
  4. User Input Handling – validate and process inputs.
  5. String Comparison – using ==, !=, etc.
  6. Formatting – for readable and dynamic output.
  7. Versatility – useful across many domains (web, data, UI). 


Real-World Applications

  • User Input Validation

  • Parsing and cleaning data
  • Text file processing

  • Dynamic content generation

  • Web scraping and automation

  • Natural Language Processing (NLP)


String formatting methods

Method Description
capitalize() Capitalizes the first character of the string
casefold() Converts string to lowercase (more aggressive than lower())
center(width, fillchar) Centers string in a field of given width using fillchar
count(sub) Returns the number of times a substring occurs
encode() Returns encoded version of string (e.g., UTF-8)
endswith(suffix) Returns True if the string ends with the given suffix
expandtabs(tabsize) Replaces tabs with spaces
find(sub) Finds first occurrence of substring; returns -1 if not found
rfind(sub) Finds last occurrence of substring
index(sub) Like find(), but raises ValueError if not found
rindex(sub) Like rfind(), but raises ValueError
isalnum() Returns True if all characters are alphanumeric
isalpha() Returns True if all characters are alphabetic
isdigit() Returns True if all characters are digits
isdecimal() True if characters are only decimal numbers
islower() Returns True if all characters are lowercase
isupper() Returns True if all characters are uppercase
isspace() Returns True if string contains only whitespace
istitle() Returns True if string is in title case
join(iterable) Joins elements of iterable with the string as separator
len(string) Returns the length of the string
lower() Converts all characters to lowercase
upper() Converts all characters to uppercase
lstrip() / rstrip() / strip() Removes leading/trailing/both whitespaces
replace(old, new) Replaces all old substrings with new
split(sep) Splits string into list by separator
splitlines() Splits at line breaks (\n)
startswith(prefix) Checks if string starts with prefix
title() Capitalizes the first letter of each word
swapcase() Inverts the case of characters
zfill(width) Pads string on the left with zeros


Program:
# String Operations Demonstration
text = "  Welcome to Python programming! Let's explore string functions.  "

# 1. Strip whitespace from both ends
clean_text = text.strip()
print("1. Stripped text:", clean_text)

# 2. Convert to lowercase
lowercase_text = clean_text.lower()
print("2. Lowercase:", lowercase_text)

# 3. Convert to uppercase
uppercase_text = clean_text.upper()
print("3. Uppercase:", uppercase_text)

# 4. Replace a word
replaced_text = clean_text.replace("Python", "Advanced Python")
print("4. Replace:", replaced_text)

# 5. Find the index of a word
index = clean_text.find("explore")
print("5. Index of 'explore':", index)

# 6. Count occurrences of a character
count_o = clean_text.count('o')
print("6. Count of 'o':", count_o)

# 7. Check if the string ends with a word
ends_with = clean_text.endswith("functions.")
print("7. Ends with 'functions.':", ends_with)

# 8. Split the sentence into words
words = clean_text.split()
print("8. Split into words:", words)

# 9. Join the words with a hyphen
joined_text = "-".join(words)
print("9. Hyphen-joined string:", joined_text)

# 10. Capitalize the first letter of the string
capitalized = clean_text.capitalize()
print("10. Capitalized:", capitalized)

# 11. Check if the string is alphanumeric
is_alnum = clean_text.isalnum()
print("11. Is Alphanumeric:", is_alnum)

Output:

1. Stripped text: Welcome to Python programming! Let's explore string functions.
2. Lowercase: welcome to python programming! let's explore string functions.
3. Uppercase: WELCOME TO PYTHON PROGRAMMING! LET'S EXPLORE STRING FUNCTIONS.
4. Replace: Welcome to Advanced Python programming! Let's explore string functions.
5. Index of 'explore': 39
6. Count of 'o': 5
7. Ends with 'functions.': True
8. Split into words: ['Welcome', 'to', 'Python', 'programming!', "Let's", 'explore', 'string', 'functions.']
9. Hyphen-joined string: Welcome-to-Python-programming!-Let's-explore-string-functions.
10. Capitalized: Welcome to python programming! let's explore string functions.
11. Is Alphanumeric: False

Encode and Decode in Python

# Original string
text = "Welcome to Python!"
# 1. Encode the string into bytes using UTF-8
encoded_text = text.encode('utf-8')
print("1. Encoded (UTF-8):", encoded_text)
# 2. Decode the bytes back to a string
decoded_text = encoded_text.decode('utf-8')
print("2. Decoded back to string:", decoded_text)

# 3. Encode using a different encoding (e.g., UTF-16)
utf16_encoded = text.encode('utf-16')
print("3. Encoded (UTF-16):", utf16_encoded)
# 4. Decode UTF-16 encoded bytes
utf16_decoded = utf16_encoded.decode('utf-16')
print("4. Decoded (UTF-16):", utf16_decoded)

Output:
1. Encoded (UTF-8): b'Welcome to Python!'
2. Decoded back to string: Welcome to Python!
3. Encoded (UTF-16): b'\xff\xfeW\x00e\x00l\x00c\x00o\x00m\x00e\x00 \x00t\x00o\x00 \x00P\x00y\x00t\x00h\x00o\x00n\x00!\x00'
4. Decoded (UTF-16): Welcome to Python!

































Comments

Post a Comment

Popular posts from this blog

FUNCTIONS, PYTHON OOPS AND EXCEPTION HANDLING

Numpy and Data Handling using Pandas