Reference ยท grows with each lesson
Python basics
The bare minimum to write and run a script.
Running a script
| Command | What it does |
python3 --version | Shows the installed Python version. |
python3 hello.py | Runs the file hello.py from top to bottom. |
cd folder | Goes into a folder. |
mkdir folder | Creates a folder. |
Syntax
| Idea | Example | Note |
| Show on screen | print("Hello") | The text goes between quotes. |
| Store in a variable | name = "Ana" | = stores; it doesn't compare. |
| Reassign | name = "Luis" | The previous value is lost. |
| Join texts | "Hello, " + name | Python doesn't add spaces on its own. |
| Comment | # Python ignores this | For human notes. |
Text vs. variable
name = "Ana"
print("name") # name
print(name) # Ana
Input, types and conversion
| Idea | Example | Note |
| Ask for data | x = input("Domain? ") | Always returns text. |
| See the type | type(5) | str text, int integer, float decimal. |
| Text to integer | int("5") | Fails with ValueError if it isn't a number. |
| Number to text | str(5) | Needed to join with +. |
| Count characters | len("python.org") | Returns 10. |
| Repeat text | "5" * 2 | Gives "55"; with numbers it would be 10. |
Reading an error
- Look at the last line: the error type and its description.
- Look at the line number Python gives.
- The
^ points to the approximate place of the problem.
| Message | Means |
SyntaxError: unterminated string literal | Quotes were opened and never closed. |
TypeError: can only concatenate str (not "int") to str | You 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.