Python basics: Difference between revisions
Created page with "= 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. <syntaxhighlight lang="python"> 3 + 5 # Addition 3 - 2 # Subtraction 3 * 4 # Multiplicati..." |
No edit summary |
||
| Line 251: | Line 251: | ||
print(text.split(',')) # Split by comma | print(text.split(',')) # Split by comma | ||
</syntaxhighlight> | </syntaxhighlight> | ||
---- | |||
= What is a module and why use it? = | |||
A '''module''' in Python is a file that contains reusable code - such as functions, classes, and variables — that can be imported into other scripts. | |||
Modules help organize code, avoid repetition, and provide specialized tools for different tasks. | |||
= The NumPy Module = | |||
'''NumPy''' is a powerful '''linear algebra library''' Python module for working with '''vectors''', '''matrix''', and '''arrays'''. | |||
It is widely used for '''scientific computing''', '''data analysis''', and '''machine learning''' because it performs mathematical operations extremely fast. | |||
<syntaxhighlight lang="python"> | |||
import numpy as np | |||
</syntaxhighlight> | |||
This line imports the '''NumPy module''' and gives it the short alias '''np''', so we can call its functions like `np.array()` or `np.arange()`. | |||
== Installing NumPy == | |||
<syntaxhighlight lang="bash"> | |||
pip install numpy | |||
</syntaxhighlight> | |||
== Creating Arrays == | |||
To start, import NumPy: | |||
<syntaxhighlight lang="python"> | |||
import numpy as np | |||
</syntaxhighlight> | |||
You can create a 1D array (vector) from a list: | |||
<syntaxhighlight lang="python"> | |||
my_list = [1, 2, 3, 4] | |||
array = np.array(my_list) | |||
print(array) | |||
# [1 2 3 4] | |||
</syntaxhighlight> | |||
You can also create a 2D array (matrix) from a list of lists: | |||
<syntaxhighlight lang="python"> | |||
list2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] | |||
matrix = np.array(list2) | |||
print(matrix) | |||
</syntaxhighlight> | |||
== Array generation functions == | |||
NumPy offers several ways to generate arrays automatically. | |||
=== np.arange() === | |||
Creates a range of numbers. | |||
<syntaxhighlight lang="python"> | |||
import numpy as np | |||
np.arange(5) # [0 1 2 3 4] | |||
np.arange(2, 10) # [2 3 4 5 6 7 8 9] | |||
np.arange(2, 10, 2) # [2 4 6 8] | |||
</syntaxhighlight> | |||
=== np.zeros() and np.ones() === | |||
Generate arrays filled with zeros or ones. | |||
<syntaxhighlight lang="python"> | |||
np.zeros((2, 4)) # 2 rows, 4 columns of zeros | |||
np.ones((3, 3)) # 3x3 matrix of ones | |||
</syntaxhighlight> | |||
=== np.linspace() === | |||
Creates evenly spaced numbers between two values. | |||
<syntaxhighlight lang="python"> | |||
np.linspace(3, 9, 5) | |||
# [3. 4.5 6. 7.5 9.] | |||
</syntaxhighlight> | |||
=== np.eye() === | |||
Creates an '''identity matrix''' (ones on the diagonal, zeros elsewhere). | |||
<syntaxhighlight lang="python"> | |||
np.eye(5) | |||
</syntaxhighlight> | |||
== Random numbers == | |||
NumPy’s random module can generate random values for testing or simulations. | |||
=== np.random.rand() === | |||
Generates random numbers between 0 and 1 (uniform distribution). | |||
<syntaxhighlight lang="python"> | |||
np.random.rand(2, 3) | |||
</syntaxhighlight> | |||
=== np.random.randn() === | |||
Generates random numbers from a '''normal (Gaussian)''' distribution. | |||
<syntaxhighlight lang="python"> | |||
np.random.randn(4, 5) | |||
</syntaxhighlight> | |||
=== np.random.randint() === | |||
Generates random integers between two values. | |||
<syntaxhighlight lang="python"> | |||
np.random.randint(1, 20) # One random integer | |||
np.random.randint(1, 20, 5) # Array of 5 random integers | |||
</syntaxhighlight> | |||
== Reshaping arrays == | |||
You can change the shape (rows and columns) of an array using '''reshape()''', as long as the total number of elements matches. | |||
<syntaxhighlight lang="python"> | |||
arr = np.random.randint(1, 100, 25) | |||
matrix = arr.reshape(5, 5) | |||
print(matrix) | |||
</syntaxhighlight> | |||
== Maximum, minimum and index positions == | |||
Use these functions to find key values and their positions in arrays. | |||
<syntaxhighlight lang="python"> | |||
arr = np.random.randint(1, 100, 50) | |||
print(arr.max()) # Maximum value | |||
print(arr.argmax()) # Index of maximum | |||
print(arr.min()) # Minimum value | |||
print(arr.argmin()) # Index of minimum | |||
</syntaxhighlight> | |||
== Indexing and slicing == | |||
Access individual or multiple elements of arrays using indices. | |||
=== One-Dimensional Arrays === | |||
<syntaxhighlight lang="python"> | |||
arr = np.arange(0, 10) | |||
print(arr[0]) # First element | |||
print(arr[-1]) # Last element | |||
print(arr[2:5]) # Slice from index 2 to 4 | |||
</syntaxhighlight> | |||
Make copies safely: | |||
<syntaxhighlight lang="python"> | |||
arr2 = arr.copy() | |||
arr2[0] = 100 | |||
print(arr) # Original unchanged | |||
</syntaxhighlight> | |||
=== Two-dimensional arrays === | |||
Access elements by [row, column]. | |||
<syntaxhighlight lang="python"> | |||
matrix = np.array([[1,2,3],[4,5,6],[7,8,9]]) | |||
print(matrix[0, 0]) # 1 | |||
print(matrix[1, 2]) # 6 | |||
print(matrix[:, 0]) # All rows, first column | |||
print(matrix[:2, :2]) # Top-left 2x2 submatrix | |||
</syntaxhighlight> | |||
== Conditional selection == | |||
You can select elements based on conditions. | |||
<syntaxhighlight lang="python"> | |||
arr = np.arange(0, 10) | |||
print(arr[arr > 5]) # Elements greater than 5 | |||
print(arr[arr % 2 == 0]) # Even elements | |||
</syntaxhighlight> | |||
== Array operations == | |||
You can perform arithmetic directly on arrays; operations are applied element-wise. | |||
<syntaxhighlight lang="python"> | |||
arr = np.arange(0, 10) | |||
print(arr + 10) | |||
print(arr * 2) | |||
print(arr - arr) | |||
</syntaxhighlight> | |||
Between two arrays: | |||
<syntaxhighlight lang="python"> | |||
a = np.arange(0, 10) | |||
b = np.arange(5, 15) | |||
print(b - a) | |||
</syntaxhighlight> | |||
== Common mathematical functions == | |||
NumPy provides built-in math functions. | |||
<syntaxhighlight lang="python"> | |||
arr = np.arange(0, 10) | |||
print(np.sqrt(arr)) # Square root | |||
print(np.max(arr)) # Maximum | |||
print(np.min(arr)) # Minimum | |||
</syntaxhighlight> | |||
[[Category:KC IT]] | [[Category:KC IT]] | ||
Revision as of 15:15, 21 October 2025
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) # 8Strings
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"]) # 30Booleans
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) # TrueTuples
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) # TrueConditional 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 commaUse `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 += 1Range 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, 5List 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 commaWhat is a module and why use it?
A module in Python is a file that contains reusable code - such as functions, classes, and variables — that can be imported into other scripts. Modules help organize code, avoid repetition, and provide specialized tools for different tasks.
The NumPy Module
NumPy is a powerful linear algebra library Python module for working with vectors, matrix, and arrays. It is widely used for scientific computing, data analysis, and machine learning because it performs mathematical operations extremely fast.
import numpy as npThis line imports the NumPy module and gives it the short alias np, so we can call its functions like `np.array()` or `np.arange()`.
Installing NumPy
pip install numpyCreating Arrays
To start, import NumPy:
import numpy as npYou can create a 1D array (vector) from a list:
my_list = [1, 2, 3, 4]
array = np.array(my_list)
print(array)
# [1 2 3 4]You can also create a 2D array (matrix) from a list of lists:
list2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix = np.array(list2)
print(matrix)Array generation functions
NumPy offers several ways to generate arrays automatically.
np.arange()
Creates a range of numbers.
import numpy as np
np.arange(5) # [0 1 2 3 4]
np.arange(2, 10) # [2 3 4 5 6 7 8 9]
np.arange(2, 10, 2) # [2 4 6 8]np.zeros() and np.ones()
Generate arrays filled with zeros or ones.
np.zeros((2, 4)) # 2 rows, 4 columns of zeros
np.ones((3, 3)) # 3x3 matrix of onesnp.linspace()
Creates evenly spaced numbers between two values.
np.linspace(3, 9, 5)
# [3. 4.5 6. 7.5 9.]np.eye()
Creates an identity matrix (ones on the diagonal, zeros elsewhere).
np.eye(5)Random numbers
NumPy’s random module can generate random values for testing or simulations.
np.random.rand()
Generates random numbers between 0 and 1 (uniform distribution).
np.random.rand(2, 3)np.random.randn()
Generates random numbers from a normal (Gaussian) distribution.
np.random.randn(4, 5)np.random.randint()
Generates random integers between two values.
np.random.randint(1, 20) # One random integer
np.random.randint(1, 20, 5) # Array of 5 random integersReshaping arrays
You can change the shape (rows and columns) of an array using reshape(), as long as the total number of elements matches.
arr = np.random.randint(1, 100, 25)
matrix = arr.reshape(5, 5)
print(matrix)Maximum, minimum and index positions
Use these functions to find key values and their positions in arrays.
arr = np.random.randint(1, 100, 50)
print(arr.max()) # Maximum value
print(arr.argmax()) # Index of maximum
print(arr.min()) # Minimum value
print(arr.argmin()) # Index of minimumIndexing and slicing
Access individual or multiple elements of arrays using indices.
One-Dimensional Arrays
arr = np.arange(0, 10)
print(arr[0]) # First element
print(arr[-1]) # Last element
print(arr[2:5]) # Slice from index 2 to 4Make copies safely:
arr2 = arr.copy()
arr2[0] = 100
print(arr) # Original unchangedTwo-dimensional arrays
Access elements by [row, column].
matrix = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(matrix[0, 0]) # 1
print(matrix[1, 2]) # 6
print(matrix[:, 0]) # All rows, first column
print(matrix[:2, :2]) # Top-left 2x2 submatrixConditional selection
You can select elements based on conditions.
arr = np.arange(0, 10)
print(arr[arr > 5]) # Elements greater than 5
print(arr[arr % 2 == 0]) # Even elementsArray operations
You can perform arithmetic directly on arrays; operations are applied element-wise.
arr = np.arange(0, 10)
print(arr + 10)
print(arr * 2)
print(arr - arr)Between two arrays:
a = np.arange(0, 10)
b = np.arange(5, 15)
print(b - a)Common mathematical functions
NumPy provides built-in math functions.
arr = np.arange(0, 10)
print(np.sqrt(arr)) # Square root
print(np.max(arr)) # Maximum
print(np.min(arr)) # Minimum