



Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!




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) →
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
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
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.
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)
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
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)
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
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
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!")
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")
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)
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 )
Function / Constant Description Example math.sqrt(x) (^) Computes the square root of a number. math.sqrt(4)
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]