Variables, Expression and Statements
Variables, Expressions, and Statements
Variables
- Definition:
- A variable is a name that refers to a value. It allows you to store and manipulate data in your programs.
- Creating Variables:
- Python code
- age = 25 # An integer variable
- name = "Alice" # A string variable
- height = 5.6 # A float variable
- is_student = True # A boolean variable
Variable Naming Rules:
- Must start with a letter (a-z, A-Z) or an underscore (_).
- Can contain letters, digits (0-9), and underscores.
- Cannot use spaces or special characters.
- Should not be a keyword (reserved words in Python).
Keywords:
Python has several reserved words that cannot be used as variable names. Examples include: if, for, while, def, return, class, import, in, is, None, True, False, etc. You can check the list of keywords using:
- Python code
- import keyword
- print(keyword.kwlist)
- import keyword
- print(keyword.kwlist)
Expressions
- Definition:
- An expression is a combination of values, variables, and operators that Python evaluates to produce another value.
- An expression is a combination of values, variables, and operators that Python evaluates to produce another value.
Operators and Operands:
- Operators: Symbols that perform operations on operands.
- Arithmetic Operators: +, -, *, /, // (floor division), % (modulus), ** (exponentiation)
- Operands: The values or variables that the operators act on.
- Example:
- Python code
- x = 10
- y = 5
- result = x + y # result is 15
Order of Operations
- Python follows the standard mathematical rules for the order of operations, often remembered by the acronym PEMDAS/BODMAS:
- P/B: Parentheses/Brackets
- E/O: Exponents/Orders
- MD: Multiplication and Division (from left to right)
- AS: Addition and Subtraction (from left to right)
- Example:
- Python code
- result = (2 + 3) * (5 ** 2) / 5 - 1 # result is 24
Operations on Strings
- String Concatenation: Combining two strings using the + operator.
- Python code
- greeting = "Hello, " + "World!" # "Hello, World!"
- String Repetition: Repeating a string using the * operator.
- Python code
- repeat = "ha" * 3 # "hahaha"
- Accessing Characters: You can access individual characters in a string using indexing (0-based).
- Python code
- word = "Python"
- first_char = word[0] # 'P'
- last_char = word[-1] # 'n'
- Slicing Strings: Extracting a substring using slicing.
- Python code
- substring = word[1:4] # 'yth'
Composition and Comments
Composition:
- Combining variables and strings for dynamic output.
- Python code
- name = "Alice"
- age = 25
- message = f"{name} is {age} years old." # Using f-strings (formatted string literals)
- Comments: Use comments to explain code. Comments start with # and are ignored by the interpreter.
- Python code
- # This is a comment
- print("Hello!") # This prints Hello!
Avoiding Name Errors
Definition:
- A NameError occurs when you try to use a variable that hasn't been defined yet.
Example of NameError:
- Python code
- print(my_variable) # Raises NameError: name 'my_variable' is not defined
To Avoid Name Errors:
- Always define variables before using them.
- Check for typos in variable names.
- Values and Types
- Common Data Types in Python:
- int: Integer numbers (e.g., 10, -5)
- float: Floating-point numbers (e.g., 3.14, -0.001)
- str: Strings (e.g., "Hello", "123")
- bool: Boolean values (True or False)
- Checking Types: Use the type() function to determine a variable’s type.
- Python code
- type(age) # <class 'int'>
- type(name) # <class 'str'>
Statements
Definition:
- A statement is a line of code that performs an action. Statements can include variable assignments, function calls, loops, conditionals, etc.
Examples of Different Statements:
- Variable Assignment:
- Python code
- x = 10
Function Call:
- Python code
- print("Hello, World!")
Conditional Statement:
- Python code
- if x > 5:
- print("x is greater than 5")
Loop Statement:
- Python code
- for i in range(5):
- print(i)
Summary
Understanding variables, expressions, and statements is fundamental to programming in Python. This knowledge forms the basis for building more complex logic, data manipulation, and algorithms. By mastering these concepts, you’ll be well-prepared to tackle advanced programming tasks.