Navigation

Basic Syntax and Structure Variables If-Else Conditions Loops Functions Modules and Libraries Commonly used Modules

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

Variables

If-Else Conditions

If x is greater than 5, it will print "x is greater than 5".
x = 10 if x > 5: print("x is greater than 5") --------------------------------------- >> x is greater than 5

If it's not, nothing happens.
x = 1 if x > 5: print("x is greater than 5") --------------------------------------- >>
x = 1 if x > 5: print("x is greater than 5") --------------------------------------- >>
If y mod 2 equals 0, it will print "y is even".
y = 2 if y % 2 == 0: print("y is even") else: print("y is odd") --------------------------------------- >> y is even

Else 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
If the grade is more than 90, the program prints "A".
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

for number in range(1, 4): print(number) --------------------------------------- >> 1 >> 2 >> 3

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

word = 'Hello' for letter in word: print(letter) --------------------------------------- >> H >> e >> l >> l >> o

While 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

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


Using Built-in Modules

Modules like math 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 using pip.
# 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

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

The csv 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