xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Running Python

Basics6 min readLesson 1 of 8

Python reads your instructions and carries them out. You can use it in two ways: type one line at a time in the interactive shell, or save several lines in a file and run the whole script. The shell is quick for small tests, and a file keeps work that you want to run again.

python
# Save this as hello.py
print('Hello, world!')
print('This file runs from top to bottom.')

1.1 The shell

To open the shell, type python in a terminal, or py on Windows installations that provide it. The >>> prompt means Python is waiting for one statement. Type exit() to leave.

1.2 Running a saved file

  1. Open a terminal in the folder that holds the file.
  2. Type python hello.py.
  3. Press Enter and read the output from top to bottom.

Python reads the file from the first line to the last and stops if a line fails.

python
total = 7 + 5
print('The total is', total)
print('The program has finished.')

1.3 When the file will not run

A common mix-up is running a file from the wrong folder. python hello.py looks for hello.py in the folder where the terminal is open, so a FileNotFoundError usually means one of these:

  • the path is wrong
  • the file was saved under another name
  • the terminal is open in a different folder

Check the folder in your file browser and run the command from there. Saving the file with a .py extension also helps the editor and the terminal treat it as Python source.

python
# Text keeps its quote marks off the screen.
print('2 + 2')
print(2 + 2)

1.4 Practice

  1. Create a file named first.py with two print calls, then run it.
  2. Change one message and run the file again.
  3. Type a single expression after the >>> prompt in the shell and press Enter.

If the terminal cannot find the file, check the folder before you touch the code.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01What is the difference between the Python shell and a Python script?

    The shell runs one statement at a time and shows results immediately. A script is a file of statements that Python runs from top to bottom when you pass the file to the interpreter.

  • 02How do you run hello.py from a terminal?

    Open the terminal in the folder that contains the file, then run `python hello.py`, or `py hello.py` on Windows.

  • 03What happens when Python hits an error in a script?

    Python stops at the failing line and prints a traceback. Statements before it have already run, and later lines do not run.

Quiz

Starting with Python

Two questions on the REPL, scripts and how Python reads a file.

2 questions

Question 1 of 2

0/2 answered

Which command opens the interactive Python REPL?

Answer all you can, then submit.