Python Basics: Variables, Expressions, and Statements
Constants and Reserved Words
Constants: Constants are fixed values, such as numbers, letters, and strings. They are called "constants" because their value does not change throughout the execution of the program.
- Numeric Constants: Standard numbers, such as integers or floating-point values.
- Example:
>>> print(123)outputs123. - Example:
>>> print(98.6)outputs98.6.
- Example:
- String Constants: Text values enclosed in single quotes (') or double quotes (").
- Example:
>>> print('Hello world')outputsHello world.
- Example:
- Numeric Constants: Standard numbers, such as integers or floating-point values.
Reserved Words: You cannot use these specific words as variable names or identifiers because Python has already assigned them a specific meaning.
- List of Reserved Words:
False,None,Trueand,as,assert,async,awaitbreak,class,continuedef,del,elif,else,exceptfinally,for,from,globalif,import,in,is,lambdanonlocal,not,or,pass,raisereturn,try,while,with,yield
- List of Reserved Words:
Variables and Assignment
- Variable Definition: A variable is a named location in the computer's memory where a programmer can store data and later retrieve it using the variable name assigned to it.
- Assignment Statement: We use the assignment operator (
=) to assign a value to a variable.- The statement consists of an expression on the right-hand side and a variable on the left-hand side to store the result.
- Example:
x = 12.2,y = 14.
- Dynamic Nature: You can change the contents of a variable in a later statement. For example, if
x = 12.2, a subsequent linex = 100replaces the original value in that memory location. - Mechanics of Assignment:
- In an expression like , the right side is evaluated first.
- Once the expression is calculated, the resulting value is placed into (assigned to) the variable
xon the left. - This process allows the variable to be updated by replacing its old value with a new one.
Python Variable Naming Rules
- Starting Characters: A variable name must start with a letter or an underscore (
_). - Allowed Characters: It must consist only of letters, numbers, and underscores.
- Case Sensitivity: Variable names are case-sensitive, meaning
spam,Spam, andSPAMare three different variables. - Examples of Naming:
- Good Names:
spam,eggs,spam23,_speed. - Bad Names:
23spam(starts with a number),#sign(contains an illegal character),var.12(contains a period).
- Good Names:
Mnemonic Variable Names
- Definition: A "mnemonic" is a memory aid. In programming, best practice dictates choosing variable names that help the programmer remember what data is intended to be stored in them.
- Clarity vs. Confusion: While Python does not care what you name your variables (as long as rules are followed), humans benefit from descriptive names. However, well-named variables can sometimes confuse beginners into thinking the variable names are actually built-in Python keywords.
- Comparative Examples:
- Obfuscated naming:
python x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print(x1q3p9afd) - Short/Generic naming:
python a = 35.0 b = 12.50 c = a * b print(c) - Mnemonic naming:
python hours = 35.0 rate = 12.50 pay = hours * rate print(pay)
- Obfuscated naming:
Numeric Expressions and Operators
- Operators: Because keyboards lack certain mathematical symbols, Python uses specific characters to represent operations.
| Operator | Operation | Example |
|---|---|---|
+ | Addition | |
- | Subtraction | |
* | Multiplication | |
/ | Division | |
** | Power (Exponentiation) | (which is ) |
// | Floor Division | |
% | Remainder (Modulo) | |
- Modulo Operator: Typically used to find the remainder of a division operation. For example, dividing by results in with a remainder of .
- Floor Division: This operator divides two numbers and rounds the result down to the nearest integer value.
- Example:
>>> print(9 // 2)outputs4. - Example:
>>> print(-7.0 // 2.0)outputs-4.0.
- Example:
Operator Precedence (Order of Evaluation)
Precedence Rules: When multiple operators are used in one expression, Python follows a specific order of evaluation (from highest to lowest precedence):
- Parentheses: Always respected first.
- Power: Exponentiation ().
- Multiplicative Group: Multiplication (
*), Division (/), Floor Division (//), and Remainder (%). - Additive Group: Addition (
+) and Subtraction (-). - Left to Right: If operators have the same precedence level, they are evaluated starting from the left.
Example Evaluation: Expression:
Best Practices: Use parentheses to make logic clear and break long mathematical operations into smaller steps to improve readability.
Data Types and Conversions
- Concept of "Type": Variables, literals, and constants in Python have a type. Python uses types to determine what operations are valid.
+used on numbers means addition:1 + 4 = 5.+used on strings means concatenation (putting strings together):'hello ' + 'there'becomes'hello there'.
- The
type()Function: This built-in function allows you to identify the class of an object.>>> type('hello')returns<class 'str'>.>>> type(1)returns<class 'int'>.
- Numeric Types:
- Integers (
int): Whole numbers (e.g., ). - Floating Point Numbers (
float): Numbers with decimal parts (e.g., ).
- Integers (
- Type Conversions:
- Implicit Conversion: When mixing an integer and a float in an expression, Python converts the integer to a float automatically.
- Explicit Conversion: Use
int()andfloat()functions to manually convert values.float(99)results in99.0.int(123.45)truncates the decimal to become123.
- Division Note: Division using the
/operator always produces a floating-point result in Python, regardless of the input types.
- String Conversions: You can convert strings to numbers using
int()orfloat()if the string contains only numeric characters. If the string contains non-numeric characters (e.g.,'hello bob'), Python will raise aValueError.
User Input and Interaction
- The
input()Function: Pauses program execution to read data from the user.- Example:
name = input('Who are you? '). - Important: This function always returns the input as a string.
- Example:
- Converting Input: Since
input()returns a string, you must use a conversion function if you need to perform calculations on user-provided data.- Example for calculating floors:
python floor = input('Europe floor?') us_floor = int(floor) + 1 print('US floor', us_floor)
- Example for calculating floors:
Comments in Python
- Syntax: Anything following the
#symbol is treated as a comment and ignored by the Python interpreter. - Purpose of Comments:
- Describing a sequence of code logic.
- Documenting authorship or history.
- Temporarily disabling a line of code for testing.
Exercise
- Task: Write a program to prompt the user for hours and rate per hour to compute gross pay.
- Sample Execution:
- Enter Hours: 35
- Enter Rate: 2.75
- Pay: 96.25