Python Basics: Syntax and Basic Data Types
Python Syntax
Python syntax is designed to be easy to read and understand, with a focus on simplicity and minimalism.
- Indentation: Unlike other programming languages that use curly braces to define blocks of code, Python relies on indentation. A consistent number of spaces or tabs (usually 4 spaces) are used to indicate the beginning and end of code blocks.
- Comments: In Python, comments start with a hash symbol (#) and can be used to provide explanations or notes within your code. Comments are not executed by the Python interpreter.
- Line continuation: To split a long line of code into multiple lines for readability, use a backslash (\) at the end of a line or enclose the expression in parentheses.
- Importing modules: To use external libraries or modules in your Python code, you can use the
import
statement followed by the module name.
Basic Data Types
Python has several built-in data types that can be used to represent different kinds of information. The most basic ones include strings, numbers (integers and floats), and booleans.
Strings
Strings are sequences of characters, such as words or sentences. In Python, strings can be enclosed in single quotes (' ') or double quotes (" "):
name = 'John Doe'
message = "Welcome to Python!"
The type of the name
and message
variables is str
.
We can also use string interpolation (f-strings):
name = "Python"
message = f"Welcome to {name}!"
Numbers
Python has two primary numeric data types:
Integers: Represent whole numbers, both positive and negative.
age = 25
temperature = -10
Floats: Represent real numbers, including decimals and fractions.
pi = 3.14159
weight = 75.5
Booleans
Booleans represent the logical values of True or False and are commonly used in conditional expressions and control structures:
is_adult = True
is_raining = False