Comprehensive Python Foundations for Beginners

Introduction to Python Programming

Python is a versatile, multi-purpose programming language designed for readability and efficiency. It is the leading language for various high-demand technical fields:

  • Machine Learning and Artificial Intelligence (AI): Python ranks as the number one language for these projects because of its extensive libraries and community support.

  • Data Science: Used heavily for data analysis, visualization, and processing.

  • Web Development: Developers use Python alongside frameworks like Django to build high-performance websites. Notable examples include:

    • YouTube

    • Instagram

    • Spotify

    • Dropbox

    • Pinterest

  • Automation: Python is used to automate repetitive manual tasks, significantly increasing productivity and saving time.

Installation and Environment Setup

To begin programming, a system must have the Python interpreter and a code editor installed.

  • Python Interpreter: Available at python.org.

    • During the Windows installation process, it is essential to check the box labeled "Add Python to path." Failure to do so will prevent Python from running correctly in the terminal or code editor.

  • Code Editor (PyCharm):

    • Developed by JetBrains, PyCharm is the most popular IDE for Python development.

    • Editions:

    • Professional Edition: A paid, commercial version for enterprise use.

    • Community Edition: A free, open-source version ideal for beginners.

    • Initial Setup: Upon first launch, users can select "Skip Remaining and Set Defaults" to quickly enter the coding environment.

  • Project Structure:

    • Projects are containers for logic files (e.g., app.py).

    • venv (Virtual Environment): This folder is automatically created to manage the specific Python environment for that project.

Basic Syntax: Printing and Strings

  • The Print Function: Used to output data to the user.

    • Syntax: print(… )\text{print}(\dots) all in lowercase.

  • Strings: Textual data is represented as a string, which is a sequence of characters.

    • Strings must be enclosed in single quotes ('...') or double quotes ("...").

    • Example: print("HelloWorld")\text{print}("Hello World") displays the message in the Terminal, the window showing program output.

Variables and Data Storage

Variables temporarily store data in the computer's memory for later use.

  • Declaration: Variables are declared by naming them, followed by an equal sign (==) and the value.

  • Naming Conventions:

    • Python is case-sensitive.

    • Multiple words in variable names should be separated by underscores (e.g., first_namefirst\_name) for readability.

  • Data Types:

    • Integers: Whole numbers without decimals (e.g., age=20age = 20).

    • Floats: Numbers with decimal points (e.g., price=19.95price = 19.95).

    • Booleans: Logical values representing true/false or yes/no. In Python, these are capitalized: True and False.

  • Dynamic Execution: Programs execute from top to bottom. If a variable is reassigned (e.g., age=20age = 20 followed by age=30age = 30), the program uses the most recent value (3030).

Handling User Input

  • The Input Function: Use input("Prompt text")\text{input}(\text{"Prompt text"}) to capture user interaction.

  • White Space: Always add a space at the end of the prompt string to separate the user's cursor from the message.

  • String Concatenation: The ++ operator is used to combine strings.

    • Example: "Hello "+name\text{"Hello "} + name creates a single greeting string.

Type Conversion Mechanics

The input()\text{input}() function always returns data as a string, even if digital characters are typed. Mathematical operations cannot be performed directly on these strings.

  • Built-in Conversion Functions:

    • int()\text{int}(): Converts a value to an integer.

    • float()\text{float}(): Converts a value to a floating-point / decimal number.

    • bool()\text{bool}(): Converts a value to a boolean.

    • str()\text{str}(): Converts a value to a string (necessary when concatenating numbers to text).

  • Case Study: Age Calculation:

    • Current Year: 20202020.

    • Input Birth Year: "1982""1982" (String type).

    • Operation: 2020−int("1982")=382020 - \text{int}("1982") = 38.

  • TypeError: Occurs when trying to combine incompatible types, such as subtracting a string from an integer or concatenating a float with a string without conversion.

Mathematical Operations

Python provides several operators for arithmetic:

  • Addition: 10+3=1310 + 3 = 13.

  • Subtraction: 10−3=710 - 3 = 7.

  • Multiplication: 10×3=3010 \times 3 = 30 (Syntax: *).

  • Standard Division: 10/3=3.333333333333333510 / 3 = 3.3333333333333335 (Returns a float).

  • Integer Division: 10//3=310 // 3 = 3 (Returns only the whole number).

  • Modulus: 10%3=110 \% 3 = 1 (Returns the remainder).

  • Exponent: 103=100010^{3} = 1000 (Syntax: **).

Augmented Assignment Operators

