Basics of Python Programming
Basics of Python Programming
Introduction to Python
Python is a versatile, high-level programming language known for its readability and
simplicity. Designed with an emphasis on code clarity, Python uses straightforward syntax
that resembles everyday English, making it accessible for beginners and powerful for experts.
It supports various programming paradigms, including procedural, object-oriented, and
functional programming. Python is widely used in web development, data analysis, artificial
intelligence, scientific computing, and automation. Its extensive library ecosystem and
supportive community contribute to its popularity and effectiveness in solving diverse
problems.
Features of Python
Python is a dynamic, high-level, free open source, and interpreted programming language. It
supports object-oriented programming as well as procedural-oriented programming.
In Python, we don’t need to declare the type of variable because it is a dynamically typed
language. For example, x = 10 Here, x can be anything such as String, int, etc. In this article,
we will see what characteristics describe the Python programming language
First off, Python is known for its readable and clean syntax. Imagine writing code that
looks almost like plain English. This means you don’t need to struggle with confusing syntax
just to get things done. For example, a simple line of Python code might look like this:
print("Hello, world!"). It's easy to understand, even if you're new to programming.
Another fantastic feature is Python's versatility. It can be used for a wide range of
tasks, from web development with frameworks like Django and Flask to data analysis
with libraries like Pandas and NumPy. Want to dive into machine learning? Python's
got you covered with libraries like TensorFlow and Scikit-learn. It’s like having a
universal remote for tech projects.
Python also boasts extensive libraries and frameworks. Think of libraries as pre-
built chunks of code that you can use to solve specific problems without having to
reinvent the wheel. Need to handle HTTP requests? There’s a library for that. Want to
plot some graphs? Python has libraries for that too. It’s a bit like having a giant
toolbox where you can pick the right tool for your project.
In short, Python’s clean syntax, versatility, extensive libraries, interactive nature, and
supportive community make it a powerful and accessible language for a variety of
programming tasks.
1. Open Your Code Editor: First, you need a place to write your code. You can use any
text editor like Notepad, but it's better to use a code editor like Visual Studio Code,
PyCharm, or even an interactive environment like Jupyter Notebook.
2. Write the Code: In your editor, type the following line of code:
print("Hello, World!")
This line uses the print() function to display the text "Hello, World!" on the screen.
The print() function is a built-in Python function that outputs whatever is inside the
parentheses to the console.
3. Save Your File: Save your file with a .py extension, for example, hello_world.py.
The .py tells your computer that this file is a Python script.
4. Run the Program: To see your code in action, you need to execute it. If you’re using
a terminal or command prompt, navigate to the directory where you saved your file
and type:
python hello_world.py
Press Enter, and you should see Hello, World! displayed on the screen.
5. See the Magic: When you run the program, Python reads the print() statement and
displays "Hello, World!" on your screen. It’s like a friendly introduction from Python
saying, “Hey, your setup is all good, and I’m ready to run your code!”
That’s all there is to it! You've just executed your first Python program. It’s a simple start, but
it opens the door to more complex coding adventures. If you see the "Hello, World!"
message, you’re ready to dive deeper into the world of Python programming.
In Python, you have two main ways to run your code: interactive mode and script mode. Each
mode serves a different purpose and is useful in different scenarios.
Interactive Mode:
What It Is: Interactive mode allows you to write and execute Python code one line at
a time. It’s like having a conversation with Python where you type a command and
instantly see the result.
How to Use It: To start interactive mode, simply open your terminal or command
prompt and type python or python3. You’ll enter the Python shell, indicated by the
>>> prompt, where you can type Python commands directly.
When to Use It: Interactive mode is great for experimenting with small code
snippets, testing ideas, or learning how Python functions work. For example, you can
quickly test a function or perform calculations without having to save and run a script.
Script Mode:
What It Is: Script mode involves writing Python code in a file (usually with a .py
extension) and then running the entire file as a program. This mode is suited for larger
programs or when you want to run the same code multiple times.
How to Use It: Write your Python code in a text editor and save the file with a .py
extension. To execute the script, open your terminal or command prompt, navigate to
the file’s location, and type python filename.py (replace filename with your file’s
name).
When to Use It: Script mode is ideal for developing and running complete programs
or scripts. It allows you to organize your code into files, making it easier to manage
and reuse.
Python's character set is essentially the collection of characters that the language recognizes
and can process. This set includes a variety of characters, which are integral for writing and
executing Python code:
1. Alphabetic Characters: Python recognizes both uppercase (A-Z) and lowercase (a-z)
letters. These characters are used for naming variables, functions, classes, and more.
2. Digits: Numbers from 0 to 9 are used in Python for numeric literals, variable names,
and other expressions.
3. Special Characters: Python supports a range of special characters that are used for
various syntactic purposes:
o Quotation Marks: Single (') and double (") quotes are used for defining
string literals.
4. Whitespace Characters: Spaces, tabs, and newlines are used to format and separate
code. Python is sensitive to indentation, which uses spaces or tabs to define the
structure of the code.
1. Keywords: These are reserved words that have a special meaning in Python. They
cannot be used as identifiers (names for variables, functions, etc.). Keywords define
the language’s syntax and structure. For example, if, else, for, while, and def are
all keywords. They control the flow of the program or define its structure.
2. Identifiers: Identifiers are names given to various program elements like variables,
functions, and classes. They must start with a letter (A-Z or a-z) or an underscore (_),
followed by letters, digits, or underscores. Examples include variable_name,
my_function, and ClassName. They help us reference and manipulate data within our
code.
3. Literals: Literals are constant values directly written in the code. They represent data
like numbers, text, or boolean values. For instance:
o Arithmetic operators: +, -, *, /, %
5. Punctuators: Punctuators are symbols that help define the structure and syntax of
Python code. They include:
Variables
In Python, variables are like containers that store data values. You can think of them as labels
for pieces of information that you want to use in your program. Here's a quick rundown on
how variables work and some key points to know:
1. Naming Variables: Variables in Python are named with identifiers. They should start
with a letter (A-Z or a-z) or an underscore (_), followed by letters, digits, or
underscores. For example, age, student_name, and total_score are all valid names.
Python is case-sensitive, so score and Score would be considered different variables.
2. Assigning Values: To assign a value to a variable, you use the equals sign (=). For
instance:
age = 16
name = "Alice"
Here, age is assigned the integer 16, and name is assigned the string "Alice".
3. Types of Variables: Python is dynamically typed, which means you don’t need to
specify the type of a variable when you declare it. The type is determined
automatically based on the value assigned. Python can handle various data types
including:
4. Reassigning Values: You can change the value of a variable by assigning a new
value to it. For example:
age = 16
age = 17
Here, the variable age initially holds 16, but after the reassignment, it holds 17.
5. Using Variables: Once you have a variable, you can use it in expressions, print it, or
manipulate it in various ways. For example:
total = age + 5
print("In 5 years, you will be", total)
6. Scope of Variables: The scope of a variable refers to where it can be accessed in your
code. Variables defined inside a function are local to that function and can’t be
accessed outside of it, while variables defined outside functions are global and can be
accessed anywhere in the script.
Characteristics:
o It can appear on the left side of an assignment statement because you can
assign a value to it.
Characteristics:
Illustrative Example:
l-value: a is an l-value because it represents the memory location where the result of
the expression b + 5 will be stored.
r-value: b + 5 is an r-value because it represents the value that will be calculated and
assigned to a.
Key Points:
l-values can be assigned new values. They are typically variables or objects that can
be modified.
r-values are typically values or expressions that provide the data for the assignment.
They do not have a fixed memory location.
Use of Comments
Comments in programming are crucial for creating readable, maintainable, and
understandable code. They are notes embedded in the code that are ignored by the compiler
or interpreter during execution but can be incredibly useful for developers. Here’s a quick
guide to using comments effectively:
Purpose of Comments
1. Documentation:
o Example:
# Calculate the area of a circle
area = 3.14 * radius * radius
2. Clarification:
o Clarify Code: They can clarify why a particular approach or algorithm was
used, which can be useful for future maintenance or for other developers
reading your code.
o Example:
o Example:
4. Debugging:
o Example:
5. Code Collaboration:
o Example:
1. Single-Line Comments:
o Example:
# This is a single-line comment
print("Hello, World!") # Inline comment
2. Multi-Line Comments:
o Syntax: Use triple quotes (''' or """) for multi-line comments, although
technically, these are multi-line strings that are not assigned to a variable.
o Example:
"""
This is a multi-line comment
that spans multiple lines.
"""
print("Hello, World!")
Best Practices
Be Clear and Concise: Write comments that are easy to understand and directly
related to the code.
Avoid Redundancy: Don’t state the obvious. Instead of saying “increment x by 1,”
explain why the increment is necessary.
Keep Comments Up-to-Date: Update comments when the code changes to avoid
misleading information.
1. Integers (int):
o Range: Integers can be positive, negative, or zero. Python supports very large
integers, limited by available memory.
3. Strings (str):
o Usage: Used for text processing, displaying messages, and handling user
input.
4. Booleans (bool):
Definition: Numbers that have both a real and an imaginary part. The imaginary part
is indicated by the letter j or J.
Example: 3 + 4j, -2 - 5j
Examples in Python:
1. Integer:
number = 10
print(type(number)) # Output: <class 'int'>
2. Floating-Point:
pi = 3.14159
print(type(pi)) # Output: <class 'float'>
3. Complex:
z = 2 + 3j
print(type(z)) # Output: <class 'complex'>
1. Lists (list):
2. Tuples (tuple):
o Usage: Used to store multiple items in a fixed order where the data shouldn’t
change.
3. Dictionaries (dict):
4. Sets (set):
o Usage: Used to store unique items and perform mathematical set operations
like union, intersection, and difference.
o Example: None
Key Points
Type Conversion: You can convert between data types using functions like int(),
float(), str(), and bool().
age = 25 # int
height = 5.9 # float
name = str(age) # converts int to string
Dynamic Typing: Python is dynamically typed, meaning you don’t need to declare a
variable’s type explicitly. The type is determined at runtime based on the assigned
value.
None
In Python, None is a special constant that represents the absence of a value or a null value. It’s
a unique data type, NoneType, and is used in various scenarios to indicate that something is
undefined or missing.
1. Representation of Absence:
o Definition: None is used to signify that a variable or function does not have a
value assigned to it. It can be thought of as a placeholder or a default value
when no other value is provided.
o Example:
result = None
o Example:
def no_return():
pass
print(no_return()) # Output: None
o Example:
variable = None
if variable is None:
print("Variable is not assigned.")
4. Function Parameters:
o Example:
def greet(name=None):
if name is None:
print("Hello, World!")
else:
print(f"Hello, {name}!")
5. Comparison:
o Example:
a = None
b = None
Function Return: It provides a clear indication when a function does not return any
specific value.
1. Key-Value Pairs:
o Definition: A dictionary stores data in pairs where each key maps to a specific
value. Keys must be unique within a dictionary, but values can be duplicated.
o Example:
student = {
"name": "Alice",
"age": 18,
"courses": ["Math", "Science"]
}
2. Unordered:
o Example:
print(student)
# Output: {'name': 'Alice', 'age': 18, 'courses': ['Math',
'Science']}
3. Mutable:
o Definition: Dictionaries are mutable, meaning you can change their content
after creation. You can add, remove, or modify key-value pairs.
o Example:
4. Accessing Values:
o Example:
o Definition: Dictionaries come with several useful methods for handling data.
6. Deleting Items:
o Definition: You can remove items using methods like del or the .pop()
method.
o Example:
Example Usage:
# Creating a dictionary
car = {
"make": "Toyota",
"model": "Corolla",
"year": 2021
}
# Accessing a value
print(car["make"]) # Output: Toyota
Mutable data types are those whose values can be changed after they are created. This means
that you can modify, add, or remove elements from these objects without creating a new
object.
1. Lists (list):
o Example:
2. Dictionaries (dict):
o Example:
3. Sets (set):
o Definition: Unordered collections of unique elements that can be modified.
o Example:
numbers = {1, 2, 3}
numbers.add(4) # Adds a new element
numbers.remove(2) # Removes an element
Immutable data types are those whose values cannot be changed after they are created. Any
operation that seems to modify the object actually creates a new object.
1. Integers (int):
o Example:
a = 5
a += 2 # Creates a new integer object, 7
o Example:
pi = 3.14
pi += 0.01 # Creates a new float object
3. Strings (str):
o Example:
message = "Hello"
message = message + " World" # Creates a new string object
4. Tuples (tuple):
o Example:
Key Differences:
Mutability: Mutable types allow in-place modification (e.g., you can change a list or
dictionary without creating a new one). Immutable types do not (e.g., changing a
string results in a new string).
Use Cases: Mutable types are used when you need to change the data structure after
creation (e.g., dynamic lists or dictionaries). Immutable types are used when you need
constant values that should not change (e.g., fixed configuration settings).
Operators
Arithmetic operators, Relational operators, Logical operators
In Python, operators are special symbols that perform operations on variables and values.
They can be broadly categorized into arithmetic operators, relational operators, and logical
operators. Here's a breakdown of each category:
Arithmetic Operators
o Example:
result = 5 + 3 # Output: 8
text = "Hello" + " World" # Output: "Hello World"
o Example:
result = 10 - 4 # Output: 6
result = 7 * 2 # Output: 14
text = "Hi! " * 3 # Output: "Hi! Hi! Hi! "
o Example:
Floor Division (//): Divides one number by another, returning the largest integer less
than or equal to the result.
o Example:
result = 10 // 3 # Output: 3
o Example:
result = 10 % 3 # Output: 1
o Example:
result = 2 ** 3 # Output: 8
Relational Operators
Relational operators are used to compare values. They return a boolean value ( True or
False).
o Example:
o Example:
Greater than (>): Checks if the value on the left is greater than the value on the right.
o Example:
result = (7 > 4) # Output: True
Less than (<): Checks if the value on the left is less than the value on the right.
o Example:
Greater than or equal to (>=): Checks if the value on the left is greater than or equal
to the value on the right.
o Example:
Less than or equal to (<=): Checks if the value on the left is less than or equal to the
value on the right.
o Example:
Logical Operators
Logical operators are used to combine conditional statements and return boolean results.
o Example:
o Example:
Not (not): Reverses the logical state of its operand. Returns True if the statement is
false, and False if the statement is true.
o Example:
Assignment Operators
o Example:
1. Addition Assignment (+=): Adds a value to the variable and assigns the result back to the
variable.
Example:
x = 10
x += 5 # Equivalent to x = x + 5; x now equals 15
2. Subtraction Assignment (-=): Subtracts a value from the variable and assigns the result
back to the variable.
Example:
y = 20
y -= 7 # Equivalent to y = y - 7; y now equals 13
3. Multiplication Assignment (*=): Multiplies the variable by a value and assigns the result
back to the variable.
Example:
z = 4
z *= 3 # Equivalent to z = z * 3; z now equals 12
4. Division Assignment (/=): Divides the variable by a value and assigns the result back to
the variable. Note that this will always result in a float.
Example:
a = 8
a /= 2 # Equivalent to a = a / 2; a now equals 4.0
5. Floor Division Assignment (//=): Performs floor division (division that rounds down) on
the variable and assigns the result back to the variable.
Example:
b = 7
b //= 2 # Equivalent to b = b // 2; b now equals 3
6. Modulus Assignment (%=): Calculates the remainder of the variable divided by a value
and assigns it back to the variable.
Example:
c = 10
c %= 3 # Equivalent to c = c % 3; c now equals 1
7. Exponentiation Assignment (**=): Raises the variable to the power of a value and assigns
the result back to the variable.
Example:
d = 2
d **= 3 # Equivalent to d = d ** 3; d now equals 8
In Python, identity operators and membership operators are used to compare objects and
check their relationships. Here’s a breakdown of each:
Identity Operators
Identity operators are used to compare the memory locations of two objects, determining
whether they are the same object.
o Example:
a = [1, 2, 3]
b = a
c = [1, 2, 3]
is not: Checks if two variables do not point to the same object in memory.
o Example:
x = "hello"
y = "world"
Membership Operators
Membership operators are used to check if a value is present within a sequence (like a list,
tuple, or string) or other iterable data structures.
o Example:
numbers = [1, 2, 3, 4, 5]
print(3 in numbers) # Output: True, because 3 is in the list
print("hello" in "hello world") # Output: True, because the
substring "hello" is present in the string
o Example:
These operators are useful for performing comparisons and checking the presence of
elements in data structures, which helps in controlling the flow of a program based on certain
conditions.
o Example:
o Example:
x = 10 # This is an assignment statement
print(x) # This is a print statement
Precedence of Operators
Operator precedence determines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated before operators with lower precedence. For
instance, multiplication (*) has higher precedence than addition (+), so in the expression 2 +
3 * 4, the multiplication is performed first, giving 2 + 12, which results in 14.
Example:
Evaluation of an Expression
Example:
Type Conversion
Type conversion allows you to change the data type of a value. This can be done implicitly
by Python or explicitly by the programmer.
Explicit Conversion: Done using functions like int(), float(), and str() to
convert between types.
o Example:
num_str = "123"
num_int = int(num_str) # Converts the string "123" to the
integer 123
o Example:
Understanding these concepts helps you write more effective and error-free code by ensuring
expressions are evaluated correctly and data types are managed properly.
Accepting Data as Input From the Console and Displaying
Output
Accepting Input from the Console
To get input from the user, use the input() function. This function reads a line of text
entered by the user and returns it as a string. If you need to handle different types of input,
like integers or floats, you'll need to convert the input explicitly.
name = input("Enter your name: ") # Prompt the user and store the
entered name as a string
print(f"Hello, {name}!") # Display the entered name
To display output, use the print() function. This function can take multiple arguments and
will display them separated by spaces.
name = "Alice"
age = 17
print(f"{name} is {age} years old.") # Using f-strings for formatted
output
You can combine both input and output operations in a single program to create interactive
scripts.
You can also handle multiple inputs at once by splitting the input string.
Using input() and print() functions allows you to create interactive Python programs that
can take user input and display output dynamically.
Syntax Errors
Syntax errors occur when the code does not follow the correct syntax or structure of the
Python language. These errors are caught by the Python interpreter before the code is
executed. They are often due to typos or incorrect use of language features.
Example:
Error Message:
Fix:
Logical Errors
Logical errors occur when the code runs without crashing but produces incorrect results.
These errors are often due to incorrect logic or algorithm mistakes. Unlike syntax errors,
logical errors are not detected by the interpreter and require careful debugging and testing to
identify.
Example:
def calculate_area(radius):
return radius * radius # Incorrect formula for area of a circle
print(calculate_area(5)) # Should be 78.5 (using πr²), but returns
25
Fix:
import math
def calculate_area(radius):
return math.pi * radius * radius # Correct formula
Runtime Errors
Runtime errors occur while the program is running and often cause the program to crash or
terminate unexpectedly. These errors can be due to various issues such as invalid operations,
file not found, or division by zero.
Example:
x = 10
y = 0
print(x / y) # Division by zero error
Error Message:
Fix:
x = 10
y = 1
print(x / y) # Correct division
Understanding these errors helps in effective debugging and writing error-free code. Syntax
errors are usually the easiest to fix as they are caught early, while logical and runtime errors
require more careful inspection of the code’s logic and execution.
Use of Indentation
Python uses indentation (whitespace) to define blocks of code. Unlike some other
programming languages that use braces or keywords, Python’s indentation is crucial for
defining the structure and flow of the program. Proper indentation ensures that code blocks
(such as those following conditional statements or loops) are correctly associated with their
control statements.
Example:
if True:
print("This is inside the if block") # Indented block
print("This is outside the if block") # Not indented
Sequential Flow
Sequential flow is the most straightforward flow of control where statements are executed
one after the other, from top to bottom. This is the default mode of execution for Python
programs.
Example:
print("Start")
print("Middle")
print("End")
In this example, the program prints "Start", then "Middle", and finally "End", in that
order.
Conditional Flow
Conditional flow allows the program to make decisions and execute different blocks of code
based on certain conditions. This is typically managed using if, elif, and else statements.
Example:
age = 20
if age < 18:
print("Minor")
elif age < 65:
print("Adult")
else:
print("Senior")
Here, the program checks the value of age and prints different messages depending on
the condition met.
Iterative Flow
Iterative flow allows the program to repeatedly execute a block of code as long as a condition
is true. This is managed using loops like for and while.
for i in range(5):
print(i) # Prints numbers from 0 to 4
This loop iterates over a range of numbers and prints each one.
count = 0
while count < 5:
print(count)
count += 1 # Increments count each iteration
Understanding these control flow concepts helps in creating well-structured and logical
programs, allowing you to manage how your code executes under different conditions and
repetitions.
Conditional Statements
1. if Statement The if statement checks a condition and executes the associated block
of code if the condition is true.
o Example:
temperature = 30
if temperature > 25:
print("It's a hot day!")
o Example:
temperature = 20
if temperature > 25:
print("It's a hot day!")
else:
print("It's a cool day!")
3. if-elif-else Statement The if-elif-else statement allows multiple conditions to
be checked in sequence. The first true condition's block is executed, and if none are
true, the else block is executed.
o Example:
temperature = 10
if temperature > 30:
print("It's a very hot day!")
elif temperature > 20:
print("It's a warm day!")
elif temperature > 10:
print("It's a cool day!")
else:
print("It's a cold day!")
Flowcharts
Flowcharts visually represent the flow of control in a program. They use different shapes to
denote different types of actions or decisions.
1. Start
3. End
Simple Programs
1. Absolute Value: To find the absolute value of a number, you can use conditional
statements to handle negative values.
o Example:
number = -7
if number < 0:
absolute_value = -number
else:
absolute_value = number
print("Absolute value:", absolute_value)
2. Sort 3 Numbers: To sort three numbers, compare them using conditional statements
and arrange them in order.
o Example:
a = 5
b = 2
c = 9
if a > b:
a, b = b, a
if a > c:
a, c = c, a
if b > c:
b, c = c, b
print("Sorted numbers:", a, b, c)
o Example:
number = 15
divisor = 3
if number % divisor == 0:
print(f"{number} is divisible by {divisor}")
else:
print(f"{number} is not divisible by {divisor}")
These examples and explanations should help you understand and implement conditional
statements in Python, along with the basics of flowcharts for visualizing program logic.
Iterative statements allow you to execute a block of code repeatedly based on certain
conditions. In Python, the primary iterative statements are for loops and while loops. Here's
how they work:
1. for Loop
The for loop iterates over a sequence (like a list, tuple, or string) or a range of numbers. It’s
useful when you know in advance how many times you want to repeat a block of code.
Example:
for i in range(5):
print(i) # Prints numbers from 0 to 4
2. range() Function
The range() function generates a sequence of numbers and is commonly used with for
loops. It can take up to three arguments: start, stop, and step.
Example:
3. while Loop
The while loop executes as long as its condition remains true. It’s useful when you don’t
know beforehand how many times you’ll need to repeat the code.
Example:
count = 0
while count < 5:
print(count)
count += 1 # Increment count
4. Flowcharts
Flowcharts can be used to visualize the control flow of loops. They help in understanding
how the iteration progresses and where decisions are made.
1. Start
4. End
o Example:
for i in range(10):
if i == 5:
break # Exits the loop when i is 5
print(i)
continue: Skips the current iteration and continues with the next iteration of the loop.
o Example:
for i in range(10):
if i % 2 == 0:
continue # Skips even numbers
print(i) # Prints only odd numbers
6. Nested Loops
Nested loops involve placing one loop inside another. They are useful for working with
multi-dimensional data or generating patterns.
Example:
for i in range(3):
for j in range(3):
print(f"({i}, {j})", end=" ")
print() # New line after inner loop
Generating Patterns:
size = 5
for i in range(size):
for j in range(size):
print('*', end=' ')
print() # New line after each row
Summation of Series:
total = 0
for i in range(1, 11):
total += i
print("Sum of series:", total)
o Example:
number = 5
factorial = 1
for i in range(1, number + 1):
factorial *= i
print("Factorial:", factorial)
Understanding these iterative constructs and their uses helps in solving repetitive tasks
efficiently and allows for the creation of complex patterns and calculations in programming.
Strings are sequences of characters used to represent text in Python. They are one of the most
commonly used data types and are essential for handling textual data. Here’s a brief overview
of strings and some of their key operations.
Introduction to Strings
A string is a collection of characters enclosed in single quotes ( '), double quotes ("), or triple
quotes (''' or """). Strings are immutable, meaning once created, their content cannot be
changed.
Example:
String Operations
1. Concatenation: Concatenation combines two or more strings into one. This is done
using the + operator.
o Example:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
2. Repetition: Repetition allows you to repeat a string a certain number of times using
the * operator.
o Example:
4. Slicing: Slicing extracts a part of the string. You use indexing to specify the start and
end positions. The syntax is string[start:end].
o Example:
The for loop is straightforward and ideal for traversing a string because it directly iterates
over each character in the string.
Example:
text = "Python"
for char in text:
print(char)
Explanation:
o The for loop iterates over each character (char) in the string text.
You can also use a while loop to traverse a string by managing the index manually.
Example:
text = "Python"
index = 0
while index < len(text):
print(text[index])
index += 1
Explanation:
o The loop continues until index is equal to the length of the string
(len(text)).
If you need both the character and its index, you can use enumerate() with a for loop.
Example:
text = "Python"
for index, char in enumerate(text):
print(f"Index {index}: {char}")
Explanation:
Example:
Explanation:
Traversing a string is a fundamental skill in programming that allows you to perform various
operations such as searching, counting, and modifying text.
len()
o Example:
text = "Hello"
print(len(text)) # Output: 5
capitalize()
o Usage: Capitalizes the first character of the string and makes all other
characters lowercase.
o Example:
title()
o Example:
lower()
o Example:
text = "HELLO"
print(text.lower()) # Output: hello
upper()
o Usage: Converts all characters in the string to uppercase.
o Example:
text = "hello"
print(text.upper()) # Output: HELLO
count()
o Example:
find()
o Usage: Returns the lowest index where the substring is found, or -1 if not
found.
o Example:
index()
o Usage: Returns the lowest index where the substring is found, raises
ValueError if not found.
o Example:
endswith()
o Example:
startswith()
o Example:
text = "hello world"
print(text.startswith("hello")) # Output: True
isalnum()
o Usage: Returns True if all characters in the string are alphanumeric (letters
and numbers).
o Example:
text = "hello123"
print(text.isalnum()) # Output: True
isalpha()
o Example:
text = "hello"
print(text.isalpha()) # Output: True
isdigit()
o Example:
text = "12345"
print(text.isdigit()) # Output: True
islower()
o Example:
text = "hello"
print(text.islower()) # Output: True
isupper()
o Example:
text = "HELLO"
print(text.isupper()) # Output: True
isspace()
lstrip()
o Example:
rstrip()
o Example:
strip()
o Example:
replace()
o Example:
join()
o Usage: Joins elements of an iterable (e.g., list) into a single string with a
specified separator.
o Example:
partition()
o Usage: Splits the string into a 3-tuple containing the part before the separator,
the separator itself, and the part after.
o Example:
split()
o Example:
These methods and functions are essential for text processing and manipulation in Python,
making it easier to work with strings in a variety of scenarios.
In Python, a list is a versatile and powerful data structure that can hold an ordered collection
of items, which can be of different types—integers, strings, objects, or even other lists. Lists
are mutable, meaning you can change their content after they are created. They are defined
using square brackets [], with items separated by commas.
Example:
Indexing
Indexing in lists is used to access individual elements based on their position. Python uses
zero-based indexing, so the first item is at index 0, the second item at index 1, and so on. You
can also use negative indexing to access elements from the end of the list, where -1 refers to
the last item, -2 to the second last, and so forth.
Example:
List Operations
1. Concatenation
Concatenation is the operation of combining two lists into a single list. You use the +
operator to concatenate lists.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]
2. Repetition
Repetition allows you to create a list with repeated copies of its elements using the *
operator.
Example:
my_list = [1, 2, 3]
repeated_list = my_list * 3
print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
3. Membership
Membership checks if an element is in the list using the in keyword. It returns True if the
element is present and False otherwise.
Example:
4. Slicing
Slicing extracts a portion of the list. It uses the syntax list[start:stop], where start is
the index of the first element included in the slice, and stop is the index of the first element
excluded from the slice.
Example:
my_list = [0, 1, 2, 3, 4, 5]
sliced_list = my_list[1:4]
print(sliced_list) # Output: [1, 2, 3]
You can also omit the start or stop to slice from the beginning or to the end of the list.
Example:
The for loop is the most straightforward way to traverse a list. It iterates over each element
of the list, allowing you to perform operations with the item.
Example:
Output:
10
20
30
40
50
In this example, item represents each element in my_list, and the loop prints each element
in turn.
You can also traverse a list using a while loop by manually managing the index. This
approach gives you more control but requires you to handle the indexing and loop conditions
yourself.
Example:
Output:
10
20
30
40
50
Here, index starts at 0 and increases by 1 after each iteration, accessing each element by its
index.
For a more concise way to process each item in a list, you can use list comprehensions. This
is a compact way of generating lists based on existing ones and can also be used for simple
operations.
Example:
Output:
Using enumerate()
If you need both the index and the value of each element while traversing, enumerate() is a
handy built-in function. It returns both the index and the item in each iteration.
Example:
Output:
Index 0: apple
Index 1: banana
Index 2: cherry
Using these techniques, you can efficiently traverse and process lists in Python, adapting your
approach based on your specific needs and the task at hand.
1. len()
2. list()
Example:
my_string = "hello"
my_list = list(my_string)
print(my_list) # Output: ['h', 'e', 'l', 'l', 'o']
3. append()
Example:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
4. extend()
Purpose: Adds elements from an iterable (like a list) to the end of the list.
Example:
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
5. insert()
Example:
my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list) # Output: [1, 4, 2, 3]
6. count()
Example:
my_list = [1, 2, 2, 3, 2]
print(my_list.count(2)) # Output: 3
7. index()
Example:
my_list = [1, 2, 3, 2]
print(my_list.index(2)) # Output: 1
8. remove()
Example:
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
9. pop()
Purpose: Removes and returns the element at the specified position (or the last
element if no position is specified).
Example:
my_list = [1, 2, 3]
item = my_list.pop()
print(item) # Output: 3
print(my_list) # Output: [1, 2]
10. reverse()
Example:
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
11. sort()
Purpose: Sorts the elements of the list in place (modifies the original list).
Example:
my_list = [3, 1, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3]
12. sorted()
Purpose: Returns a new list that is sorted (does not modify the original list).
Example:
my_list = [3, 1, 2]
sorted_list = sorted(my_list)
print(sorted_list) # Output: [1, 2, 3]
print(my_list) # Output: [3, 1, 2]
13. min()
Example:
my_list = [4, 1, 7, 3]
print(min(my_list)) # Output: 1
14. max()
Example:
my_list = [4, 1, 7, 3]
print(max(my_list)) # Output: 7
15. sum()
Purpose: Returns the sum of all elements in the list (only works with numeric lists).
Example:
my_list = [1, 2, 3]
print(sum(my_list)) # Output: 6
These functions and methods provide a range of options for manipulating and analyzing lists,
making it easier to handle various data-processing tasks in your Python programs.
Nested Lists
Nested lists in Python are simply lists that contain other lists as their elements. They can be
thought of as a matrix or a table, where each cell or row is a list itself. This structure allows
you to represent more complex data arrangements and perform operations on multi-
dimensional data.
Basic Example
nested_list = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
In this example, nested_list contains three lists, each with three integers.
Accessing Elements
To access elements in a nested list, you need to specify the index of both the outer list and the
inner list. For example:
Modifying Elements
You can modify elements in a nested list just like you would with a regular list:
nested_list[0][1] = 20
print(nested_list) # Output: [[1, 20, 3], [4, 5, 6], [7, 8, 9]]
You can use nested loops to iterate over each element in a nested list. Here’s how you can
print every item:
Output:
1 20 3
4 5 6
7 8 9
Nested lists are commonly used to represent matrices (2D arrays) in Python. For instance, if
you're working with a grid or table of data, a nested list can help you store and manipulate
this data effectively.
Summary
Nested lists provide a powerful way to handle multi-dimensional data in Python. They offer
flexibility in representing complex data structures, making them useful for various
applications such as data analysis, matrix operations, and more.
Suggested Programs
Here are some suggested programs to work with lists in Python, focusing on finding
maximum, minimum, mean values, performing linear search, and counting the frequency of
elements:
Program:
Explanation:
The mean is calculated by dividing the sum of the numbers by the count of the
numbers.
2. Linear Search on a List of Numbers
Program:
Explanation:
The linear_search() function iterates through the list and checks if each element
matches the target value. It returns the index if found or -1 if not.
Program:
Explanation:
The Counter class from the collections module helps count the occurrences of
each element in the list. It returns a dictionary-like object where keys are list elements
and values are their counts.
Summary
These programs provide practical ways to work with lists in Python. Finding maximum,
minimum, and mean values helps analyze numeric data. Linear search is a basic searching
technique to locate elements, while counting frequencies can be useful for understanding the
distribution of values. These exercises build foundational skills for handling and processing
list data in various programming scenarios.
Dictionary
Introduction to Dictionaries
In Python, a dictionary is a built-in data type that stores data in key-value pairs. Think of it
like a real-world dictionary where you look up a word (key) to find its definition (value). This
structure allows for fast lookups, additions, and modifications of data.
Example of a Dictionary:
# Creating a dictionary
student = {
"name": "John Doe",
"age": 16,
"grade": "11th",
"subjects": ["Math", "Science", "English"]
}
In this dictionary:
"John Doe", 16, "11th", and ["Math", "Science", "English"] are their
respective values.
To access the values stored in a dictionary, you use the keys. Here’s how you can do it:
Example:
Explanation:
student["name"] retrieves the value associated with the key "name", which is "John
Doe".
Similarly, student["age"] gets the age, and student["subjects"] returns the list
of subjects.
Example:
In this example:
Summary
Dictionaries are a powerful tool in Python for storing and managing data in key-value pairs.
Accessing items is straightforward using the keys, and handling potential errors is easy with
methods like .get(). This flexibility makes dictionaries ideal for various applications, from
simple data storage to complex data manipulation tasks.
Mutability of a Dictionary
Dictionaries in Python are mutable, which means you can change their contents after they
have been created. This mutability allows you to add new key-value pairs, modify existing
ones, and even delete items as needed.
You can add new key-value pairs to a dictionary by simply assigning a value to a new key. If
the key doesn't already exist, it will be created.
Example:
print(student)
# Output: {'name': 'John Doe', 'age': 16, 'grade': '11th', 'subjects':
['Math', 'Science', 'English']}
In this example, the key "subjects" is added to the dictionary with its associated value
["Math", "Science", "English"].
To change the value associated with an existing key, simply assign a new value to that key.
Example:
print(student)
# Output: {'name': 'John Doe', 'age': 17, 'grade': '11th', 'subjects':
['Math', 'Science', 'English']}
Summary
Dictionaries in Python are versatile and allow for easy updates and additions. By leveraging
their mutable nature, you can dynamically manage and manipulate data. Adding new terms or
modifying existing items is straightforward, making dictionaries a flexible choice for various
programming tasks.
Traversing a Dictionary
Traversing a dictionary means iterating through its keys, values, or key-value pairs to access
or manipulate its contents. This is a common task when you need to process or display
dictionary data.
1. Traversing Keys
You can loop through the keys of a dictionary using a for loop. This allows you to access
each key and use it to get corresponding values.
Example:
# Define a dictionary
student = {
"name": "John Doe",
"age": 16,
"grade": "11th",
"subjects": ["Math", "Science", "English"]
}
# Traversing keys
for key in student:
print(f"Key: {key}")
In this example, the loop iterates through each key in the student dictionary and prints it.
2. Traversing Values
If you only need to access the values, you can loop through the dictionary’s values.
Example:
# Traversing values
for value in student.values():
print(f"Value: {value}")
To get both keys and values simultaneously, use the .items() method. This method returns a
view object that displays a list of tuples, each containing a key-value pair.
Example:
In this example, each tuple returned by .items() is unpacked into key and value, which are
then printed.
For more advanced operations, you can use dictionary comprehensions to create or modify
dictionaries based on traversal.
Example:
print(uppercased_dict)
# Output: {'NAME': 'John Doe', 'AGE': 16, 'GRADE': '11th', 'SUBJECTS':
['Math', 'Science', 'English']}
In this example, the dictionary comprehension creates a new dictionary where all keys are
converted to uppercase.
Python dictionaries come with a set of built-in functions and methods that make it easy to
work with key-value pairs. Here’s a rundown of the most commonly used ones:
1. len()
Example:
student = {"name": "John", "age": 16}
print(len(student)) # Output: 2
2. dict()
Creates a new dictionary. It can take keyword arguments or a list of key-value pairs.
Example:
3. keys()
Returns a view object that displays a list of all the keys in the dictionary.
Example:
keys = student.keys()
print(keys) # Output: dict_keys(['name', 'age'])
4. values()
Returns a view object that displays a list of all the values in the dictionary.
Example:
values = student.values()
print(values) # Output: dict_values(['John', 16])
5. items()
Returns a view object that displays a list of tuples, each containing a key-value pair.
Example:
items = student.items()
print(items) # Output: dict_items([('name', 'John'), ('age', 16)])
6. get()
Returns the value for the specified key if the key is in the dictionary. Otherwise, it returns
None or a default value if provided.
Example:
7. update()
Updates the dictionary with key-value pairs from another dictionary or from an iterable of
key-value pairs.
Example:
8. del
Example:
del student["age"]
print(student) # Output: {'name': 'John', 'grade': '11th', 'school': 'High
School'}
9. clear()
Example:
student.clear()
print(student) # Output: {}
10. fromkeys()
Example:
11. copy()
Example:
copy_dict = student.copy()
print(copy_dict) # Output: {'name': 'John', 'grade': '11th', 'school':
'High School'}
12. pop()
Removes a specified key and returns its value. If the key is not found, it raises a KeyError
unless a default value is provided.
Example:
name = student.pop("name")
print(name) # Output: John
print(student) # Output: {'grade': '11th', 'school': 'High School'}
13. popitem()
Removes and returns the last key-value pair from the dictionary as a tuple.
Example:
item = student.popitem()
print(item) # Output: ('school', 'High School')
print(student) # Output: {'grade': '11th'}
14. setdefault()
Returns the value of a key if it is in the dictionary. If not, it inserts the key with a specified
default value and returns that value.
Example:
15. max()
Returns the maximum key from the dictionary based on lexicographical order.
Example:
16. min()
Returns the minimum key from the dictionary based on lexicographical order.
Example:
17. sorted()
Example:
sorted_keys = sorted(student)
print(sorted_keys) # Output: ['grade']
Summary
Python dictionaries come equipped with a variety of built-in methods that simplify many
common tasks, from adding and updating items to accessing and manipulating data. Whether
you're looking to explore key-value pairs, make modifications, or clear the entire dictionary,
these functions and methods make handling dictionary data straightforward and efficient.
Suggested Programs
Here are two simple programs using dictionaries to tackle common tasks: counting characters
and managing employee data.
This program counts how often each character appears in a string and stores the counts in a
dictionary.
Example Program:
def count_characters(input_string):
# Create an empty dictionary to store character counts
char_count = {}
return char_count
Explanation:
The program uses a dictionary char_count to track how many times each character
appears.
It loops through the input_string, updating the count in the dictionary for each
character.
2. Create a Dictionary with Names of Employees, Their Salaries, and Access Them
This program creates a dictionary to store employee names and their salaries, and then
accesses this data.
Example Program:
Explanation:
When you use the import statement, you're telling Python to load a module so you can use
its functions, classes, or variables. For example:
import math
In this example:
You access functions in the math module using the dot notation (math.sqrt()),
where sqrt is a function that calculates the square root of a number.
Using From Statement to Import Specific Components
If you only need specific functions or variables from a module, you can use the from
<module> import <item> syntax. This approach makes your code cleaner and more
efficient by importing only what you need.
In this example:
from math import sqrt, pi imports only the sqrt function and pi constant from
the math module.
You can then use sqrt() and pi directly without prefixing them with math.
The math module in Python provides various mathematical functions and constants that make
it easier to perform complex calculations. By importing the math module, you gain access to
functions and constants such as pi, e, and mathematical functions like sqrt(), ceil(), and
sin(). Here’s a quick guide on how to use these features:
import math
Using Constants
Example:
import math
Using Functions
import math
Summary
The math module is a powerful toolkit for performing mathematical operations in Python. By
importing it, you can utilize constants like pi and e, and functions for arithmetic,
trigonometric, and other calculations. Whether you're solving complex equations or just need
basic mathematical operations, the math module simplifies the process.
Random Module
The random module includes functions to generate random numbers and perform random
operations. Here's a look at some of its useful functions:
random.random(): Returns a random floating-point number between 0.0 and 1.0.
Example:
import random
Example:
import random
Example:
import random
Statistics Module
The statistics module is used for statistical operations and includes functions to compute
various statistical metrics:
Example:
import statistics
Example:
import statistics
data = [1, 3, 5, 7, 9]
print("Median of data:", statistics.median(data))
# Output: Median of data: 5
statistics.mode(data): Returns the most frequently occurring value (mode) in the
data set. Note: If there's no unique mode, it raises a StatisticsError.
Example:
import statistics
data = [1, 1, 2, 3, 4]
print("Mode of data:", statistics.mode(data))
# Output: Mode of data: 1
Summary
The random and statistics modules are invaluable tools in Python for dealing with random
number generation and statistical calculations. The random module helps you generate
random numbers for simulations and games, while the statistics module lets you easily
compute common statistical measures like the mean, median, and mode. Whether you're
doing data analysis or just adding some randomness to your programs, these modules provide
a straightforward approach to handle these tasks.
Guido van Rossum created the Python programming language in the late 1980s. In contrast to
other popular languages such as C, C++, Java, and C#, Python strives to provide a simple but
powerful syntax. Python is used for software development at companies and organizations
such as Google, Yahoo, and NASA.
Simple Hello program: Python programs must be written with a particular structure. The
syntax must be correct, or the interpreter will generate error messages and not execute the
program. When we want to write a program, we use a text editor to write the Python
instructions into a file, which is called a script. By convention, Python scripts have names
that end with .py. For example, we will name our first program as “hello.py”.
IDLE is a simple Python integrated development environment available for Windows, Linux,
and Mac OS X. To open IDLE interactive shell “Goto start menu on windows -> open
IDLE”. You may type the above one-line Python program directly into IDLE and press enter
to execute the program. Since it does not provide a way to save the code you enter, the
interactive shell is not the best tool for writing larger programs. The IDLE interactive shell is
useful for experimenting with small snippets of Python code.
IDLE’s editor: IDLE has a built-in editor. From the IDLE menu, select New Window, Type
the text print(“This is my first program”) into the editor. You can save your program
using the Save option in the File menu. Save the code to a file named “hello.py”. The
extension .py is the extension used for Python source code. We can run the program from
within the IDLE editor by pressing the F5 function key or from the editor’s Run menu: Run -
> Run Module. The output appears in the IDLE interactive shell window.
This is a Python statement. A statement is a command that the interpreter executes. This
statement prints the message “This is my first program” on the screen. A statement is the
fundamental unit of execution in a Python program. Statements may be grouped into larger
chunks called blocks, and blocks can make up more complex statements.
The statement print(“This is my first program”) makes use of a built-in function named
“print”. Python has a variety of different kinds of statements that may be used to build
programs.
Simple Data-Types
A data type, in programming, is a classification that specifies which type of value a variable
has and what type of mathematical, relational or logical operations can be applied to it
without causing an error. A string, for example, is a data type that is used to classify text and
an integer is a data type used to classify whole numbers.
Some basic data types that python support are integer, float, string.
Integer (int): Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length. The number four (4) is an example of a numeric value. In mathematics, 4 is
an integer value. Integers are whole numbers, which means they have no fractional parts, and
they can be positive, negative, or zero. Examples of integers include 4, −19, 0, and −1005. In
contrast, 4.5 is not an integer, since it is not a whole number. Python supports a number of
numeric and non-numeric values. In particular, Python programs can use integer values. Let’s
take an example integer.py
X=10
Y=223313445534
Z=-987
Print(X)
Print(Y)
Print(Z)
Print(X+Y+Z)
In above program, there are three variable holding integer values in x,y, and z. Then there are
three print statements which will display the three integer variables and last print statement
will display addition of all the 3 numbers that are in the variables.
Float: Many computational tasks require numbers that have fractional parts. For example, to
compute the area of a circle given the circle’s radius, the value pi, or approximately 3.14159
is used. Python supports such non-integer numbers, and they are called floating point
numbers. The name implies that during mathematical calculations the decimal point can
move or “float” to various positions within the number to maintain the proper number of
significant digits. The Python name for the floating-point type is float. Let’s take an example
of float in this program we will calculate area of circle
PI=3.14
Radius=5.5
Area=PI*Radius*Radius
In the above example we are taking 3 float variables PI Radius and area. In a statement
Area=PI*Radius*radius, we are calculating the area of circle and putting the value in variable
area. Then in print statement, we are printing the area of circle with a message.
String: String literals in python are surrounded by either single quotation marks or double
quotation marks. ‘hello’ is the same as “hello”. String variable holds the text.
Let’s take an example in this example we will see how to print string variables and how to
take input from the user.
x=”hello”
print(“Enter text”)
y=input()
print(x,y)
In above program, there are 2 variables x and y. x is holding the string “hello” and y will take
text from the keyboard at run time and next line will print both the strings.