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) outputs 123.
      • Example: >>> print(98.6) outputs 98.6.
    • String Constants: Text values enclosed in single quotes (') or double quotes (").
      • Example: >>> print('Hello world') outputs Hello world.
  • 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, True
      • and, as, assert, async, await
      • break, class, continue
      • def, del, elif, else, except
      • finally, for, from, global
      • if, import, in, is, lambda
      • nonlocal, not, or, pass, raise
      • return, try, while, with, yield

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 line x = 100 replaces the original value in that memory location.
  • Mechanics of Assignment:
    • In an expression like x=3.9×x×(1−x)x = 3.9 \times x \times (1 - x), the right side is evaluated first.
    • Once the expression is calculated, the resulting value is placed into (assigned to) the variable x on 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, and SPAM are 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).

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:
    1. Obfuscated naming: python x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print(x1q3p9afd)         
    2. Short/Generic naming: python a = 35.0 b = 12.50 c = a * b print(c)         
    3. Mnemonic naming: python hours = 35.0 rate = 12.50 pay = hours * rate print(pay)         

Numeric Expressions and Operators

  • Operators: Because keyboards lack certain mathematical symbols, Python uses specific characters to represent operations.
OperatorOperationExample
+Additionxx=xx+2xx = xx + 2
-Subtraction5−2=35 - 2 = 3
*Multiplicationyy=440×12yy = 440 \times 12
/Divisionzz=yy/1000zz = yy / 1000
**Power (Exponentiation)4∗∗34 ** 3 (which is 43=644^3 = 64)
//Floor Division23//5=423 // 5 = 4
%Remainder (Modulo)23%5=323 \% 5 = 3
  • Modulo Operator: Typically used to find the remainder of a division operation. For example, dividing 2323 by 55 results in 44 with a remainder of 33.
  • Floor Division: This operator divides two numbers and rounds the result down to the nearest integer value.
    • Example: >>> print(9 // 2) outputs 4.
    • Example: >>> print(-7.0 // 2.0) outputs -4.0.

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):

    1. Parentheses: Always respected first.
    2. Power: Exponentiation (∗∗**).
    3. Multiplicative Group: Multiplication (*), Division (/), Floor Division (//), and Remainder (%).
    4. Additive Group: Addition (+) and Subtraction (-).
    5. Left to Right: If operators have the same precedence level, they are evaluated starting from the left.
  • Example Evaluation:     Expression: 1+2∗∗3/4×51 + 2 ** 3 / 4 \times 5

    1. 2∗∗3=82 ** 3 = 8
    2. 8/4=2.08 / 4 = 2.0
    3. 2.0×5=10.02.0 \times 5 = 10.0
    4. 1+10.0=11.01 + 10.0 = 11.0
  • 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., −14,0,100-14, 0, 100).
    • Floating Point Numbers (float): Numbers with decimal parts (e.g., −2.5,0.0,98.6-2.5, 0.0, 98.6).
  • 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() and float() functions to manually convert values.
      • float(99) results in 99.0.
      • int(123.45) truncates the decimal to become 123.
    • 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() or float() if the string contains only numeric characters. If the string contains non-numeric characters (e.g., 'hello bob'), Python will raise a ValueError.

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.
  • 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) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

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