Getting started with Python, Strings
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.
- 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."
- 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.
- 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.
- 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.
- Graphical User Interface is used for the developing Desktop application.
- PyQT5, Tkinter, Kivy are the libraries which are used for developing the web application.
- 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.
- 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.
- 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 |
keyword module in Python to display all the current keywords.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.
- 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.
- 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:
- (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.
- 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.
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.
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
- Begin with the # symbol.
- Used for brief explanations or notes.
- Applies only to one line.
- 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.
- Placed on the same line as a statement.
- Used to explain the statement.
- 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.
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.).
In this example:
-
The
print()statements are indented inside their respectiveifandelseblocks. -
The
ifandelseblocks are themselves indented inside the function.
Datatypes
Classification of Python Built-in Data Types:
➤ 1. Numeric Data Types
- Used to store whole numbers.
- Can be positive or negative.
- There is no limit to the size of the integer.
- Used to store decimal (floating point) numbers.
- It can also store values in scientific notation using e or E.
- Used to represent complex numbers.
- Syntax: real + imaginary j
➤ 2. Sequence Data Types
- 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.
- Ordered, mutable (can change after creation).
- Allows duplicate values.
- Can hold elements of different types.
- Ordered, immutable (cannot change once created).
- Can contain elements of different data types.
➤ 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.
➤ 4. Set
- Unordered collection of unique items.
- Cannot have duplicates.
- Mutable – we can add or remove elements.
- Does not support indexing.
➤ 5. Dictionary
- Stores key-value pairs.
- Unordered, mutable, and does not allow duplicate keys.
- Keys must be immutable (like numbers, strings, or tuples).
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
- Arithmetic Operators ( +, -, *, /, %, **, // )
- Assignment Operators ( =, +=, -=, *=, /=, %=, **=, //= )
- Comparison Operators ( <, <=, >, >=, ==, != )
- Logical Operators ( and, or, not )
- Identity Operators ( is, is not )
- Membership Operators ( in, not in )
- 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 | Description | Example |
|---|---|---|---|
+ | Addition | Adds the values on both sides of the operator | a + b = 13 |
- | Subtraction | Subtracts the right-hand operand from the left-hand operand | a - b = 7 |
* | Multiplication | Multiply values on both sides of the operator | a * b = 30 |
/ | Division | Divides the left-hand operand by the right-hand operand | a / b = 3.33 |
% | Modulus | Returns the remainder of the division of the left operand by the right operand | a % b = 1 |
** | Exponentiation | Raises the left operand to the power of the right operand | a ** b = 100000 |
// | Floor Division | Divides and returns the largest whole number less than or equal to the result | a // b = 3 |
- 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 += 3 → x = x + 3 |
-= |
Subtract and Assign | Subtracts the right operand from the left operand and assigns the result to the left operand | x -= 2 → x = x - 2 |
*= |
Multiply and Assign | Multiplies the left operand by the right and assigns the result to the left operand | x *= 4 → x = x * 4 |
/= |
Divide and Assign | Divides the left operand by the right and assigns the result to the left operand | x /= 2 → x = x / 2 |
%= |
Modulus and Assign | Takes modulus using left and right operands, assigns the result to the left operand | x %= 3 → x = x % 3 |
**= |
Exponent and Assign | Raises the left operand to the power of the right operand and assigns it to the left operand | x **= 2 → x = x ** 2 |
//= |
Floor Divide and Assign | Performs floor division and assigns the result to the left operand | x //= 3 → x = x // 3 |
- 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.
| 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 |
- 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. |
- 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. |
- 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. |
Operator Precedence
5 * 2 is evaluated before 10 + because * has higher precedence than +.| 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 |
Input and Output Functions
input() function in Python is used to take input from the user during program execution. It always returns the input as a string.print() function in Python is used to display output to the console. It can print strings, numbers, variables, and even formatted text.sep: defines the separator between printed items (default is space ' ').end: defines what to print at the end (default is a newline \n).f or F. It allows you to embed expressions or variables directly inside the string using curly braces {}.format() function is a string method that inserts values into placeholders {} within a string.Type Conversion
int to float, or from str to int.- 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.
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} |
Debugging
- 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.
| 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 |
p name → Swathin → moves to print(message)c → continues programFlow of Control
By default, Python executes code line by line from top to bottom. However, we can change this flow using:
-
Conditional Statements
-
Looping Statements
-
Loop Control Statements
| Statement | Description |
|---|---|
if | Executes a block if the condition is true |
elif | Else if — checks another condition |
else | Executes if all above are false |
if statements
if statement executes a block of code only if the condition is true.elif statements
elif stands for "else if". It checks another condition if the previous if was False. else statements
else block executes if none of the previous conditions are true.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:
# 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.while loop
while loop repeats a block of code as long as a given condition is true.for loop (which iterates over a sequence), the while loop is used when the number of iterations is not known in advance.The
conditionis 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!
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
for and while) immediately when a condition is met.continue statement
pass statement
Nested Loops
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.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
Programs:
Check if a number is prime
Prime numbers within a range
Armstrong number
Fibonacci series
Factorial of a number
Strong number
Palindrome number
Strings
-
Single quotes
' ', or -
Double quotes
" "
''' ''' or """ """) for multi-line strings.Immutability
text = "Hello"text[0] = 'h' # Error: TypeError: 'str' object does not support item assignment
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)
Slicing
string[start:end] to get a substring.- start: Starting index (inclusive)
- end: Ending index (exclusive)
String Operations:
Traversing a String:
- for loop
for char in "Swathi":print(char)
- while loop
i = 0name = "Swathi"while i < len(name):print(name[i])i += 1
Why String Operators Are Important?
-
Text Manipulation – slicing, repetition, concatenation, etc.
-
Data Processing – useful for handling and cleaning textual data.
-
Code Efficiency – helps write cleaner, shorter code.
-
User Input Handling – validate and process inputs.
-
String Comparison – using
==,!=, etc. -
Formatting – for readable and dynamic output.
-
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 |
Nice👍🏻
ReplyDelete