Understanding Variables in Programming

Oct 7, 2024

Lecture Notes: Introduction to Variables in Programming

Overview

  • Fundamental concept in programming: Variables
  • Examples given using Python

Key Concepts

What is a Variable?

  • Definition: A variable stores information in a program for later use.
  • Components:
    • Name: Identifier for the variable.
    • Type: Defines the kind of data stored.
    • Value: The data stored in the variable.

Examples

  1. Variable: greeting

    • Type: str (string)
    • Value: "Hello World"
    • Usage: Printing greeting outputs "Hello World" without quotes.
  2. Variable: my_number

    • Type: int (integer)
    • Value: 50

Variable Types

String (str)

  • Contains text or a sequence of characters.
  • Can include letters, numbers, punctuation, and spaces.
  • Examples: "Hello World", "abc123", or even an empty string.
  • Convention in Python:
    • Double quotes preferred for the course.

Integer (int)

  • Contains a whole number (positive, negative, or zero).
  • Cannot have decimals.
  • Examples: -50, 0, 5

Floating-point Number (float)

  • Like an integer but can include decimals.
  • Examples: -3.2, 0.0, 4.5652
  • Zero point zero (0.0) is equal to integer zero.

Assignment Statements

  • Used to create or update variables.
  • Structure:
    • Left: Variable Name
    • Middle: Single Equal Sign (=)
    • Right: Value to assign

Using the type Function

  • Prints the type of a variable.
  • Example: type(greeting) outputs class 'str'.
  • For my_number, the output is class 'int'.

Conclusion

  • Basics of variables in Python covered.
  • Future topics: Advanced operations with variables.