Let’s start with the basics of Python syntax.
Python uses indentation to define blocks of code. Instead of using braces like `{}` in other languages, Python relies on spaces or tabs. For example, if you have an `if` statement, the code that should run if the condition is true is indented:
if True:
print("This is inside the if block")
print("This is outside the if block")Here, the second `print` statement is not indented, so it runs regardless of the `if` condition.
To add comments in your code, you use the `#` symbol. Anything after `#` on that line is a comment and is ignored by Python:
# This is a comment
print("Hello, World!") # This prints text to the screenFor multi-line comments, Python does not have a special syntax. Instead, you use triple quotes:
"""
This is a multi-line comment.
It spans multiple lines.
"""
print("Hello again!")
Variables in Python are used to store data. You assign a value to a variable using `=`:
name = "Alice" # This is a string variable age = 30 # This is an integer variable
Python handles different types of data, like strings, integers, and floats. Strings are text, integers are whole numbers, and floats are numbers with decimal points:
name = "Alice" # String age = 30 # Integer height = 5.6 # Float
You can perform operations with these data types. For example, you can add numbers:
x = 10 y = 5 sum = x + y print(sum) # This will print 15
You can also combine strings:
greeting = "Hello" name = "Alice" message = greeting + " " + name print(message) # This will print "Hello Alice"
Python also has functions, which are blocks of code designed to do something specific. You define a function using the `def` keyword:
def say_hello():
print("Hello!")
To use the function, you simply call it by its name followed by parentheses:
say_hello() # This will print "Hello!"
That’s a quick overview of basic Python syntax. As you practice and write more code, these concepts will become more familiar.
Comments
- Single-line comment:
# This is a comment - Multi-line comment:
""" This is a multi-line comment """
Variables
- Define a variable:
x = 5 - Variable names can include letters, numbers, and underscores. They must start with a letter or underscore.
Data Types
- Integer:
x = 10 - Float:
y = 3.14 - String:
name = "Alice" - Boolean:
flag = True
Basic Operations
- Addition:
a + b - Subtraction:
a - b - Multiplication:
a * b - Division:
a / b - Integer Division:
a // b - Modulus:
a % b - Exponentiation:
a ** b
Strings
- Concatenation:
"Hello" + " World" - Repetition:
"Hello" * 3 - Accessing characters:
name[0](first character) - Slicing:
name[1:4](substring)
Lists
- Create a list:
my_list = [1, 2, 3] - Access elements:
my_list[0] - Slice list:
my_list[1:3] - Append item:
my_list.append(4)
Tuples
- Create a tuple:
my_tuple = (1, 2, 3) - Access elements:
my_tuple[0]
Dictionaries
- Create a dictionary:
my_dict = {'key1': 'value1', 'key2': 'value2'} - Access value:
my_dict['key1'] - Add item:
my_dict['key3'] = 'value3'
Control Flow
- If statement:
if condition: # code elif another_condition: # code else: # code - For loop:
for item in iterable: # code - While loop:
while condition: # code
Functions
- Define a function:
def function_name(parameters): # code return value - Call a function:
function_name(arguments)
Indentation
- Python uses indentation to define code blocks. Consistent spacing is crucial.
Exception Handling
- Try/Except:
try: # code except ExceptionType as e: # code
Imports
- Import a module:
import module_name - Import specific items:
from module_name import item_name
Classes and Objects
- Define a class:
class MyClass: def __init__(self, value): self.value = value def method(self): # code - Create an object:
obj = MyClass(value)
Lambda Functions
- Create a lambda function:
lambda x: x * 2
List Comprehensions
- Syntax:
[expression for item in iterable if condition] - Example:
squares = [x**2 for x in range(10)]