Prepstellar

Python Fundamentals · Python Runtime and Core Syntax

22 cards

Interpreter and Program Basics

Swipe, scroll or use ← →
  1. Choose between exploring and running

    Before writing a single line, decide how the code will reach the interpreter. That choice is not cosmetic: it decides whether you get an immediate answer to one idea or a repeatable program you can run again tomorrow.

    The interpreter behaves somewhat like a Unix shell. When it is called with its standard input connected to a terminal, it reads and executes commands interactively. When it is called with a file name argument, or with a file as standard input, it reads and executes a script from that file.

    How you start it What it does What it is for
    Terminal input, no file Reads and executes commands as you type them Immediate exploration: try an expression, see the result
    A file name argument, or a file as standard input Reads and executes the script held in that file Repeatable program execution

    These are two distinct working modes, and everything else in this concept is a variation on one of them.

    1 / 22
  2. Choose between exploring and running

    The command that starts the interpreter is not fixed. The directory where the interpreter lives is an installation option: on many Unix machines it is /usr/local/bin/python3.14, and putting that directory on the shell search path makes python3.14 enough to start it. Other locations are possible, and on Windows the python3.14 command is available after a Microsoft Store install, while the py command comes from the py.exe launcher.

    So python in the command forms below stands for whichever launcher is correct on your machine, not for a universal program name.

    To leave an interactive session, type the end-of-file character at the primary prompt — Control-D on Unix, Control-Z on Windows. If that does nothing, call quit().

    2 / 22
  3. Quick check

    You start the interpreter by giving it the name of a Python file on the command line. What happens?

    1. AIt opens an interactive session and leaves the file untouched until you import it

      Interactive execution is what you get when standard input is a terminal and no file was supplied; a file name argument selects the other mode.

    2. BIt reads that file and executes the script it contains

      Right. A file name argument, like a file supplied as standard input, makes the interpreter read and execute the script in that file.

    3. CIt passes each line of the file to the shell as a command

      The interpreter executes Python statements from the file; the lines are not handed to the shell.

    3 / 22

  4. Send code without writing a script file

    Two command-line forms let you run Python without creating a file at all, and they are easy to confuse because both take something that looks like a name.

    The form python -c command [arg] ... executes the statements inside command. Python statements often contain spaces and other characters that the shell treats specially, so the complete command is usually quoted:

    python -c "print(2 + 2)"
    

    The form python -m module [arg] ... locates a module and executes its source as a script, exactly as if you had spelled out its full path on the command line. It is how a module that is also useful as a tool gets run.

    Form What actually runs When to reach for it
    python script.py The named file Normal program execution
    python -c "statements" The quoted statements themselves A one-off calculation or check
    python -m package.module The located module's source, run as a script Running an installed module as a tool
    4 / 22
  5. Quick check

    Which command form finds a module by name and then runs that module's source as a script?

    1. A`python -m module [arg] ...`, with the option placed just before the module name

      Right. The `-m` option precedes the module name, and the interpreter locates that module and executes its source as a script.

    2. B`python -c module [arg] ...`, since any bare name written after `-c` is treated as a module

      `-c` treats the value that follows it as Python statements to execute, so a bare module name would be run as code, not located.

    3. C`python module -m [arg] ...`, since the option follows the name

      An interpreter option has to come before the name it applies to; written afterwards it no longer selects module execution.

    5 / 22

  6. Keep the prompt after a script has run

    Sometimes running a script is only half the job: you also want to poke at the variables it left behind. Passing -i before the script runs that script and then enters interactive mode, so the session continues at the prompt with the script's state still in memory.

    python -i inspect.py
    

    A related form is a script name of -, which means the script itself is read from standard input. That still selects script execution; it does not add a prompt afterwards.

    Keep the four roles apart: -c supplies statements, -m supplies a module, - supplies a script through standard input, and -i adds an interactive session once a script has finished.

    6 / 22
  7. Quick check

    A developer must run `inspect.py` from disk and then immediately examine the values it produced, at a prompt. Which choice does both?

    1. APass `-` as the script name so the file arrives through standard input

      A script name of `-` only changes where the script comes from; the session still ends when the script ends.

    2. BWrite `-m` after the script name so the file is located as a module

      `-m` belongs before a module name and would not run an already named file and then open a prompt.

    3. CPass `-i` before the script name so the prompt opens once it finishes

      Right. `-i` placed before the script runs that script and then enters interactive mode, keeping its state available.

    7 / 22

  8. Keep your progress in the app

    That’s 3 of 9 quick checks. In the app they stay answered, and every lesson remembers where you left off.

  9. See the arguments your program received

    A program usually needs to know what it was asked to do. When they are known to the interpreter, the script name and the arguments after it are turned into a list of strings and assigned to the argv variable in the sys module. Import sys to reach that list:

    import sys
    print(sys.argv)
    

    Two properties matter in practice. The elements are strings — nothing is converted to a number for you. And the list always has at least one element: when neither a script nor arguments are given, sys.argv[0] is an empty string rather than a missing value.

    sys.argv is one ordinary list. Python does not create a separate global variable per argument, and this list is not the module search path.

    8 / 22
  10. Quick check

    How does Python hand a script its name and the arguments typed after it?

    1. AAs string elements of the list `sys.argv`, reachable after `import sys`

      Right. The script name and later arguments become a list of strings assigned to `argv` in the `sys` module.

    2. BAs numbers in a tuple, converted by the interpreter first

      Arguments stay strings and the container is a list; no numeric conversion happens on the way in.

    3. CAs one global variable per argument, created automatically in the program's namespace

      Arguments are elements of a single list, not separate names invented in the program's namespace.

    9 / 22

  11. Read the invocation form from sys.argv[0]

    The first element does more than name a file: it tells the program how it was started.

    How the interpreter was invoked Value of sys.argv[0]
    No script and no arguments An empty string
    A script name That script name
    Script name given as - (standard input) -
    -c command -c
    -m module The full name of the located module
    10 / 22
  12. Read the invocation form from `sys.argv[0]`

    There is a second rule that protects your program's own options. Anything found after the command supplied to -c, or after the module supplied to -m, is not consumed by the interpreter's option processing: it stays in sys.argv for that command or module to handle.

    So python -m tools.report weekly --quiet gives the module a list whose first element is tools.report and whose remaining elements are weekly and --quiet. The --quiet flag is not stolen by the interpreter on the way through, which is exactly what lets a module define its own command-line interface.

    11 / 22
  13. Quick check

    A module is started with `python -m tools.report weekly --quiet`. Which description of `sys.argv` is correct?

    1. AElement zero is `-m`, and the interpreter consumes the two trailing values as its own options

      The `-m` marker itself never becomes element zero, and values after the module name are left alone by option processing.

    2. BElement zero is the located module's full name, and both trailing values stay available to the module

      Right. With `-m`, element zero is the full name of the located module, and later values remain in the list for that module to handle.

    3. CElement zero is an empty string, so only `weekly` reaches the module as an argument

      An empty element zero describes the case where no script and no arguments were given at all.

    12 / 22

  14. Work at the interactive prompt

    When commands are read from a terminal device, the interpreter is said to be in interactive mode. Before the first prompt it prints a welcome message stating its version number and a copyright notice, so the first thing on screen already tells you which interpreter you reached.

    Two prompts then take turns:

    Prompt Name Meaning
    >>> Primary prompt The interpreter wants a new command
    ... Secondary prompt The interpreter wants a continuation line
    13 / 22
  15. Work at the interactive prompt

    Continuation lines are needed when you enter a multi-line construct. Typing an if statement shows both prompts at work:

    >>> the_world_is_flat = True
    >>> if the_world_is_flat:
    ...     print("Be careful not to fall off!")
    ...
    Be careful not to fall off!
    

    The construct kept asking for more input at the secondary prompt, and a blank line completed it. That blank line is how you tell the interpreter that a multi-line command entered interactively is finished, which is why nothing ran until it was typed.

    14 / 22
  16. Quick check

    While typing a multi-line `if` interactively, which prompt appears, and what ends the command?

    1. A`>>>` appears for each extra line, and the command ends when the indentation returns to the margin

      Three greater-than signs are the primary prompt, shown when the interpreter is ready for a brand-new command.

    2. B`---` appears for each extra line, and the command ends when a closing keyword is typed

      Three hyphens are not one of the interpreter's prompts, and no closing keyword terminates the construct.

    3. C`...` appears for each extra line, and the command ends when a blank line is entered

      Right. Continuation lines use the secondary prompt of three dots, and a blank line completes a multi-line command entered interactively.

    15 / 22

  17. Diagnose a prompt without line editing

    Interpreter behavior can depend on installation and environment settings, and the interactive editing conveniences are among the parts that depend on system support. They are not guaranteed just because the prompt appeared.

    There is a quick test. Type a word at the prompt, then press Left arrow. If the cursor moves, command-line editing is available. If nothing seems to happen, or a sequence such as ^[[D or ^B is printed on the line, command-line editing is not available, and only Backspace will remove characters from the current line.

    That is an environment finding, not a program error. The session is still interactive and still runs your code; you simply edit the current line with Backspace until the environment offers more.

    16 / 22
  18. Quick check

    At the prompt, pressing Left arrow prints `^[[D` instead of moving the cursor. The session must continue. What does this tell you?

    1. AInteractive mode failed to start, so the interpreter must be restarted

      The visible prompt proves interactive mode is already running, so nothing about the session needs restarting.

    2. BThe file's source encoding is wrong, so a coding declaration has to be typed in

      Source encoding governs how a file's bytes are read, which has nothing to do with arrow-key support at a prompt.

    3. CCommand-line editing is unavailable here, so only Backspace edits the current line

      Right. A printed escape sequence means the environment offers no command-line editing, leaving Backspace as the way to remove characters from the current line.

    17 / 22

  19. Declare a source encoding when the default is not enough

    Python treats source files as encoded in UTF-8 by default. In that encoding, characters of most of the world's languages can be used at the same time in string literals, identifiers and comments — although the standard library uses only ASCII characters for identifiers, a convention that portable code should follow.

    Two things outside Python have to cooperate for those characters to appear correctly: your editor must recognize that the file is UTF-8, and it must use a font that supports every character in the file. A file can be perfectly valid and still look like nonsense in the wrong editor.

    18 / 22
  20. Declare a source encoding when the default is not enough

    To declare a codec other than the default, add a special comment line as the first line of the file:

    # -*- coding: cp1252 -*-
    

    There is one exception to that first-line rule. If the source starts with a Unix shebang line, the encoding declaration goes on the second line, immediately after it:

    #!/usr/bin/env python3
    # -*- coding: cp1252 -*-
    

    The declaration is a comment line at the top of the file. It is not something you place at the end of the program or hide inside a string.

    19 / 22
  21. Quick check

    A script begins with a Unix shebang line and needs the `cp1252` codec. Where does the encoding declaration belong?

    1. AOn the second line, immediately after the shebang

      Right. A shebang on line one is the documented exception, so the encoding comment moves to the second line.

    2. BOn the last line, after every Python statement

      An encoding declaration is read at the top of the file; placed after the statements it would come far too late.

    3. CInside the program's first string literal

      The declaration is a special comment line, not text stored inside a string literal.

    20 / 22

  22. Key takeaways

    • The input decides the mode: a terminal gives interactive execution, while a file name or a file supplied as standard input gives script execution.
    • Three shortcuts, three jobs: -c runs quoted statements, -m locates a module and runs its source as a script, and -i before a script opens the prompt once that script finishes.
    • sys.argv is a list of strings with at least one element, reached after import sys; its first element identifies the invocation — an empty string, a script name, -, -c, or a located module's full name.
    • Your program keeps its own options: values after a -c command or a -m module stay in sys.argv instead of being consumed by the interpreter.
    • The prompt speaks twice: >>> asks for a new command, ... asks for a continuation line, and a blank line completes a multi-line command.
    • Source files are UTF-8 unless declared otherwise, with the declaration on the first line — or the second, after a shebang.
    21 / 22
  23. Quick check

    A source file carries no encoding declaration at all. How is it read?

    1. AAs ASCII, the encoding the standard library uses for its identifiers

      ASCII identifiers are a portability convention followed by the standard library, not the encoding applied to source files.

    2. BAs UTF-8, the default encoding for Python source files

      Right. Python treats source files as UTF-8 by default; any other supported codec has to be declared explicitly.

    3. CAs the codec the editor last saved with, which Python detects on opening

      Python applies the default encoding or an explicit declaration; it does not adopt whatever the editor happened to use.

    22 / 22

  24. 9 quick checks · then the test

    In the app, finishing the quick checks opens this lesson’s 10-question test, and the ones you miss come back exactly when you’re about to forget them.

The whole course, on your phone

Lessons you can read, audio you can listen to on the way to work, and practice that remembers what you got wrong.