These provide a concise way to update variables:

  • Instead of x=x+3x = x + 3, write x+=3x += 3.

  • Works with other operators: x−=3x -= 3, x∗=3x *= 3, etc.

Operator Precedence

Similar to standard mathematics, Python follows priority rules:

  1. Multiplication and Division are evaluated first.

  2. Addition and Subtraction are evaluated second.

  3. Parentheses (… )(\dots) can change the order of evaluation.

  • Example: 10+3×2=1610 + 3 \times 2 = 16.

  • Example: (10+3)×2=26(10 + 3) \times 2 = 26.

Logical and Comparison Operators

  • Comparison Operators (return Booleans):

    • >>, ≥\ge, <<, ≤\le.

    • ==== for equality.

    • != for not equal (≠\ne).

  • Logical Operators:

    • and: Returns True if both expressions are true.

    • or: Returns True if at least one expression is true.

    • not: Inverts the Boolean value (e.g., not(False)=True\text{not(False)} = True).

Decisions with If Statements

If statements direct the program flow based on conditions.

  • Syntax: Use the if keyword, a condition, and a colon :.

  • Indentation: Python defines code blocks using indentation. Subordinate code must be indented to belong to a specific condition.

  • Else If (elif): Allows for multiple sequential conditions.

  • Else: Handles all cases where prior conditions were false.

  • Comments: Use the # symbol for non-executable notes within the code.

Repetition with While Loops

Used to execute a code block multiple times as long as a condition is met.

  • The Loop Variable: Typically denoted as ii. It must be incremented (e.g., i+=1i += 1) inside the loop to avoid an infinite loop, which runs until the system exhausts memory.

  • Readability: Large numbers can be written with underscores (e.g., 1_0001\_000 for one thousand).

  • String Multiplication: Multiplying a string by an integer repeats the string (e.g., "X"×3="XXX""X" \times 3 = "XXX"). This is used to create visual patterns like triangles.

Working with Lists

Lists store collections of objects inside square brackets [… ][\dots].

  • Indices:

    • Start at 00 (first element).

    • Negative indices start from the end: −1-1 is the last item, −2-2 is second to last.

  • Ranges: names[0:3]names[0:3] returns items at indices 0,1,20, 1, 2 (excludes the end index).

  • List Objects and Methods:

    • .append(x): Adds x to the end.

    • .insert(index, x): Places x at a specific index.

    • .remove(x): Deletes the first instance of x.

    • .clear(): Empties the list.

    • len(list)\text{len}(list): Built-in function to count items.

    • in Operator: Boolean check for existence (e.g., "John" in names\text{"John" in names}).

Iteration with For Loops

For loops simplify iterating through every item in a collection.

  • Syntax: for item in numbers:.

  • Advantage: For loops are more concise than while loops for collections because they eliminate the need for a manually incremented index variable and type-specific range calculations.

Using the Range Function

The range()\text{range}() function generates a sequence of numbers.

  • range(5)\text{range}(5): 0,1,2,3,40, 1, 2, 3, 4 (up to but excluding 55).

  • range(5,10)\text{range}(5, 10): 5,6,7,8,95, 6, 7, 8, 9.

  • range(5,10,2)\text{range}(5, 10, 2): 5,7,95, 7, 9 (using a step/increment of 22).

Immutable Sequences: Tuples

Tuples store objects but are immutable, meaning they cannot be modified after creation.

  • Syntax: Defined using parentheses (… )(\dots) (e.g., numbers=(1,2,3)numbers = (1, 2, 3)).

  • Restrictions: Methods like .append(), .insert(), and .remove() do not exist. Only .count() and .index() are available.

  • Best Practice: Use tuples for security when you want to ensure a list remains unchanged throughout the program's lifecycle.

Questions & Discussion

  • Q: Why separate multiple words in variable names with an underscore?

  • A: This adherence to Python coding standards improves readability (e.g., first_name vs firstname).

  • Q: Are variables in Python case-sensitive?

  • A: Yes. For example, the boolean False must have a capital F to be recognized as a keyword.

  • Q: How does the .find() method handle missing characters?

  • A: If the method is called on a character not present in the string (e.g., looking for an uppercase "Y" in "python"), it returns −1-1.

  • Q: Do string methods like .upper() modify the original string?

  • A: No. Strings in Python are immutable. Methods return a new string object without altering the original variable.

  • Q: What is the shortcut for running a file in PyCharm on Mac?

  • A: Ctrl+Shift+R\text{Ctrl} + \text{Shift} + \text{R}.