Python Introduction: Variables, Data Types, and Abstraction
Fundamentals of Python and Abstraction
Sequence of Definition:
- A value must be defined before it can be used in a Python program.
Strings (
str):strrepresents text data and tells Python the type of data being printed.- String literals can be enclosed using single quotes (
'), double quotes ("), or other quote formats.
Output Statements and Functions:
- Code Statement Example:
print("Hello, world!") - Function Mechanics: The
printfunction describes how to show information on the screen. - Abstraction Concept: The
printfunction serves as an example of abstraction by encapsulating the lower-level mechanics of displaying output on a screen.
- Code Statement Example:
Variables and Memory Storage
Variable Definition and Storage:
- A variable acts as storage that holds a value in memory.
- Variables allow programmers to store and reuse text or values throughout code.
Variable Assignment and Execution:
- Text Reuse Example:
- Variable Assignment:
greeting = "Hello, world!" - Output Call:
print(greeting) - Program Output:
Hello, world! - Direct Value Assignment:
- Code Example:
my_value = 8 - Concept: Assigns the specific integer value directly to the variable
my_value.
Expression Assignment and Evaluation:
- A variable can be assigned an expression instead of a simple literal value.
- Code Example:
my_value = 3 + 5 - Evaluation Mechanics: When the program runs, the expression evaluates to the single value , which is then stored in
my_value. - Performing Computations with Variables:
- Step 1: Assign expression to variable:
my_value = 3 + 5(evaluates to ). - Step 2: Pass expression with variable to
print:print(my_value + 2) - Program Output: (computed as ).
Variable Naming Rules and Conventions
Allowed Characters:
- Variable names can contain letters, digits ( through ), and underscores (
_).
- Variable names can contain letters, digits ( through ), and underscores (
Numerical Placement Restrictions:
- A variable name cannot start with a number.
- Variable names are allowed to have numbers later in the name.
Exact Identifier Matching:
- Variable identifiers are distinct and must match accurately when called.
- The identifier
my-valueis different frommy_value. Callingmy-valuewhenmy_valuewas defined will not work.
Human vs. Computer Meaning:
- A variable name does not carry semantic meaning to the computer; it is processed strictly as a label.
- Meaningful variable names are selected solely to help humans read and comprehend the code.
Type Operations and Constraints
- String and Number Combination Restriction:
- Combining a string and a number directly using addition/concatenation is not permitted in Python.
- Invalid Attempt Example:
greeting = "hello" + 3followed byprint(greeting). - Note: Attempting to combine a string and an integer directly causes an error (to be gone over in detail later).