Python is a high-level, general-purpose programming language used for various applications like AI, machine learning, web development, and automation. It is known for its clean and simple syntax , requiring fewer lines of code compared to many other languages. Python is cross-platform , meaning it can run on Windows, Mac, and Linux. It has a large community and ecosystem of libraries and frameworks. Python has been around for over 20 years, with Python 3 being the version for the future (and the one used in the course). The Python Interpreter is a program that executes Python code. The interpreter can be used in an interactive shell for quick experimentation, or to run code from a .py file. A Syntax Error occurs due to bad syntax or grammar in the code, like an incomplete expression. Python Fundamentals A Code Editor is used for typing code. An IDE (Integrated Development Environment) is a code editor with additional features like: Autocompletion: Helps complete code as you type. Debugging: Finding and fixing errors. Testing. VS Code (Visual Studio Code) is a popular code editor that can be enhanced with extensions to become a powerful IDE. Python files typically have the .py extension . An Extension (or Plugin) can add functionality to a code editor/IDE. The official Python extension for VS Code provides features like linting, debugging, autocompletion, code formatting, unit testing, and code snippets. Linting is the process of analyzing code for potential errors, mostly syntactical issues, before running the program. Pylint is a popular linter. The Problems Panel in VS Code lists all issues (like linting errors) in your code in one place. The Command Pallet (Shift + Command + P on Mac, Shift + Control + P on Windows) allows executing various commands in VS Code. Variables Variables are used to store data in computer's memory . A variable acts as a label referencing a memory location where data is stored. Variable names should be descriptive and meaningful . Avoid mystical names (e.g., cn , c1 ). Naming conventions: Use lowercase letters and underscores to separate multiple words (e.g., students_count ). Best practice: Put a space around the assignment operator ( = ) . Assignment operator ( = ): Assigns a value to a variable. Primitive Data Types These are basic data types built into Python. Numbers: Integers (int): Whole numbers (e.g., 1000 ). Floats (float): Numbers with a decimal point (e.g., 4.99 ). Complex Numbers (complex): Numbers in the form a + bj (e.g., 1 + 2j ). Used in math/electrical engineering. Booleans (bool): Represent truth values, can be True or False . Python is case sensitive : True and False must start with a capital letter. Used for making decisions in programs. Strings (str): Represent text . Surround text with single ( ' ) or double ( " ) quotes . Triple quotes ( ''' or """ ) are used for long strings or multi-line strings. len(string) : Built-in function to get the length (number of characters) of a string. Indexing ( [] ): Access specific characters. Zero-based: The first character is at index 0 . string[index] : Returns the character at that index. Negative indexing: string[-1] is the last character, string[-2] is the second to last, etc. Slicing ( start:end ): Extract a portion (substring). string[start:end] : Returns a new string from start up to (but not including ) end . string[start:] : Returns from start to the end. string[:end] : Returns from the beginning up to (but not including) end . string[:] : Returns a copy of the original string. Escape Characters ( \ ): Special character in strings. Escape Sequences: \" : Include a double quote. \' : Include a single quote. \\ : Include a backslash. \n : Newline character. String Concatenation: Joining strings using the + operator. Formatted Strings (f-strings): A cleaner way to build strings by embedding expressions. Prefix the opening quote with f (e.g., f"..." ). Embed variables or expressions inside curly braces {} . The expression is evaluated at runtime. Numbers in Detail Getting User Input Type Conversion Conditional Statements (If/Elif/Else) A concise way to assign a value to a variable based on a condition. Syntax: variable = value_if_true if condition else value_if_false . Equivalent to a simple if/else structure assigning a value. Functions (Creating Your Own) Environment and Tools Python Implementations and Execution String Operators substring in string : Returns True if substring is found in string , otherwise False . (Boolean expression) substring not in string : Returns True if substring is not found in string , otherwise False . Types: int , float , complex . Standard Arithmetic Operators: + : Addition - : Subtraction * : Multiplication / : Float Division (e.g., 10 / 3 results in 3.33... ) // : Integer Division (e.g., 10 // 3 results in 3 ) % : Modulus (Remainder of division, e.g., 10 % 3 results in 1 ) ** : Exponent (Left to the power of right, e.g., 10 ** 3 is 1000 ) Augmented Assignment Operators: Shorthand for combining an operation and assignment. x = x + 3 is equivalent to x += 3 . Works for other operators: -= , *= , /= , //= , %= , **= . Number Functions and Modules round(number) : Built-in function to round a number. abs(number) : Built-in function to get the absolute value of a number. import math : Imports the built-in Math module, which contains advanced mathematical functions. Access functions from the math module using dot notation (e.g., math.ceil(number) ). Need to convert input strings to numbers (or other types) for calculations or comparisons. Built-in Functions: int(value) : Converts value to an integer. float(value) : Converts value to a float. bool(value) : Converts value to a boolean. str(value) : Converts value to a string. Attempting to perform operations on incompatible types (e.g., string + number) results in a TypeError . type(object) : Built-in function to get the type of an object. Used to compare values, resulting in a Boolean value ( True or False ). > : Greater than < : Less than >= : Greater than or equal to <= : Less than or equal to == : Equality (checks if values and types are the same). 10 == "10" is False . != : Not Equal Can be used with strings, comparing them based on their lexicographical order (alphabetical, using numeric representation of characters - ord() function shows this, but the specific numeric values aren't typically memorized). Used to make decisions in programs. if condition: : Executes the indented block if condition (a Boolean expression) is True . elif condition: : (Else if) Checked if the preceding if (or elif ) was False . Executes the indented block if its condition is True . You can have multiple elif blocks. else: : Executes the indented block if none of the preceding if or elif conditions were True . Optional. Colons ( : ) are required at the end of if , elif , and else lines. Indentation is crucial to define the code blocks belonging to each condition. Used to combine or modify Boolean expressions. and : Returns True if both operands are True . or : Returns True if at least one operand is True . not : Inverses the Boolean value (e.g., not True is False , not False is True ). Logical operators are short-circuiting : With and , evaluation stops as soon as a False operand is found. With or , evaluation stops as soon as a True operand is found. Chaining Comparison Operators Python Language is a specification (rules and grammar). Python Implementation is a program that understands and executes Python code. CPython is the default and most popular implementation, written in C. Other implementations exist (Jython in Java, IronPython in C#, PyPy in Python). Jython allows reusing Java code in Python programs. IronPython allows reusing C# code. Execution in CPython: Python code is compiled into Python Bytecode . Bytecode is passed to the Python Virtual Machine (PVM) . The PVM converts bytecode to Machine Code at runtime and executes it. This process makes Python platform independent . String Methods (Dot Notation) Everything in Python is an object , and objects have methods (functions belonging to the object). Access methods using the dot notation ( object.method() ). Examples: string.upper() : Returns a new string with all characters uppercase. string.lower() : Returns a new string with all characters lowercase. string.title() : Returns a new string with the first character of each word capitalized. string.strip() : Returns a new string with leading/trailing whitespace removed. string.lstrip() : Removes leading whitespace. string.rstrip() : Removes trailing whitespace. string.find(substring) : Returns the index of the first occurrence of the substring. Returns -1 if not found. Python is case sensitive for searching. string.replace(old, new) : Returns a new string with all occurrences of old replaced by new . Most string methods return a new string ; they do not modify the original string. input(prompt) : Built-in function that prompts the user for input in the terminal. The argument prompt is the message displayed to the user. The input() function always returns a string , even if the user types a number. Truthiness and Falsiness In a boolean context (e.g., if conditions), some non-Boolean values are interpreted as True or False . Falsy Values: The values that are interpreted as False . Empty strings ( "" ) The number 0 None (represents absence of a value) Truthy Values: Anything that is not falsy is interpreted as True . Non-empty strings, non-zero numbers (positive or negative). Used to repeat a block of code . for Loops: Iterate over items in an iterable object . Syntax: for variable in iterable: followed by an indented block. In each iteration, variable takes on the value of the next item from the iterable. Commonly used with the range() function. range() function: Generates a sequence of numbers (a range object, which is iterable). range(stop) : Generates numbers from 0 up to (but not including) stop . range(start, stop) : Generates numbers from start up to (but not including) stop . range(start, stop, step) : Generates numbers from start up to (but not including) stop , incrementing by step . break statement: Immediately exits the innermost loop. for...else statement: The else block is executed only if the loop completes without encountering a break statement . while Loops: Repeat a block of code as long as a condition is True . Syntax: while condition: followed by an indented block. The condition is evaluated before each iteration. Infinite Loops: A while loop where the condition is always True (e.g., while True: ). These run forever unless a break statement is used within the loop. Can consume resources. Nested Loops: Putting one loop inside another. The inner loop completes all its iterations for each single iteration of the outer loop. Strings in Detail Ternary Operator (Conditional Expression) Logical Operators Allows combining multiple comparisons concisely. Syntax: value1 operator1 value2 operator2 value3 . Example: 18 <= age < 65 is equivalent to age >= 18 and age < 65 . This is cleaner. Used to organise code into reusable blocks , making programs more maintainable. Defined using the def keyword . Syntax: def function_name(parameters): followed by an indented block. Function names should be descriptive , lowercase, using underscores (PEP 8). Parameters are variables defined in the function definition's parentheses. They are placeholders for input values. Arguments are the actual values passed to the function when it is called . Calling a function: Use the function name followed by parentheses (e.g., greet() , increment(2, 1) ). Functions can: Perform a task (e.g., print to the console). Calculate and return a value (e.g., round() ). return value statement: Exits the function and sends value back to the caller. If a function has no return statement, or uses return without a value, it implicitly returns None . None is a special object representing the absence of a value. Keyword Arguments: Passing arguments using the parameter name followed by = (e.g., increment(number=2, by=1) ). Makes function calls more readable, especially with multiple arguments. Optional Parameters: Define parameters with a default value (e.g., def increment(number, by=1): ). If the argument is not provided when calling, the default value is used. Optional parameters must be defined after all required parameters in the function signature. Variable Number of Arguments ( *args ): Using *parameter_name in the function definition (e.g., def multiply(*numbers): ). This collects all positional arguments passed to the function into a tuple (an iterable collection similar to a list, but immutable). You can then iterate over this tuple inside the function. Comparison Operators Loops