Python is a popular programming language because it is easy to read and write. It is used for many things like web development, data analysis, machine learning, and more.
Why Learn Python?
- Easy to Learn: Python uses simple syntax that looks like English.
- Versatile: You can use it for small scripts or big applications.
- AI Apps: The entire AI/ML ecosystem is based on python coding.
- Community Support: Many people use Python, so you can find help online.
Quick Example
Open a new notebook in Google Colab, type this code and run it:print("Hello, World!")
Variables
A variable is a container that stores a value. You can think of it as a label for data.Rules for Naming Variables:
- Variable names can include letters, numbers, and underscores (_).
- They cannot start with a number.
- Avoid using Python keywords (like if, for, while).
name = "John" # A string variable
age = 20 # An integer variable
is_student = True # A boolean variable
Data Types
- Integers (int) : These are the usual integers of arithmetic.
- Float (float) : Decimal point numbers.
- Strings (str) : Sequence of characters enclosed in quotes ('' or "")
- Boolean (bool) : These are either True or False. True and False are python keywords with a capital T and capital F, respectively.
- None : Represents the absence of any value.
x=42
type(x)
y="python"
type(y)
Simple Arithmetic Operations
You can perform various operations with variables, depending on their data type. Here are some examples for simple arithmetic operations for you to try in Google Colab:# Addition
a = 10
b = 5
result = a + b
print("Addition:", result) # Output: 15
# Subtraction
result = a - b
print("Subtraction:", result) # Output: 5
# Multiplication
result = a * b
print("Multiplication:", result) # Output: 50
# Division
result = a / b
print("Division:", result) # Output: 2.0
# Modulus (remainder)
result = a % b
print("Remainder:", result) # Output: 0
# Exponentiation (power)
result = a ** 2
print("Power:", result) # Output: 100
Simple String Operations
# Concatenation
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print("Full Name:", full_name) # Output: John Doe
# Repetition
greeting = "Hi! "
print(greeting * 3) # Output: Hi! Hi! Hi!
# Length of a string
message = "Hello, Python!"
print("Length of message:", len(message)) # Output: 14
Simple Comparison Operations
x = 10
y = 20
# Greater than
print(x > y) # Output: False
# Less than
print(x < y) # Output: True
# Equal to
print(x == y) # Output: False
# Not equal to
print(x != y) # Output: True
Decision Making : if-elif-else
if-elif-else statements are used in Python to make decisions based on conditions. Python checks the conditions one by one and executes the block of code for the first condition that is True.Here is a simple example (note the indentation):
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
else:
# Code to execute if all conditions are False
Key points:
- The if block is required, but elif and else are optional.
- Conditions are written as expressions that evaluate to True or False.
- Python uses indentation (spaces) to define the blocks of code.
number = 5
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
Functions
A function is a block of reusable code that performs a specific task. Using functions makes the code a lot more organised, clean and easy to understand. Functions also help to make your code modular, readable, and reusable.In Python, you define a function using the def keyword.
def function_name(parameters):
# Code block
return value # (optional)
Here:
- function_name: The name you use to call the function.
- parameters: Input values that the function can accept (optional).
- return: Sends a result back to the caller (optional).
def greet():
print("Hello! Welcome to Python.")
# Call the function
greet()
Example 2: A simple function with one input parameter
def greet_user(name):
print("Hello,", name)
# Call the function with an argument
greet_user("Alice")
Example 3: A simple function with return value
def add_numbers(a, b):
return a + b
# Call the function and store the result
result = add_numbers(5, 3)
print("The sum is:", result)
Example 4: A function to check even and odd
def check_even_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
# Call the function
print(check_even_odd(4)) # Output: Even
print(check_even_odd(7)) # Output: Odd
For Loops
A for loop in Python is used to repeat a block of code a specific number of times. It is commonly used to iterate over sequences like strings, ranges, or other iterable objects. Using for loops with the range() function:- The range() function generates a sequence of numbers, which is often used with for loops.
- range(stop): Generates numbers from 0 to stop - 1.
- range(start, stop): Generates numbers from start to stop - 1.
- range(start, stop, step): Generates numbers from start to stop - 1, incrementing by step.
for i in range(1, 6): # Generates numbers 1 to 5
print(i)
You can also combine for-loops with if-elif-else statements. Here is a code to print all even numbers between 1 and 10 (inclusive).
for num in range(1, 11): # Numbers from 1 to 10
if num % 2 == 0: # Check if the number is even
print(num)
Lists in Python
A list is a collection of items in Python. It allows you to store multiple values in a single variable. Lists are one of the most commonly used data structures because they are flexible and easy to use.Key features of lists:
- Ordered: Items in a list are stored in a specific order.
- Mutable: You can change the content of a list after creating it.
- Heterogeneous: Lists can contain items of different data types.
# A list of numbers
numbers = [1, 2, 3, 4, 5]
# A list of strings
fruits = ["apple", "banana", "cherry"]
# A mixed list
mixed = [10, "hello", 3.14, True]
# An empty list
empty = []
You can access items in a list using their index. Indexing starts at 0.
fruits = ["apple", "banana", "cherry"]
# Accessing items
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
# Accessing the last item
print(fruits[-1]) # Output: cherry
Lists are mutable, so you can change, add, or remove items.
numbers = [1, 2, 3, 4]
# Changing an item
numbers[1] = 20
print(numbers) # Output: [1, 20, 3, 4]
# Adding an item
numbers.append(5)
print(numbers) # Output: [1, 20, 3, 4, 5]
# Removing an item
numbers.remove(3)
print(numbers) # Output: [1, 20, 4, 5]
Iterating through a List using for loop
You can use a for loop to go through each item in a list.fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Here is a simple example to find the sum of a list of numbers:
# Find the sum of a list of numbers
numbers = [1, 2, 3, 4, 5]
# Initialize a variable to store the sum
total = 0
# Using a for loop to calculate the sum
for num in numbers:
total += num
print("Total Sum:", total)
Here is another simple example to find the largest in a list of numbers:
# Find the largest in a list of numbers
numbers = [10, 25, 7, 40, 18]
# Initialize a variable to store the largest number
largest = numbers[0] # Assume the first number is the largest
# Using a for loop to find the largest number
for num in numbers:
if num > largest:
largest = num
print("The largest number is:", largest)
Nested for loops
A nested for loop is when you have one for loop inside another. Here's a simple example that prints a multiplication table for numbers 1 to 3.# Outer loop for rows (1 to 3)
for i in range(1, 4):
# Inner loop for columns (1 to 3)
for j in range(1, 4):
print(i * j, end="\t") # Print the product and stay on the same line
print() # Move to the next line after each row
Dictionaries in Python
A dictionary is a collection of key-value pairs. It is an unordered, mutable data structure in Python. Each key is unique, and each key maps to a value. Dictionaries are useful for storing data that needs to be associated with a unique identifier (the key).Here is the basic syntax of a dictionary:
dictionary = {key1: value1, key2: value2, key3: value3}
Key Features of Dictionaries:
- Unordered: The items in a dictionary do not have a defined order.
- Mutable: You can add, remove, or change items after creating the dictionary.
- Key-Value Pairs: Each item is a pair where a key maps to a value.
dictionary[key1] #prints value1
Lets create a simple dictionary and print it:
# A dictionary with student information
student = {
"name": "Jack",
"age": 20,
"grade": "A"
}
# Accessing values by keys
print(student["name"]) # Output: Jack
print(student["age"]) # Output: 20
You can also add and change the items in a dictionary:
# A dictionary of a person's contact info
contact = {
"name": "Alice",
"phone": "123-456-7890"
}
# Adding a new key-value pair
contact["email"] = "alice@example.com"
# Updating an existing value
contact["phone"] = "987-654-3210"
# Printing the updated dictionary
print(contact)
Iterating over dictionaries using for loop
You can iterate over dictionaries using loops to access keys, values, or both.- To loop through all the keys in a dictionary, you can use the keys() method.
# A sample dictionary student = { "name": "John", "age": 20, "grade": "A" } # Loop through the keys for key in student.keys(): print(key)
- To loop through all the values in a dictionary, you can use the values() method.
# Loop through the values for value in student.values(): print(value)
- To loop through both keys and values at the same time, you can use the items() method.
# Loop through both keys and values for key, value in student.items(): print(key, ":", value)
String Operations
Strings in Python are sequences of characters and are used for text manipulation. Python provides several operations and built-in functions to work with strings.- Concatenation (+): Combine two or more strings into one.
greeting = "Hello" name = "Alice" message = greeting + " " + name print(message) # Output: Hello Alice
- Repetition (*): Repeat a string multiple times.
repeat = "Hi! " print(repeat * 3) # Output: Hi! Hi! Hi!
- Length (len()): Get the number of characters in a string.
text = "Python" print(len(text)) # Output: 6
- Slicing: Extract a part of a string using a range of indices.
text = "Hello World" print(text[0:5]) # Output: Hello print(text[6:]) # Output: World
- in Operator: Check if a substring exists in a string.
sentence = "I love programming" print("love" in sentence) # Output: True print("Python" in sentence) # Output: False
Common String Functions
- upper(): Convert all characters to uppercase.
text = "hello" print(text.upper()) # Output: HELLO
- lower(): Convert all characters to lowercase.
text = "HELLO" print(text.lower()) # Output: hello
- strip(): Remove leading and trailing spaces.
text = " Hello World " print(text.strip()) # Output: Hello World
- replace(old, new): Replace a substring with another.
text = "I like apples" print(text.replace("apples", "oranges")) # Output: I like oranges
- find(substring): Find the index of the first occurrence of a substring. Returns -1 if not found.
text = "Hello World" print(text.find("World")) # Output: 6 print(text.find("Python")) # Output: -1
- split(separator): Split a string into a list of substrings using a separator.
sentence = "Python is fun" words = sentence.split(" ") print(words) # Output: ['Python', 'is', 'fun']
- join(iterable): Join elements of an iterable into a single string.
words = ['Python', 'is', 'fun'] sentence = " ".join(words) print(sentence) # Output: Python is fun
- startswith(prefix): Check if the string starts with a given prefix.
text = "Python Programming" print(text.startswith("Python")) # Output: True
- endswith(suffix): Check if the string ends with a given suffix.
text = "Python Programming" print(text.endswith("Programming")) # Output: True