top of page

Python: Getting Started

Python is a beginner-friendly and versatile language that brings your ideas to life. Its simplicity, extensive libraries, and real-world applications make it a great choice. Start with the basics, explore resources, and practice coding.

Hello World

print("Hello, World!")

# Output: Hello, World!

Code prints the string "Hello, World!"

Variables

age = 21  # age is type int

name = "Rumbaoa"  # name is type str

print(age) # Output: 21

1. declare your variables. 2. variage age is a type int 3. varible name is a type string

List

mylist = []

mylist.append(1)

mylist.append(2)

for item in mylist:

    print(item)  # Output: 1,2

1. A list is an ordered collection of elements. 2. Lists are denoted by square brackets ([ ]). 3. They can store multiple values of different data types. 4. Lists are mutable, allowing for modifications after creation. 5. Elements in a list can be accessed and manipulated using indexing and slicing. 6. Lists are a versatile and commonly used data structure in Python.

Dictionary

my_dict = {"key1": "value1", "key2": "value2"}

print(my_dict["key1"])  # Output: value1

1. A dictionary is an unordered collection of key-value pairs. 2. Denoted by curly braces ({}) and consist of key-value pairs separated by colons (:). 3. Keys within a dictionary must be unique and immutable (e.g., strings, numbers, or tuples). 4. Values within a dictionary can be of any data type. 5. Provides fast lookup and retrieval of values based on their associated keys. 6. Elements within a dictionary can be added, modified, or removed. 6. Used for organizing and manipulating data based on specific key-value relationships.

Tuple

# Creating a tuple

fruits = ('apple', 'banana', 'orange')

​

# Accessing elements in a tuple

print(fruits[0])  # Output: apple

print(fruits[1])  # Output: banana

print(fruits[2])  # Output: orange

1. A tuple is an ordered collection of elements. 2. Denoted by parentheses (). 3. Are immutable, meaning their elements cannot be modified after creation. 4. Elements within a tuple can be of different data types. 5. Tuples can store multiple values and are useful for grouping related data. 6. Used when you want to ensure data integrity and prevent accidental modifications. 7. Supports indexing and slicing to access individual elements. 8. Tuples are more memory-efficient compared to lists and can be used as keys in dictionaries.

Arithmetic Operations

# Addition

result = 10 + 10

print(result) # Output: 20

 

# Subtraction

result = 10 - 5

print(result) # Output: 5

 

# Multiplication

result = 10 * 3

print(result) # Output: 30

​

# Division

result = 10 / 2

print(result) # Output: 5.0

​

# Floor Division

result = 10 // 4

print(result) # Output: 2

 

# Modulo

result = 10 % 3

print(result) # Output: 1

 

# Exponentiation

result = 10 ** 2

print(result) # Output: 100

1. Addition: + operator adds two numbers. 2. Subtraction: - operator subtracts one number from another. 3. Multiplication: * operator multiplies two numbers. 4. Division: / operator divides one number by another, yielding a float result. 5. Floor Division: // operator divides one number by another, yielding an integer result (rounding down). 6. Modulo: % operator returns the remainder of the division between two numbers. 7. Exponentiation: ** operator raises one number to the power of another.

Logic Operator

# Logical Operators Example 

num1, num2 = 10,

​

# Using logical operators 

