Reference ยท grows with each lesson

Python basics

The bare minimum to write and run a script.

Running a script

CommandWhat it does
python3 --versionShows the installed Python version.
python3 hello.pyRuns the file hello.py from top to bottom.
cd folderGoes into a folder.
mkdir folderCreates a folder.

Syntax

IdeaExampleNote
Show on screenprint("Hello")The text goes between quotes.
Store in a variablename = "Ana"= stores; it doesn't compare.
Reassignname = "Luis"The previous value is lost.
Join texts"Hello, " + namePython doesn't add spaces on its own.
Comment# Python ignores thisFor human notes.

Text vs. variable

name = "Ana"
print("name")   # name
print(name)     # Ana

Input, types and conversion

IdeaExampleNote
Ask for datax = input("Domain? ")Always returns text.
See the typetype(5)str text, int integer, float decimal.
Text to integerint("5")Fails with ValueError if it isn't a number.
Number to textstr(5)Needed to join with +.
Count characterslen("python.org")Returns 10.
Repeat text"5" * 2Gives "55"; with numbers it would be 10.

Reading an error

  1. Look at the last line: the error type and its description.
  2. Look at the line number Python gives.
  3. The ^ points to the approximate place of the problem.
MessageMeans
SyntaxError: unterminated string literalQuotes were opened and never closed.
TypeError: can only concatenate str (not "int") to strYou tried to join text with an integer using +. Convert with str().
ValueError: invalid literal for int() with base 10: 'abc'int() received a text that isn't a number.

Source: Automate the Boring Stuff, ch. 1.