Python basics

From A Technological Wiki
Revision as of 18:31, 26 October 2025 by Root (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Basic python course

This tutorial provides a quick introduction to Python programming. It covers basic data types, control structures, and common programming concepts in Python.

Numbers and variables

Numbers represent integer or decimal values that can be used in mathematical operations.

Variables are names that store values in memory.

3 + 5      # Addition
3 - 2      # Subtraction
3 * 4      # Multiplication
5 / 2      # Division (returns 2.5)
5 % 2      # Modulus (remainder)

You can store and reuse values using variables:

a = 5
b = 3
result = a + b
print(result)  # 8

Strings

Strings are sequences of characters, such as text or symbols.

They can be enclosed in single (`'`) or double (`"`) quotes.

greeting = "Hello"
name = 'Alice'
print(greeting, name)

You can combine strings and variables using format():

name = "Antonio"
age = 30
print("My name is {} and I am {} years old".format(name, age))

Access characters using indices:

word = "football"
print(word[0])   # 'f'
print(word[-1])  # 'l'
print(word[1:4]) # 'oot'

Lists

A list is an ordered collection of elements that can contain numbers, strings, or other objects.

Lists are mutable, meaning you can add, change, or remove elements.

letters = ['a', 'b', 'c']
letters.append('d')
print(letters)  # ['a', 'b', 'c', 'd']
print(letters[0])   # 'a'
print(letters[-1])  # 'd'

Lists can also contain other lists (nested lists):

nested = [1, 2, 3, ['a', 'b', 'c']]
print(nested[3][0])  # 'a'

Dictionaries

A dictionary stores data as key-value pairs.

Each key must be unique, and it’s used to retrieve its corresponding value.

person = {"name": "Antonio", "age": 30}
print(person["name"])  # Antonio
print(person["age"])   # 30

Booleans

Booleans represent logical values: either True or False.

They are commonly used in conditions and comparisons.

a = 5
b = 6
print(a == b)  # False
print(a < b)   # True

Tuples

A tuple is a collection of elements similar to a list, but immutable, meaning it cannot be changed after creation.

t = (1, 2, 3)
print(t[0])  # 1
# t[0] = 5 → Error (cannot modify tuple)

Sets

A set is an unordered collection of unique elements.

It automatically removes duplicates and can be used for mathematical operations like unions or intersections.

numbers = {1, 2, 2, 3}
print(numbers)  # {1, 2, 3}

Convert a list to a set to remove duplicates:

nums = [1, 2, 2, 3, 3]
unique = set(nums)
print(unique)

Comparison operators

Comparison operators are used to compare two values and return a boolean result (True or False).

a = 5
b = 4
print(a == b)  # False
print(a != b)  # True
print(a > b and b < 10)  # True
print(a < b or b < 10)   # True

Conditional statements

Conditional statements allow the program to make decisions based on certain conditions.

text = "Hello, good morning, my name is Antonio"
print(text.upper())    # All uppercase
print(text.lower())    # All lowercase
print(text.split())    # Split by spaces
print(text.split(',')) # Split by comma

Use `if`, `elif`, and `else` to control the flow of the program.

a = 5
b = 7

if a == b:
    print("a equals b")
elif a > b:
    print("a is greater than b")
else:
    print("a is less than b")

For Loops

A for loop is used to iterate over a sequence such as a list, string, or range of numbers.

numbers = [1, 2, 3, 4, 5]
for n in numbers:
    print(n * 5)

While Loops

A while loop repeats a block of code as long as a specified condition is true.

number = 1
while number < 5:
    print(number)
    number += 1

Range Function

The range() function generates a sequence of numbers.

It is commonly used in loops to define how many times to iterate.

for x in range(2, 6):
    print(x)
# Output: 2, 3, 4, 5

List Comprehensions

List comprehensions provide a concise way to create new lists from existing ones.

numbers = [1, 2, 3, 4, 5]
doubles = [n * 2 for n in numbers]
print(doubles)

Functions

A function is a reusable block of code that performs a specific task.

Functions can receive parameters and return results.

def greet(name):
    """Prints a personalized greeting."""
    print("Hello, " + name)

greet("Antonio")

def add(a, b):
    """Returns the sum of two numbers."""
    return a + b

print(add(2, 3))

Map Function

The map() function applies another function to each item in an iterable (e.g., list) and returns the results.

def multiply(x):
    return x * 2

numbers = [1, 2, 3]
doubled = list(map(multiply, numbers))
print(doubled)

Lambda Functions

A lambda function is an anonymous, one-line function often used for short operations.

numbers = [1, 2, 3]
tripled = list(map(lambda x: x * 3, numbers))
print(tripled)

Filter Function

The filter() function selects elements from a sequence that meet a given condition.

numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)

String Methods

String methods are built-in functions that allow you to manipulate and analyze text.

text = "Hello, good morning, my name is Antonio"
print(text.upper())    # All uppercase
print(text.lower())    # All lowercase
print(text.split())    # Split by spaces
print(text.split(',')) # Split by comma