Skip to content

Chapter 2 of 7

Variables, Types, and Operators

Variables in Python are names that reference objects storing data. They are created automatically on first assignment, as in x = 5, and because Python uses dynamic typing, the type of a variable is determined at runtime rather than at compile time. This means a single variable can hold different types sequentially; for instance, you could write x = 5 followed by x = 'hello' without any type errors.

The basic immutable data types in Python include int for integers, float for floating-point numbers, str for strings, and bool for True and False values. Mutable types include lists and dictionaries. A special value called None represents the absence of a value and is a singleton object often used as a default return for functions without explicit return statements. When converting between types, you can use built-in functions like int(), float(), str(), and bool(); for example, int('42') converts the string '42' into the integer 42.

Python provides a rich set of operators for working with values. Arithmetic operators include +, -, *, /, // (floor division), % (modulo), and ** (exponentiation). Comparison operators such as ==, !=, >, <, >=, and <= return a boolean value: True or False. Logical operators include and (true when both operands are true), or (true when either operand is true), and not (negation), and they short-circuit evaluate, meaning they stop as soon as the result is determined.

For basic input and output, the print() function outputs objects to standard output, converting them to strings and using sep=' ' between arguments and end='\n' at the end by default. The input(prompt) function reads a line from standard input, strips the newline, and returns it as a string. To work with numeric input, you typically need to wrap input() with int() or float() to convert the result.

All chapters
  1. 1Introduction to Python
  2. 2Variables, Types, and Operators
  3. 3Control Flow
  4. 4Functions
  5. 5Data Structures
  6. 6Object-Oriented Programming
  7. 7Modules, Exceptions, and Advanced Features

Drill it

Reading is not remembering. These come from the Python Programming deck:

Q

What is Python?

Python is a high-level, interpreted programming language known for its readability and simplicity. It supports multiple paradigms including procedural, object-o...

Q

Who created Python and when?

Guido van Rossum created Python, with the first version released in 1991. It was named after the British comedy series Monty Python.

Q

What are the key features of Python?

Python features dynamic typing, automatic memory management, extensive standard library, and cross-platform compatibility. It emphasizes code readability with s...

Q

How do you run a Python script from the command line?

Save the code in a file with .py extension, then run python filename.py in the terminal. Use python3 if Python 2 is also installed.