1. Comments:
In Python, comments are used to annotate code and are preceded by the #
symbol. Comments are ignored by the Python interpreter and are useful for providing explanations or context within your code.
# This is a single-line comment
"""
This is a
multi-line
comment
"""
2. Variables and Data Types:
Python is dynamically typed, meaning you don’t need to declare the data type of a variable explicitly.
# Variable assignment
name = "John"
age = 25
height = 5.9
is_student = True
Common data types in Python include:
int
for integersfloat
for floating-point numbersstr
for stringsbool
for boolean values
3. Print Statement:
The print()
function is used to display output. You can print variables, strings, or a combination of both.
print("Hello, Python!")
print("My name is", name)
print("I am", age, "years old.")
4. Indentation:
Indentation is crucial in Python for indicating blocks of code. Use consistent indentation (usually four spaces) to define the scope of loops, conditionals, and functions.
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
5. Conditionals:
Python uses if
, elif
, and else
for conditional statements.
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
else:
grade = 'C'
6. Loops:
Python supports for
and while
loops.
# For loop
for i in range(5):
print(i)
# While loop
counter = 0
while counter < 5:
print(counter)
counter += 1
7. Lists:
Lists are ordered, mutable collections in Python.
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
8. Tuples:
Tuples are ordered, immutable collections.
coordinates = (3, 4)
colors = ("red", "green", "blue")
9. Dictionaries:
Dictionaries are key-value pairs.
person = {
"name": "Alice",
"age": 30,
"is_student": False
}
10. Functions:
Functions are defined using the def
keyword.
def greet(name):
print("Hello, " + name + "!")
# Function call
greet("Alice")
11. Input from Users:
Use the input()
function to get user input.
user_name = input("Enter your name: ")
print("Hello, " + user_name + "!")
12. String Manipulation:
Python provides powerful string manipulation methods.
message = "Python is fun!"
length = len(message)
uppercase_message = message.upper()
13. Math Operations:
Perform basic math operations using +
, -
, *
, /
, and %
.
result = 5 + 3
remainder = 10 % 3
14. Importing Modules:
Python’s functionality can be extended by importing modules.
import math
square_root = math.sqrt(25)
15. Whitespace Sensitivity:
Be mindful of whitespace as it is part of Python syntax.
# Good
if x > 0:
print("Positive")
# Bad
if x > 0:
print("Positive")
Mastering these basic Python syntax elements will lay a strong foundation for your programming journey. In the upcoming sections, we’ll explore more advanced concepts and practical applications.