if num1 > num2:

    print("num1 is greater than num2."

elif num2 > num1: 

    print("num2 is greater than num1.")

else

    print("num1 and num2 are equal.")

​

Output:

num1 is greater than num2.

1. and operator: Returns True if both operands are True, otherwise returns False. 2. or operator: Returns True if at least one of the operands is True, otherwise returns False. 3. not operator: Returns the inverse of the operand's logical value. If the operand is True, not returns False, and vice versa.

f-string

# Simple f-string example

age = 25

 

# f-string to create a formatted string

message = f"You are {age} years old." print(message)

​

Output:

You are 25 years old.

1. f-strings are a way to format and embed expressions inside string literals. 2. Denoted by the prefix "f" followed by the string enclosed in quotation marks. 3. Expressions within f-strings are enclosed in curly braces {} and evaluated during runtime. 4. They allow direct insertion of variables, expressions, or function calls into strings.

If Else

# Simple if/else statement example

num = 10

 

if num > 0:

    print("The number is positive.")

else:

    print("The number is non-positive.")

​

Output:

The number is positive.

1. The if/else statement allows control of the flow of your program based on a condition. 2. The if statement evaluates a condition and executes a block of code if the condition is true. 3. The else statement provides an alternative block of code to execute when the if condition is false. 4. Only one of the code blocks (either the if block or the else block) is executed, based on the condition.

For Loop

fruits = ["apple", "banana", "cherry"]

​

for fruit in fruits:

    print(fruit)

​

Output:

apple

banana

cherry

1. The for loop is used to iterate over a sequence of elements, such as a list or a string. 2. It executes a block of code for each item in the sequence until the sequence is exhausted.

While Loop

count = 0

while count < 5:

    print(count)

    count += 1

​

Output:

 0

 1

 2

 3

 4

1. The while loop is used to repeatedly execute a block of code as long as a certain condition is true. 2. It continues executing the code until the condition becomes false.

Nested Loop

i = 1

while i <= 3:

    for j in range(1, 4):

        print(i * j, end=' ')

    print()

    i += 1

​

Output:

1 2 3

2 4 6

3 6 9

1. A nested loop is a loop inside another loop. 2. It is used to perform iterations within iterations, executing the inner loop's code multiple times for each iteration of the outer loop.

Data Types

# Integer

age = 25

 

# Float

pi = 3.14

 

# String

name = "John Doe"

​

# Boolean

is_student = True

​

# List

numbers = [1, 2, 3, 4, 5]

fruits = ["apple", "banana", "cherry"]

 

# Tuple

coordinates = (10, 20)

person = ("John", 25, True)

 

# Dictionary

student = {"name": "Alice", "age": 22}

​

# Set

unique_numbers = {1, 2, 3, 4, 5}

unique_fruits = set(["apple", "banana", "cherry"])

 

# Printing the values

print(age)

print(pi)

print(name)

print(is_student)

print(numbers)

print(fruits)

print(coordinates)

print(person)

print(student)

print(unique_numbers)

print(unique_fruits)

​

Output:

25

3.14

John Doe

True

[1, 2, 3, 4, 5]

['apple', 'banana', 'cherry']

(10, 20)

('John', 25, True)

{'name': 'Alice', 'age': 22}

{1, 2, 3, 4, 5}

{'apple', 'cherry', 'banana'}

1. Integer (int): Represents whole numbers, such as 1, 10, -5, etc. 2. Float (float): Represents decimal numbers, such as 3.14, 2.5, -0.75, etc. 3. String (str): Represents a sequence of characters enclosed in quotes, such as "Hello", 'Python', "42", etc. 4. Boolean (bool): Represents either True or False. 5. List (list): Represents an ordered collection of items enclosed in square brackets, such as [1, 2, 3], ['apple', 'banana'], [1, 'hello', True], etc. 6. Tuple (tuple): Represents an ordered, immutable collection of items enclosed in parentheses, such as (1, 2, 3), ('apple', 'banana'), (1, 'hello', True), etc. 7. Dictionary (dict): Represents an unordered collection of key-value pairs enclosed in curly braces, such as {'name': 'John', 'age': 25}, {'fruit': 'apple', 'color': 'red'}, etc. 8. Set (set): Represents an unordered collection of unique elements enclosed in curly braces or created using the set() function, such as {1, 2, 3}, {'apple', 'banana'}, set([1, 2, 3]), etc.

File Handling

# File Handling with "with open"

file_path = "example.txt"

 

# Reading from a file

with open(file_path, "r") as file:

    content = file.read()

    print(content)

 

# Writing to a file

with open(file_path, "w") as file:

    file.write("Hello, World!")

 

# Appending to a file

with open(file_path, "a") as file:

    file.write("\nThis is an appended line.")

​

1. The "with" statement is used for resource management, ensuring that resources are properly managed and released after their usage. 2. "with open" is a specific use case of the "with" statement that is commonly used for file handling operations. 3. It simplifies the process of working with files by automatically handling the opening and closing of the file. 4. The "open" function is used to open a file and return a file object. 5. The file object provides various methods and attributes to read, write, and manipulate the contents of the file. 6. When using "with open", the file is automatically closed at the end of the block, even if exceptions occur.

bottom of page