Introduction to Python Programming - Chapter 1

Background and Introduction to Python

  • Python Tools and Ecosystem Naming Conventions:

    • Software libraries and applications within the Python ecosystem frequently incorporate the letters "py" into their names.

    • Spotipy (https://openstax.org/r/100spotipy): A Python library providing access to Spotify online streaming services.

    • Pytube (https://openstax.org/r/100pytube): A Python library used for downloading and interacting with YouTube videos.

    • Pydora (https://openstax.org/r/100pydora): An API wrapper for Pandora online streaming.

  • Industry Usage and Significance:

    • Python (https://openstax.org/r/100python) is currently one of the top programming languages globally.

    • Extensive usage by major technological organizations and institutions, including Google, Apple, NASA, Instagram, and Pixar.

  • Core Reasons for Popularity:

    1. Rich Ecosystem of Libraries:

    • A library is a collection of pre-written code designed for reuse across different programs.

    • Standard Library (https://openstax.org/r/100pythlibrary): Built directly into Python to solve everyday computing tasks, such as extracting data from tables or generating summary reports.

    • Third-Party Libraries: Contributed by the global developer community. An prominent example is Pandas (https://openstax.org/r/100pandas), a standard library for data analysis.

    1. Concise and Straightforward Syntax:

    • Syntax defines the structural rules governing how code must be written, including keywords, symbols, and formatting.

    • Python syntax requires significantly less boilerplate code compared to older languages.

  • Example 1.1: Hello World Comparison:

    • By convention, "Hello World" (https://openstax.org/r/100helloworld) is the initial program written when learning a new language. It displays the message Hello, World! to the user.

    • Python Implementation (1 line of code):

    print("Hello, World!")
        ```
    - **Java Implementation** (5 lines of code):
    

    java public class Hello { public static void main(String[] args) { System.out.println("Hello, World!"); } }     ```

    • Trade-offs: Conciseness is not the sole factor in language selection. Specific application contexts require specific tools; for example, Java is heavily utilized in Android mobile development.

  • Concepts in Practice: Python vs Java Syntax:

    • Question 5: In general, Python programs are _____ than Java programs.

    • Options: a. faster, b. longer, c. shorter

    • Answer: c. shorter

    • Question 6: In the example programs above, what syntax required by Java is not required by Python?

    • Options: a. semicolons, b. parentheses, c. quote marks

    • Answer: a. semicolons

  • Practice Activity: Favorite Song Program:

    • In Python error messages, EOF stands for End of File.

    • Modifying a program to read multiple lines of input (e.g., name and song) requires successive calls to input(): python print("What is your favorite song?") song = input() print("Cool! I like", song, "too.")     

Basic Input and Output (I/O)

  • Basic Output (print() Function):

    • Displays information or results (output) to the user console.

    • Printing Multiple Values: Multiple comma-separated values can be passed into a single print() call. By default, Python outputs each value separated by a space character (" ").

    • Default Line Termination: The print() function automatically appends a newline character () at the end of its output, causing subsequent calls to output on a new line.

    • Customizing Separators (sep) and Endings (end):

    • sep: Specifies the string character(s) placed between multiple arguments.

    • end: Specifies the string character(s) appended at the end of the print statement.

  • Table 1.1: Examples of print() Function Customization:

    • Code:

    print("Today is Monday.")
    print("I like string beans.")
        ```
        *Output*:
    

    text Today is Monday. I like string beans.     ```

    • Code:

    print("Today", "is", "Monday")
    print("Today", "is", "Monday", sep="...")
        ```
        *Output*:
    

    text Today is Monday Today…is…Monday     ```

    • Code:

    print("Today is Monday, ", end="")
    print("I like string beans.")
        ```
        *Output*:
    

    text Today is Monday, I like string beans.     ```

    • Code:

    print("Today", "is", "Monday", sep="? ", end="!!")
    print("I like string beans.")
        ```
        *Output*:
    

    text Today? is? Monday!!I like string beans.     ```

  • Concepts in Practice: The print() Function:

    • Question 1: Which line of code prints Hello world! as one line of output?

    • Options: a. print(Hello world!), b. print("Hello", "world", "!"), c. print("Hello world!")

    • Answer: c. print("Hello world!")

    • Question 2: Which lines of code prints Hello world! as one line of output?

    • Options:

      • a. print("Hello") / print(" world!")

      • b. print("Hello") / print(" world!", end="")

      • c. print("Hello", end="") / print(" world!")

    • Answer: c

    • Question 3: What output is produced by the statement print("555", "0123", sep="-")?

    • Options: a. 555 0123, b. 5550123-, c. 555-0123

    • Answer: c. 555-0123

  • Importance of Formatting Precision:

    • While spaces and newline characters may seem minor, extreme precision is mandatory in programming to ensure correct output structure and execution.

  • Basic Input (input() Function):

    • Input is data provided by the user to a running program.

    • Standard syntax: variable = input("prompt")

    • Components of an Input Statement:

    1. Variable: A symbolic identifier referencing a specific location in memory where user input is stored.

    2. input() Function: A built-in, reusable block of code that halts execution, reads a single line of text entered by the user, and stores it into memory.

    3. Prompt: An optional string message displayed to the user prior to input entry.

  • Concepts in Practice: The input() Function:

    • Question 4: Which line of code correctly obtains and stores user input?

    • Options: a. input(), b. today_is = input, c. today_is = input()

    • Answer: c. today_is = input()

    • Question 5: Someone named Sophia enters their name when prompted with print("Please enter your name: ") and name = input(). What is displayed by print("You entered:", name)?

    • Options: a. You entered: name, b. You entered: Sophia, c. You entered:, Sophia

    • Answer: b. You entered: Sophia

    • Question 6: What is the output if the user enters "six" as the input for print("Please enter a number: "), number = input(), print("Value =", number)?

    • Options: a. Value = six, b. Value = 6, c. Value = number

    • Answer: a. Value = six

  • Try It Exercises: Input/Output:

    • Frost Poem: A program using multiple print() statements to output Robert Frost's poem line by line (https://openstax.org/r/100robertfrost):

    print("I shall be telling this with a sigh")
    print("Somewhere ages and ages hence:")
    print("Two roads diverged in a wood, and I--")
    print("I took the one less traveled by,")
    print("And that has made all the difference.")
        ```
    - **Name and Likes**: Program prompting for user inputs and printing formatted output:
    

    python name = input("What is your name? ") like = input("What do you like? ") print() print(name, "likes", like)          *Sample Interaction*: text What is your name? Shakira What do you like? singing

    Shakira likes singing     ```

Variables and Naming Rules

  • Assignment Statements:

    • Variables associate descriptive names with stored memory values (e.g., age stores an integer like 66, birth stores a text string like "May 15").

    • The assignment operator (=) assigns the evaluated expression on the right-hand side to the variable name on the left-hand side.

    • Note: The assignment operator (=) is non-directional equality, distinct from mathematical comparison (==).

  • Concepts in Practice: Assigning and Using Variables:

    • Question 1: Which line of code correctly retrieves the value of city after city = "Chicago"?

    • Options: a. print("In which city do you live?"), b. city = "London", c. print("The city where you live is", city)

    • Answer: c

    • Question 2: Which program stores and retrieves a variable correctly?

    • Options:

      • a. print("Total =", total) / total = 6

      • b. total = 6 / print("Total =", total)

      • c. print("Total =", total) / total = input()

    • Answer: b

    • Question 3: Which is the assignment operator?

    • Options: a. :, b. ==, c. =

    • Answer: c

    • Question 4: Which is a valid assignment?

    • Options: a. temperature = 98.5, b. 98.5 = temperature, c. temperature - 23.2

    • Answer: a

  • Variable Naming Rules and Guidelines:

    • Valid Structure: Can contain upper/lowercase letters, digits, and underscores (_). Can be of any length.

    • Forbidden Starts: Cannot start with a digit (e.g., 101class is illegal).

    • Case Sensitivity: Identifiers are strictly case-sensitive (Total and total refer to two distinct variables).

    • Snake Case Standard: Python official PEP 8 style guide mandates snake case for variable names (all lowercase with underscores between words, e.g., first_name, total_price).

    • Descriptive Naming: Prefer clear, short words over arbitrary single characters (e.g., count is preferred over c).

    • Keywords: Reserved words with built-in functionality that cannot be used as variable identifiers.

  • Table 1.2: Complete Table of Reserved Keywords in Python:

  | | | | | |   |---|---|---|---|---|   | 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 |   | asynch | elif | if | or | yield |

  • Concepts in Practice: Valid Variable Names:

    • Question 5: Which can be used as a variable name?

    • Options: a. median, b. class, c. import

    • Answer: a. median

    • Question 6: Why is 2nd_input an invalid variable name?

    • Options: a. contains an underscore, b. starts with a digit, c. is a keyword

    • Answer: b. starts with a digit

    • Question 7: Which would be a good name for a variable storing a zip code?

    • Options: a. z, b. var_2, c. zip_code

    • Answer: c. zip_code

    • Question 8: Given DogBreed, which improvement conforms to Python's style guide?

    • Options: a. dog_breed, b. dogBreed, c. dog-breed

    • Answer: a. dog_breed

  • Try It Exercise: Final Score:

    • Program specification and solution: python team1 = "Liverpool" team2 = "Chelsea" score1 = 4 score2 = 3 print(team1, "versus", team2) print("Final score:", score1, "to", score2)     

    • Output produced: text Liverpool versus Chelsea Final score: 4 to 3     

String Basics and Operations

  • String Definition and Quote Enclosure:

    • A string is an ordered sequence of characters enclosed inside matching single (') or double (") quotes.

    • Embedding Quote Marks Inside Strings:

    • Enclose double quotes inside single quote delimiters: `'They said