Docsity

Python Reference Card - Sintassi, Strutture Dati e NumPy, Schemi e mappe concettuali di Fondamenti di informatica

Toggle sidebar
bg1
1
1. Basic Python Reference Card
1.1 Arithmetic Operations & Basic Data Types
Syntax / Operator
Description / Rule
Example
+, -, *, /
Basic arithmetic operations. Division / always returns a float.
5/3 → 1.6666666666666667
//
Integer division (Floor Division), returns an int if both
operands are integers.
5//3 → 1
%
Modulus operator (returns the remainder of division).
5%3 → 2
**
Exponentiation (power).
3**2 → 9
(...)
Parentheses for operator precedence.
(3+4)*2 → 14
type(val)
Returns the data type of a value or variable.
type(5.5) → <class 'float'>
1.2 Variables & Assignment
Syntax /
Concept
Description
Example
Assignment
No need to declare variable type explicitly (Dynamic Typing).
x = 3
Compound
Operators
Shorthand variable update and re-assignment.
x += 1 (equivalent to x = x + 1)
Type Casting
Explicit type conversion between compatible types (str(),
int(), float()).
x1 = str(10.5) → '10.5'
x2 = int(10.5) → 10
1.3 Strings (Syntax, Slicing & Methods)
Operation / Method
Example
Definition & Escape
place = "l'università" or 'l\'università'
len(s)
len('andrea') → 6
Indexing
s[0] (first element), s[-1] (last element)
Slicing
s[:3] (first 3 characters)
s[:-3] (all except last 3)
s[-2:] (last 2 characters)
s[::2] (every 2nd character)<br>s[::-1] (reversed string)
Immutability
s = 'P' + s[1:] (creates a new string)
Concatenation &
Repetition
'a' + 'b' → 'ab'
'100'*3 → '100100100'
Main Methods
.upper() → uppercase
.lower() → lowercase
.split(delim) → splits into a list
pf3
pf4
pf5

Anteprima parziale del testo

Scarica Python Reference Card - Sintassi, Strutture Dati e NumPy e più Schemi e mappe concettuali in PDF di Fondamenti di informatica solo su Docsity!

1. Basic Python Reference Card

1. 1 Arithmetic Operations & Basic Data Types

Syntax / Operator Description / Rule Example +, - , *, / Basic arithmetic operations. Division / always returns a float. 5/3 → 1. // (^) Integer division (Floor Division), returns an int if both operands are integers.

% (^) Modulus operator (returns the remainder of division). 5%3 → 2 ** (^) Exponentiation (power). 3*2 → 9 (...) (^) Parentheses for operator precedence. (3+4)2 → 14 type(val) (^) Returns the data type of a value or variable. type(5.5) →

1. 2 Variables & Assignment

Syntax / Concept Description Example Assignment No need to declare variable type explicitly ( Dynamic Typing ). x^ =^3 Compound Operators Shorthand variable update and re-assignment. x += 1 (equivalent to x = x + 1 ) Type Casting Explicit type conversion between compatible types (str(), int(), float()). x1 = str(10.5) → '10.5' x2 = int(10.5) → 10

1. 3 Strings (Syntax, Slicing & Methods)

Operation / Method Description / Rule Example Definition & Escape Enclosed by '...' or "...". Use `` to escape quotes or apostrophes. place = "l'università" or 'l'università' len(s) (^) Returns the length of a string. len('andrea') → 6 Indexing Access individual characters (0-based). Negative indices start from the end. s[0] (first element), s[-1] (last element) Slicing Syntax: s[start:stop:step]. s[:3] (first 3 characters) s[:-3] (all except last 3) s[-2:] (last 2 characters) s[::2] (every 2nd character)s[::-1] (reversed string) Immutability Strings cannot be modified in-place (s[0] = 'A' raises an error). s = 'P' + s[1:] (creates a new string) Concatenation & Repetition Use + to concatenate and * to repeat. 'a' + 'b' → 'ab' '100'*3 → '100100100' Main Methods Common string manipulation functions. .upper() → uppercase .lower() → lowercase .split(delim) → splits into a list

1. 4 Booleans & Comparison Operators

Category Syntax Explanation Boolean Values True, False Data type bool. Logical Operators and, or, not (^) Boolean logic operations (True and False → False). Comparison Operators <, <=, >, >=, ==, != Evaluates conditions and returns booleans (a == b, a != b). Chained Comparisons Direct mathematical chaining syntax a > b > c or a > b == c. Object Identity is, is not Tests object memory identity.

1. 5 Output Formatting (‘print’)

Formatting Method Syntax Example % Operator C-style formatting (%f float, %s string, %d integer). print("x = %.2f" % x) "I am %s %s" % (name, family) .format() Method Positional, index-based, or padded formatting. "I^ am^ {}^ {}".format(name,^ family) "I am {1} {0}".format(name, family) "{0:20}".format(name) (20-char width padding)

2. Data Structures Reference Card

2.1 Lists (‘list’): lists are ordered, mutable collections defined using square brackets [...]. They can contain mixed

data types and nested lists.

