ЁЯТб

Variables in Python

Jul 21, 2024

Variables in Python

Introduction

  • Variables are like containers in Python programming, similar to kitchen containers storing different items (e.g., rice, sugar).
  • Variables store values in the computer's RAM.

Creating Variables

  • Declaration: a = 1
  • Printing a variable: print(a)
  • When you write a = 1, '1' is stored in memory and 'a' points to that memory address.

Examples

  • b = 'Harry': Assign a string to a variable with double quotes.
  • Important: Strings should be enclosed in double quotes to avoid errors.
    • Example: Without quotes, print(b) might treat 'b' as a variable pointing to another value.

Variable Types

  1. Integers: Whole numbers (e.g., a = 1)
  2. Floats: Decimal numbers (e.g., a = 1.1)
  3. Strings: Text enclosed in quotes (e.g., b = 'Harry')
  4. Booleans: True or False values

Checking Variable Types

  • Using type() function: print(type(a)) # Output: <class 'int'> print(type(b)) # Output: <class 'str'>

Different Data Types in Python

  1. Numbers
    • Integer: Whole numbers
    • Float: Decimal numbers
    • Complex: Real and Imaginary parts (e.g., a = 2 + 3j)
  2. Strings: A sequence of characters (e.g., s = "Hello")
  3. Booleans: True or False
  4. Sequences
    • Lists: Mutable collection of items (e.g., [1, 2, 'a'])
    • Tuples: Immutable list (e.g., (1, 2, 'a'))
  5. Mappings: Dictionaries
    • Key-value pairs (e.g., d = {'name': 'Harry', 'age': 25})

Lists and Tuples

  • Lists: Collection of items of different types, mutable.
    • Creation: list = [1, 2, 'a']
    • Can store another list inside it.
  • Tuples: Similar to lists but immutable.
    • Creation: tuple = (1, 2, 'a')
    • Can't be changed.

Dictionary

  • Collection of key-value pairs.
    • Example: student = {'name': 'Sakshi', 'age': 20, 'can_vote': True}

Variable Concepts and Operations

  • Python requires specifying the type of value that a variable can hold to perform operations correctly. a = 1 b = 2 print(a + b) # Output: 3
  • Mixing types can cause errors. a = 1 b = 'Harry' print(a + b) # Error, can't add integer and string

Mutable and Immutable Types

  • Mutable: Can be changed (e.g., Lists).
  • Immutable: Cannot be changed (e.g., Tuples).
  • Remember: Mutation means change.

Everything is an Object in Python

  • In Python, everything is an object (Integers, strings, etc.).
  • Class types indicate what kind of object a variable is.

Conclusion

  • Understanding different data types and their behaviors is crucial for efficient programming.
  • Python's flexibility with variable types allows for dynamic and complex operations.

[Playlist Link & Bookmarking Steps]