Variables

Introduction to Variables in Python

  • Python supports various value types, including integers (ints), floating-point numbers (floats), and strings (str).

  • Variables are used to store and recall calculated values for future use.

Example: Calculating Costs for Guacamole

  • Scenario: Preparing for a potluck and calculating expenses for ingredients.

  • Items and Prices:

    • Avocados: 2

    • Price per avocado: $1.78

    • Lemon: $0.77

    • Onion: $1.29

    • Ground oregano: $5.99

  • Subtotal Calculation:

    • Initial subtotal: $11.61 (calculated from added prices)

    • Sales tax in Alberta: 5%

    • Total calculation requires recalling previous values.

Understanding Variables

  • Definition: Variables allow naming a stored value for easy recall.

  • Assignment Statement: The equal sign (=) is called an assignment statement, where the right side is computed and stored as the left side's identifier.

  • Identifiers: Referred to as names in this context.

    • Example assignments:

      • avocado = 1.78

      • lemon = 0.77

      • onion = 1.29

      • oregano = 5.99

Calculating Subtotal Using Variables

  • Subtotal Initialization:

    • Start subtotal at 0: subtotal = 0

  • Updating Subtotal: Each item can be added sequentially:

    • subtotal = 2 * avocado

    • subtotal = subtotal + lemon

    • subtotal = subtotal + onion

    • subtotal = subtotal + oregano

  • The updated subtotal can be printed at any stage.

Final Calculations

  • Tax Calculation:

    • tax = 0.05 * subtotal

  • Total Calculation:

    • total = subtotal + tax

  • Formatting Output:

    • To format total to two decimal places: print("%.2f" % total)

  • String formatting will be elaborated in future videos.

Common Mistakes with Variables

  • Case Sensitivity: Variable names are case-sensitive. Example: Using total and Tax leads to a NameError (incorrect capitalization).

  • Spelling Errors: Misspelling an identifier results in a NameError. Example: subtotal vs. subtotl.

Valid Identifier Rules

  • Starting Characters: Identifiers cannot start with a digit (e.g., 2avocado is invalid).

  • Spaces: Cannot contain spaces (e.g., sub total is invalid).

  • Special Characters: Hyphens are invalid (e.g., sub-total); underscores can be used instead (e.g., sub_total).

  • Camel Case: Use camel case for multi-word identifiers (e.g., subTotal).

Reserved Keywords

  • Identifiers cannot be keywords in Python (e.g., None is invalid as an identifier).

  • To check for keywords use: help('keywords').

Conclusion

  • This video covered the use of variables for computation storage, reassignment of values, and common pitfalls.

  • Understanding these concepts is crucial for effective programming in Python.