Syntax / Method Description / Rule Example Creation & Access Indexing is 0-based. Supports negative indexing. lst^ =^ ['a',^ 'b',^ 'c'] lst[0] → 'a' lst[-1] → 'c' Mutability Items can be directly reassigned or replaced with different types. lst[1] = 'lime' lst[0] = [1, 2] (nested list) Concatenation & Repetition

  • joins lists; * repeats a list. [1, 2] + [3] → [1, 2, 3] ['a'] * 3 → ['a', 'a', 'a'] elem in lst (^) Membership test returning a boolean. 'lime' in grocery → True .index(x) (^) Returns the index of the first occurrence of x. grocery.index('lime') .append(x) (^) Adds an item x to the end of the list. grocery.append(2.0) .pop(index) (^) Removes and returns the item at the specified index. grocery.pop(0) .sort() (^) Sorts list elements in-place (requires compatible types). numbers.sort() .reverse() (^) Reverses list elements in-place. numbers.reverse() .count(x) (^) Returns total occurrences of x in the list. numbers.count(7) max(lst), min(lst) Returns the maximum or minimum element. max([3, 1, 7]) → 7

2.5 Inspection & Documentation Tools

Function Description / Purpose Example dir(obj) (^) Returns a list of all valid attributes and methods of an object. dir(set) help(obj) (^) Displays official documentation and usage details for a function or method. help(list.pop)

3. Statements Reference Card

3.1 Conditional Statements (‘if’, ‘elif’, ‘else’): conditional statements execute code blocks conditionally based on

Boolean evaluations.

Syntax / Concept Description / Rule Example if condition: (^) Executes code block if the condition evaluates to True. if a < b: print("a is smaller") elif condition: Evaluates subsequent conditions if prior if/elif conditions were False. elif a > b: print("b is smaller") else: (^) Executes default code block if all preceding conditions evaluate to False. else: print("they are equal") Comparison Operators Compare values returning booleans: <, >, <=, >=, ==, !=. if a <= b: → checks less than or equal

3.2 ‘for’ Loops & Control Statements: for loops iterate over sequence items (strings, lists, dictionaries, ranges) in

order.

Syntax / Function Description / Rule Example Sequence Iteration Iterates directly over items in strings, lists, or dictionary keys. for c in 'andrea': for k in students.keys(): range(stop) (^) Generates integers from 0 up to stop -

list(range(4)) → [0, 1, 2, 3] range(start, stop, step) Generates integers from start up to stop - 1 with a custom step. list(range(0, 10, 2)) → [0, 2, 4, 6, 8] enumerate(iterable) (^) Returns tuples containing index i and element val. for i, c in enumerate('pierluca'): pass (^) Null statement placeholder; does nothing and proceeds. for x in lst: pass continue (^) Skips the remaining statement body for the current loop iteration. for x in lst: continue break (^) Immediately terminates loop execution. if x == 2: break

3.4 ‘while’ Loops: while loops repeat a block of code continuously as long as the given condition remains True.

Structure Description Example Standard Loop Repeats execution until condition becomes false. while^ i^ <^ n: print(i) i += 1 Infinite Loop Runs indefinitely unless interrupted externally or exited with break. while^ True: print("Hello World!")

4. Methods and Functions Reference Card

4.1 Methods vs. Functions: methods are functions built directly into objects, accessed via dot notation

object.method(args). Functions are reusable blocks of code defined to perform specific tasks.

Concept / Tool Description / Rule Syntax & Example Methods Functions associated with specific objects to perform actions on them. my_list.extend([2, 3]) Functions Independent code blocks grouping statements to run multiple times with inputs/outputs. len("hello")

4.2 Defining Functions (‘def’): the def statement creates a user-defined function. Python relies on mandatory

indentation (whitespace) to organize function code blocks.

Component / Feature Description / Rule Syntax & Example def Statement Keyword used to declare a function, followed by name, arguments in (), and a colon :. def say_hello(): Code Block & Indentation Function statements must be indented under def. def say_hello(): print("Hello World!") Type Annotations Optional type hints specifying expected argument types and return type. def compute_taxes(income: float, tax_rate: float) - > float: return Value Returns computed result to caller; functions without return output None. return income * tax_rate Multiple Return Values Returns multiple values separated by commas as a tuple; supports tuple unpacking. def double_and_half(x): return x*2, x/ a, b = double_and_half(6)

4.3 Recursion: recursion is a programming technique where a function calls itself to solve smaller instances of the

same problem.

Concept Description / Mechanism Example (Fibonacci) Base Case Terminating condition that stops recursion to avoid infinite loops. if n == 0 or n == 1: return 1 Recursive Call The function calling itself with a modified/reduced argument. return fibonacci(n - 1) + fibonacci(n - 2) Complete Function Full recursive implementation combining base case and recursive call. pythondef fibonacci(n): if n == 0 or n == 1: return 1< return fibonacci(n - 1) + fibonacci(n – 2 )

5. Math and Numpy Libraries Reference Card

5.1 The math Module: the math module provides access to core mathematical functions in Python.

Function / Constant Description Example math.sqrt(x) (^) Computes the square root of a number. math.sqrt(4)

5.4 NumPy: Manipulation, Copying, and Slicing

Concept Description / Command Example Reshaping Changes array dimensions; the total number of elements must match the original. x.reshape((4, 5)) Auto-Reshaping Using - 1 allows NumPy to infer that specific dimension automatically. x.reshape(-1, 2) Flattening Returns a contiguous, flattened 1D version of the array. x.ravel(), x.reshape(-1) Data Types Checks or assigns the array's data type (e.g., bool, float). x.dtype, np.array([1, 2], dtype=float) Assignment vs. Copy b = a assigns by reference; modifying b alters a. .copy() creates an independent array. c = a.copy() Slicing & Indexing Extracts specific subarrays or values along multiple dimensions. x[1, 2, :], x[:, 5, 6]