Variables, Expressions, and Statements

Chapter Overview

  • Chapter 2 of Python for Everybody, focusing on the fundamental concepts of variables, expressions, and statements in Python.

Constants

  • Definition: Fixed values used in programming that do not change.

    • Types of Constants:

    • Numeric Constants: Regular numerical values (e.g., integers, floats).

    • String Constants: Enclosed in single (') or double (") quotes.

  • Examples:

    • python print(123) # Output: 123 print(98.6) # Output: 98.6 print('Hello world') # Output: Hello world

Reserved Words

  • Definition: Words that cannot be used as variable names due to their reserved status in Python syntax.

  • List of Reserved Words:

    • False, await, else, import, pass

    • None, break, except, in, raise

    • True, class, finally, is, return

    • and, continue, for, lambda, try

    • as, def, from, nonlocal, while

    • assert, del, global, not, with

    • async, elif, if, or, yield

Variables

  • Definition: A named location in memory where data can be stored and retrieved.

  • Characteristics:

    • Programmers can choose the names of variables at their discretion.

    • Variable contents can be altered in subsequent statements.

  • Example of Assignment:

    • python x = 12.2 y = 14 x = 100 # Changing x's value

Python Variable Name Rules

  • Naming Conventions:

    • Must start with a letter or underscore (_).

    • Can consist of letters, numbers, and underscores.

    • Is case sensitive (e.g., spam, Spam, SPAM are different).

  • Examples of Valid and Invalid Names:

    • Good: spam, eggs, spam23, _speed

    • Bad: 23spam, #sign, var.12

Mnemonic Variable Names

  • Concept: Using meaningful names as a memory aid to remember the value represented.

    • Well-chosen names may sound appealing, potentially causing confusion if they resemble reserved keywords.

    • Refer to Wikipedia on Mnemonics for further information.

Code Examples and Explanation

  • Sample Code Snippet:

    • python x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print(x1q3p9afd)

    • This code assigns and multiplies two values, storing the result in x1q3p9afd, and prints the result.

  • Similar examples are provided with varied variable names to demonstrate that the underlying operations remain the same.

Assignment Statements

  • Definition: Used to assign a value to a variable with the equals sign (=).

  • Syntax: Comprises an expression on the right-hand side and a variable on the left-hand side.

  • Examples:

    • python x = 3.9 * x * (1 - x)

    • After evaluation, the result is stored in the variable x.

Numeric Expressions

  • Operations: All basic mathematical operations done in Python using specific symbols:

    • +: Addition

    • -: Subtraction

    • *: Multiplication

    • /: Division

    • **: Exponentiation (power)

    • %: Remainder (modulus)

  • Examples:

    • python xx = 2 xx = xx + 2 # Output: 4

  • The use of these symbols is essential for performing calculations in Python.

Order of Evaluation

  • Importance: Determines the sequence in which operations are performed based on operator precedence.

    • Higher precedence operations are calculated before lower precedence ones.

  • Operator Precedence Rules:

    1. Parentheses

    2. Exponentiation (**)

    3. Multiplication (*), Division (/), Remainder (%)

    4. Addition (+), Subtraction (-)

    5. Left to Right

  • Using parentheses helps clarify complex expressions and prioritize certain calculations.

Type in Python

  • Definition: The classification of values (e.g., integer, float, string).

    • Python differentiates between types, allowing operations specific to each.

  • Example:

    • python ddd = 1 + 4 # Integer addition eee = 'hello ' + 'there' # String concatenation

Type Matters

  • Behavior: Certain operations depend on types. For instance, concatenating a string and an integer without conversion will result in an error.

  • Checking Types: Use the type() function to determine the type of a variable.

    • Example of an error due to type mismatch:

    • python eee = 'hello ' + 'there' eee = eee + 1 # Raises TypeError

Different Types of Numbers

  • Main Types:

    • Integers: Whole numbers (e.g., -14, -2, 0)

    • Floating Point Numbers: Numbers with decimals (e.g., -2.5, 98.6)

  • Examples of Type Checking:

    • python xx = 1 temp = 98.6 type(xx) # Output: <class 'int'> type(temp) # Output: <class 'float'>

Type Conversions

  • Concept: When mixing integers and floats, integers are implicitly converted to floats.

  • Control Conversion: Use built-in functions int() and float() to manually convert types as needed.

    • Example of floating point conversion:

    • python print(float(99) + 100) # Output: 199.0

Integer Division

  • Definition: Division where the result is always a float in Python 3.x (unlike Python 2.x where it behaved differently).

  • Examples:

    • python print(10 / 2) # Output: 5.0 print(9 / 2) # Output: 4.5

String Conversions

  • Converting between strings and numerical types requires care. If the string is non-numeric, an error will occur:

    • python sval = '123' ival = int(sval) # Converts '123' to integer print(ival + 1) # Output: 124 nsv = 'hello' niv = int(nsv) # Raises ValueError

User Input

  • Getting Input: Use the input() function to pause the program and read data from users.

    • Example:

    • python nam = input('Who are you? ') print('Welcome', nam) # Outputs: Welcome [User's Name]

Converting User Input

  • User input is always read as a string; conversions are necessary for numerical data.

    • Example:

    • python inp = input('Europe floor? ') usf = int(inp) + 1 print('US floor', usf) # Outputs US floor based on user input

Comments in Python

  • Usage: Anything after a # is ignored by the interpreter. Comments are useful for:

    • Describing code functionality.

    • Documenting authorship, or other important information.

    • Temporarily disabling code lines during testing or debugging.

Example of Code with Comments

  • ```python

Get the name of the file and open it

name = input('Enter file:')
handle = open(name, 'r')

Count word frequency

counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1

Find the most common word

bigcount = None
bigword = None
for word, count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count

All done

print(bigword, bigcount)
```

Summary

  • Key topics covered in this chapter include:

    • Type of variables

    • Reserved words in Python

    • Principles of variable naming (including mnemonic names)

    • Operators and operator precedence in expressions

    • Integer division vs. floating-point results

    • Type conversion between numerics and strings.

    • User input handling and converting inputs.

    • Importance of comments for code documentation and clarity.

Exercise

  • Prompt users for hours and rate per hour to compute gross pay:

    • Example Input:

    • Enter Hours: 35

    • Enter Rate: 2.75

    • Example Output:

    • Pay: 96.25