In the examples below, input and output are distinguished by the presence or absence of prompts (
>>> and ...). To try these examples, type everything after the prompt.Using Python as a Calculator
Numbers
The interpreter acts as a simple calculator. You can type expressions and get results:Variables
Use the equal sign (=) to assign values:
The Special _ Variable
In interactive mode, the last printed expression is assigned to _:
Treat
_ as read-only. Don’t assign to it explicitly, as this creates a new local variable that masks the built-in behavior.Text (Strings)
Python can manipulate text using thestr type. Strings can be enclosed in single or double quotes:
Escaping Quotes
To include quotes in strings, escape them with\ or use the other quote type:
Special Characters
Theprint() function produces more readable output:
Raw Strings
Use raw strings (prefix withr) to prevent backslash interpretation:
Multi-line Strings
Use triple quotes for strings spanning multiple lines:String Operations
Concatenation and repetition:Indexing and Slicing
Strings can be indexed (subscripted):String Immutability
String Length
Lists
Lists are compound data types that group together values:Indexing and Slicing Lists
Like strings, lists support indexing and slicing:List Concatenation
List Mutability
Unlike strings, lists are mutable:Adding Items
Assignment and References
Modifying Lists
Assignment to slices:Nested Lists
First Steps Towards Programming
Let’s write a Fibonacci series using awhile loop:
- Multiple assignment:
a, b = 0, 1assigns simultaneously - While loop: Executes as long as the condition is true
- Indentation: Python uses indentation to group statements
- Print function: Writes output to the screen
Customizing Print Output
Control the line ending with theend parameter:
