Overview
This lecture covers fundamental programming concepts such as variables, constants, input/output, assignments, data types, and casting, using a Python dice game as an example.
Variables and Constants
- A variable is a named address in memory used to store values that can change during program execution.
- In Python, you assign a value to a variable using the equals sign (e.g., total = 0).
- A constant is a value set at design time that does not change while the program is running.
- Python does not natively support constants, so programmers must avoid changing their values manually.
- Constants are usually declared at the top of the program for readability and easier updates.
Assignments and Operators
- Assignment assigns the value on the right to the variable/constant on the left using the equals sign.
- Operators, such as +, can be used for arithmetic or string concatenation (joining two strings).
- The same operator symbol can perform different tasks depending on context, known as operator overloading.
Input, Output, and Casting
- Input gathers data from the user, usually via keyboard, often using the input() command in Python.
- Output displays data to the user, typically using print statements in Python.
- Casting converts data from one type to another, e.g., input from a keyboard (string) to an integer using int().
- Casting is also used to convert variables between types for processing or compatibility reasons.
Data Types
- Four key data types:
- Integer: whole numbers (positive or negative).
- Real/Float: numbers with decimal parts.
- Character: a single alphanumeric symbol (e.g., 'A', '1').
- String: a sequence of characters (e.g., "hello", "123").
- Integers are more memory-efficient than floats and are preferred when decimals aren't needed.
Advantages of Constants
- Easier to read and maintain code by changing a value only in one place.
- Reduces chance of errors by preventing accidental value changes.
- Allows the compiler to optimize code better, improving program speed.
Key Terms & Definitions
- Variable — a memory location with a user-friendly name that can store changing values.
- Constant — a fixed value set at design time and not changed during execution.
- Assignment — the process of giving a value to a variable or constant.
- Casting — converting a variable from one data type to another.
- Input — data received from an input device like a keyboard.
- Output — data shown to the user, such as printed text.
- Data Type — specifies the kind of value a variable holds (integer, float, character, string).
Action Items / Next Steps
- Review the examples in the Python dice game code.
- Understand the difference between variables, constants, and when to use each.
- Practice writing Python code that includes input, output, assignment, and casting.
- Read further on arithmetic operators and their uses in programming.