Welcome to the Introduction of Python
Python is a beginner-friendly programming language with simple syntax and powerful libraries, making it ideal for tasks like data analysis, web development, and automation. It’s perfect for new learners to focus on creativity and problem-solving while exploring endless possibilities.
Basic Syntax and Structure
- Python uses indentation to define blocks of code (e.g., loops, functions).
- Statements in Python end without a semicolon.
- Python code is clean and straightforward to write and read.
- People use a style guide for writing clean, readable, and consistent Python code.
- It improve readability and maintainability of Python projects.
- It provides recommendations for formatting Python code, such as indentation, naming conventions, and line length.
- For more details
- Basic Arithmetic Operators
- Relational and Logical Operators
| Operator | Type | Description | Example | Output |
|---|---|---|---|---|
| > | Relational | Greater than | 5 > 3 | True |
| < | Relational | Less than | 3 < 5 | True |
| >= | Relational | Greater than or equal to | 5 >= 5 | True |
| <= | Relational | Less than or equal to | 3 <= 5 | True |
| == | Relational | Equal to | 5 == 5 | True |
| != | Relational | Not equal to | 5 != 3 | True |
| and | Logical | Returns True if both conditions are True | (5 > 3) and (4 > 2) | True |
| or | Logical | Returns True if at least one condition is True | (5 > 3) or (4 < 2) | True |
| not | Logical | Reverses the Boolean value | not (5 > 3) | False |
| Operator | Type | Description | Example | Output |
|---|---|---|---|---|
| > | Relational | Greater than | 5 > 3 | True |
| < | Relational | Less than | 3 < 5 | True |
| >= | Relational | Greater than or equal to | 5 >= 5 | True |
| <= | Relational | Less than or equal to | 3 <= 5 | True |
| == | Relational | Equal to | 5 == 5 | True |
| != | Relational | Not equal to | 5 != 3 | True |
| and | Logical | Returns True if both conditions are True | (5 > 3) and (4 > 2) | True |
| or | Logical | Returns True if at least one condition is True | (5 > 3) or (4 < 2) | True |
| not | Logical | Reverses the Boolean value | not (5 > 3) | False |
Variables
- Integers (int): 10, -5
- Floats (float): 3.14, -0.5
- Strings (str): "Hello", 'World'
- Booleans (bool): True, False
If-Else Conditions
- The
ifstatement checks a condition. If the condition is true, the code inside it runs. - If it's false, the program skips the if block.
x = 10
if x > 5:
print("x is greater than 5")
---------------------------------------
>> x is greater than 5If it's not, nothing happens.
x = 1
if x > 5:
print("x is greater than 5")
---------------------------------------
>> - The
if-elsestatement adds a backup plan. - If the condition in if is false, the code in the
elseblock runs.
x = 1
if x > 5:
print("x is greater than 5")
---------------------------------------
>> y = 2
if y % 2 == 0:
print("y is even")
else:
print("y is odd")
---------------------------------------
>> y is evenElse y mod 2 not equals 0, it will print "y is odd".
y = 3
if y % 2 == 0:
print("y is even")
else:
print("y is odd")
---------------------------------------
>> y is odd- The
if-elif-elsestatement checks multiple conditions in order. - Once it finds a condition that is true, it runs the matching block of code and skips the rest.
- If none of the conditions are true, the
elseblock runs.
grade = 100
if grade >= 90:
print("A")
elif grade >= 70:
print("B")
else:
print("Fail")
---------------------------------------
>> A
Else-if (Elif) the grade is more than 70 but less than or equal to 90, the program prints "B".
grade = 85
if grade >= 90:
print("A")
elif grade >= 70:
print("B")
else:
print("Fail")
---------------------------------------
>> B
Else the grade is less than 70, the program prints "Fail".
grade = 50
if grade >= 90:
print("A")
elif grade >= 70:
print("B")
else:
print("Fail")
---------------------------------------
>> Fail
Loops
For Loops
- A for loop repeats code for each item in a collection (like a list, range, or string).
- It picks one item at a time and runs the code block for each.
for number in range(1, 4):
print(number)
---------------------------------------
>> 1
>> 2
>> 3fruits = ["apple", "banana"]
for fruit in fruits:
print(fruit)
---------------------------------------
>> apple
>> bananaword = 'Hello'
for letter in word:
print(letter)
---------------------------------------
>> H
>> e
>> l
>> l
>> oWhile Loops
- A while loop repeats code as long as a condition is true.
- It checks the condition before running the code block.
- Make sure to update variables inside the loop to avoid infinite loops!
count = 1
while count <= 3:
print(count)
count += 1
---------------------------------------
>> 1
>> 2
>> 3
number = 5
while number > 0:
print(number)
number -= 1
---------------------------------------
>> 5
>> 4
>> 3
>> 2
>> 1
word = "Python"
index = 0
while index < len(word):
print(word[index])
index += 1
---------------------------------------
>> P
>> y
>> t
>> h
>> o
>> n
Functions
- A function is a block of code that runs when it is called.
- Functions can accept input through parameters and return output.
- They help organize code and avoid repetition.
Defining and Calling Functions
If a function is called, it executes its code block.def greet():
print("Hello, world!")
greet()
---------------------------------------
>> Hello, world!
Functions with Parameters
Functions can take arguments as input to customize their behavior.def greet(name):
print(f"Hello, {name}!")
greet("Alice")
---------------------------------------
>> Hello, Alice!
Functions with Return Values
A function can return a value using the `return` keyword.def add(a, b):
return a + b
result = add(5, 3)
print(result)
---------------------------------------
>> 8
Using Default Parameters
Functions can have default values for parameters.def greet(name="Guest"):
print(f"Hello, {name}!")
greet()
greet("Alice")
---------------------------------------
>> Hello, Guest!
>> Hello, Alice!
Using Functions in Loops
Functions can be used inside loops for repeated actions.def square(num):
return num * num
for i in range(1, 4):
print(square(i))
---------------------------------------
>> 1
>> 4
>> 9
Modules and Libraries
- A module is a file containing Python code that can be reused in other programs.
- A library is a collection of pre-written modules for performing specific tasks.
- You can use the
importstatement to access a module or library.
Using Built-in Modules
Modules likemath provide additional functionality.
import math
print(math.sqrt(16))
print(math.pi)
---------------------------------------
>> 4.0
>> 3.141592653589793
Using Custom Modules (OPTIONAL)
You can create your own modules and import them.# In file mymodule.py
def greet(name):
return f"Hello, {name}!"
# In your main program
import mymodule
print(mymodule.greet("Alice"))
---------------------------------------
>> Hello, Alice!
Installing and Using Libraries (OPTIONAL)
Third-party libraries can be installed usingpip.
# Install requests library
# pip install requests
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
---------------------------------------
>> 200
Using Aliases
You can use an alias to simplify module names.import math as m
print(m.sqrt(25))
---------------------------------------
>> 5.0
Importing Specific Functions
You can import only specific functions from a module.from math import sqrt, pi
print(sqrt(49))
print(pi)
---------------------------------------
>> 7.0
>> 3.141592653589793
Combining Modules
Modules can work together for more complex tasks.import math
import random
radius = random.randint(1, 10)
area = math.pi * radius ** 2
print(f"Radius: {radius}, Area: {area}")
---------------------------------------
>> Radius: 7, Area: 153.93804002589985
Commonly used Modules
- Some modules like
math,csv, andjsonare built into Python. - Others, like third-party libraries, can be installed with
pip. - However, during your practicals you would only be using built in modules
- The
flaskandsqlite3modules will be discssed in practical
Using the math Module
The math module provides mathematical functions.
import math
print(math.sqrt(16)) # Square root
print(math.factorial(5)) # Factorial
print(math.pi) # Value of pi
---------------------------------------
>> 4.0
>> 120
>> 3.141592653589793
Using the random Module
The random module generates random numbers and selects random items.
import random
print(random.randint(1, 10)) # Random integer between 1 and 10
print(random.choice(["apple", "banana", "cherry"])) # Random choice
---------------------------------------
>> 7
>> banana
Using split to Break Strings
The split() method splits a string into parts based on a delimiter.
text = "apple,banana,cherry"
fruits = text.split(",") # Split by comma
print(fruits)
line = "Hello World"
words = line.split() # Split by whitespace
print(words)
---------------------------------------
>> ['apple', 'banana', 'cherry']
>> ['Hello', 'World']
Using readlines to Read Files
The readlines() method reads all lines from a file into a list.
with open("example.txt", "w") as file:
file.write("Hello\nWorld\nPython")
with open("example.txt", "r") as file: #write - w, read - r, ammend - a
lines = file.readlines()
print(lines)
---------------------------------------
>> ['Hello\n', 'World\n', 'Python']
The
csv module helps in reading and writing CSV files.
import csv
with open("data.csv", "w") as file: #write - w, read - r, ammend - a
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
---------------------------------------
>> ['Name', 'Age']
>> ['Alice', '25']
Using a Custom Delimiter in CSV
Thecsv module allows you to set a custom delimiter for separating fields.
import csv
# Writing a CSV with a semicolon delimiter
with open("data_semicolon.csv", "w", newline="") as file:
writer = csv.writer(file, delimiter=";")
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
writer.writerow(["Bob", 30])
# Reading the CSV with a semicolon delimiter
with open("data_semicolon.csv", "r") as file:
reader = csv.reader(file, delimiter=";")
for row in reader:
print(row)
---------------------------------------
>> ['Name', 'Age']
>> ['Alice', '25']
>> ['Bob', '30']
Using the json Module
The json module is used to work with JSON data.
import json
data = {"name": "Alice", "age": 25}
json_string = json.dumps(data) # Convert to JSON string
print(json_string)
parsed_data = json.loads(json_string) # Convert back to dictionary
print(parsed_data["name"])
---------------------------------------
>> {"name": "Alice", "age": 25}
>> Alice