🐍 Python Syntax Basics
Introduction
This tutorial covers the essential Python syntax and programming concepts you need to get started. We'll explore variables, data types, control structures, functions, and more. By the end, you'll have a solid foundation to write your first Python programs.
1. Your First Python Program
Hello World
# This is a comment
print("Hello, World!")
Running Python Code
# Save as hello.py and run
python3 hello.py
# Or run interactively
python3
>>> print("Hello, World!")
>>> exit()
2. Variables and Data Types
Variables
# Variables don't need type declarations
name = "Alice"
age = 25
height = 5.6
is_student = True
# Print variables
print(name)
print(f"My name is {name} and I'm {age} years old")
Basic Data Types
# Numbers
integer_number = 42
float_number = 3.14
complex_number = 3 + 4j
# Strings
single_quote = 'Hello'
double_quote = "World"
triple_quote = """This is a
multi-line string"""
# Boolean
is_true = True
is_false = False
# None (represents absence of value)
empty_value = None
# Check data types
print(type(integer_number)) # <class 'int'>
print(type(float_number)) # <class 'float'>
print(type(single_quote)) # <class 'str'>
print(type(is_true)) # <class 'bool'>
3. Numbers and Math Operations
Arithmetic Operations
# Basic arithmetic
a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.333...
print(a // b) # Floor division: 3
print(a % b) # Modulo (remainder): 1
print(a ** b) # Exponentiation: 1000
# Order of operations (PEMDAS)
result = 2 + 3 * 4 # 14, not 20
print(result)
# Parentheses for grouping
result = (2 + 3) * 4 # 20
print(result)
Math Functions
import math
# Built-in functions
print(abs(-5)) # Absolute value: 5
print(round(3.7)) # Round: 4
print(max(1, 5, 3)) # Maximum: 5
print(min(1, 5, 3)) # Minimum: 1
print(sum([1, 2, 3, 4])) # Sum: 10
# Math module functions
print(math.sqrt(16)) # Square root: 4.0
print(math.pi) # Pi: 3.14159...
print(math.ceil(4.2)) # Ceiling: 5
print(math.floor(4.8)) # Floor: 4
4. Strings
String Operations
# String concatenation
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # John Doe
# String repetition
stars = "*" * 10
print(stars) # **********
# String length
message = "Hello, Python!"
print(len(message)) # 14
# String indexing
text = "Python"
print(text[0]) # P (first character)
print(text[-1]) # n (last character)
print(text[2:5]) # tho (slice from index 2 to 4)
String Methods
text = " Hello, World! "
# Case methods
print(text.upper()) # " HELLO, WORLD! "
print(text.lower()) # " hello, world! "
print(text.title()) # " Hello, World! "
print(text.capitalize()) # " hello, world! "
# Whitespace methods
print(text.strip()) # "Hello, World!"
print(text.lstrip()) # "Hello, World! "
print(text.rstrip()) # " Hello, World!"
# Search methods
print(text.find("World")) # 9
print(text.count("l")) # 3
print("Hello" in text) # True
# Replace
print(text.replace("World", "Python")) # " Hello, Python! "
# Split and join
words = "apple,banana,cherry".split(",")
print(words) # ['apple', 'banana', 'cherry']
joined = "-".join(words)
print(joined) # apple-banana-cherry
String Formatting
name = "Alice"
age = 30
score = 95.5
# Old style (%)
print("Name: %s, Age: %d, Score: %.1f" % (name, age, score))
# .format() method
print("Name: {}, Age: {}, Score: {:.1f}".format(name, age, score))
print("Name: {0}, Age: {1}, Score: {2:.1f}".format(name, age, score))
print("Name: {n}, Age: {a}, Score: {s:.1f}".format(n=name, a=age, s=score))
# f-strings (Python 3.6+, recommended)
print(f"Name: {name}, Age: {age}, Score: {score:.1f}")
print(f"Next year I'll be {age + 1} years old")
5. Lists
Creating and Accessing Lists
# Create lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# Access elements
print(fruits[0]) # apple
print(fruits[-1]) # cherry
print(fruits[1:3]) # ['banana', 'cherry']
# List length
print(len(fruits)) # 3
List Operations
fruits = ["apple", "banana"]
# Add elements
fruits.append("cherry") # Add to end
fruits.insert(1, "orange") # Insert at index 1
fruits.extend(["grape", "kiwi"]) # Add multiple elements
print(fruits) # ['apple', 'orange', 'banana', 'cherry', 'grape', 'kiwi']
# Remove elements
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove and return last element
del fruits[0] # Remove by index
# Other operations
print(fruits.count("apple")) # Count occurrences
print(fruits.index("cherry")) # Find index
fruits.sort() # Sort in place
fruits.reverse() # Reverse in place
List Comprehensions
# Traditional way
squares = []
for i in range(5):
squares.append(i ** 2)
print(squares) # [0, 1, 4, 9, 16]
# List comprehension (more Pythonic)
squares = [i ** 2 for i in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# With conditions
even_squares = [i ** 2 for i in range(10) if i % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
6. Dictionaries
Creating and Accessing Dictionaries
# Create dictionary
person = {
"name": "Alice",
"age": 30,
"city": "New York",
"is_student": False
}
# Access values
print(person["name"]) # Alice
print(person.get("age")) # 30
print(person.get("salary", "Not specified")) # Not specified
# Check if key exists
print("name" in person) # True
print("salary" in person) # False
Dictionary Operations
person = {"name": "Alice", "age": 30}
# Add/update values
person["city"] = "New York"
person["age"] = 31
# Remove items
del person["city"]
age = person.pop("age", 0) # Remove and return value
# Dictionary methods
print(person.keys()) # dict_keys(['name'])
print(person.values()) # dict_values(['Alice'])
print(person.items()) # dict_items([('name', 'Alice')])
# Loop through dictionary
for key, value in person.items():
print(f"{key}: {value}")
7. Control Structures
Conditional Statements (if/elif/else)
age = 18
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
elif age < 65:
print("Adult")
else:
print("Senior")
# Multiple conditions
score = 85
if score >= 90 and score <= 100:
grade = "A"
elif score >= 80 and score < 90:
grade = "B"
else:
grade = "C"
print(f"Grade: {grade}")
# Ternary operator
status = "adult" if age >= 18 else "minor"
print(status)
Loops
For Loops
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Loop with index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# Loop through a range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(2, 8, 2):
print(i) # 2, 4, 6
# Loop through dictionary
person = {"name": "Alice", "age": 30, "city": "NYC"}
for key, value in person.items():
print(f"{key}: {value}")
While Loops
# Basic while loop
count = 0
while count < 5:
print(f"Count: {count}")
count += 1
# Break and continue
count = 0
while count < 10:
count += 1
if count == 3:
continue # Skip the rest of this iteration
if count == 7:
break # Exit the loop
print(count) # 1, 2, 4, 5, 6
8. Functions
Defining and Calling Functions
# Simple function
def greet():
print("Hello, World!")
greet() # Call the function
# Function with parameters
def greet_person(name, age=25):
print(f"Hello, {name}! You are {age} years old.")
greet_person("Alice") # Hello, Alice! You are 25 years old.
greet_person("Bob", 30) # Hello, Bob! You are 30 years old.
# Function with return value
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result) # 8
# Multiple return values
def get_name_parts(full_name):
parts = full_name.split()
return parts[0], parts[-1] # Returns tuple
first, last = get_name_parts("John Doe")
print(f"First: {first}, Last: {last}")
Function Examples
# Calculate area of rectangle
def rectangle_area(length, width):
"""Calculate the area of a rectangle."""
return length * width
area = rectangle_area(5, 3)
print(f"Area: {area}")
# Check if number is even
def is_even(number):
return number % 2 == 0
print(is_even(4)) # True
print(is_even(7)) # False
# Find maximum in a list
def find_max(numbers):
if not numbers:
return None
max_num = numbers[0]
for num in numbers[1:]:
if num > max_num:
max_num = num
return max_num
numbers = [3, 7, 2, 9, 1]
print(f"Maximum: {find_max(numbers)}")
9. Error Handling
Try/Except Blocks
# Basic error handling
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("Please enter a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
else:
print("No errors occurred!")
finally:
print("This always runs!")
# Multiple exceptions
try:
# Some code that might fail
pass
except (ValueError, TypeError) as e:
print(f"Input error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
10. File Operations
Reading and Writing Files
# Write to file
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a test file.\n")
# Read from file
with open("example.txt", "r") as file:
content = file.read()
print(content)
# Read line by line
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes newline characters
# Append to file
with open("example.txt", "a") as file:
file.write("This line was appended.\n")
11. Modules and Imports
Using Built-in Modules
# Import entire module
import math
print(math.pi)
print(math.sqrt(16))
# Import specific functions
from math import pi, sqrt
print(pi)
print(sqrt(16))
# Import with alias
import datetime as dt
now = dt.datetime.now()
print(now)
# Import all (not recommended)
from math import *
print(sin(pi/2)) # 1.0
Creating Your Own Module
# Save as calculator.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
# Use in another file
from calculator import add, multiply
print(add(5, 3)) # 8
print(multiply(4, 6)) # 24
12. Practice Exercises
Exercise 1: Temperature Converter
def celsius_to_fahrenheit(celsius):
"""Convert Celsius to Fahrenheit."""
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
"""Convert Fahrenheit to Celsius."""
return (fahrenheit - 32) * 5/9
# Test the functions
c = 25
f = celsius_to_fahrenheit(c)
print(f"{c}°C = {f}°F")
f = 77
c = fahrenheit_to_celsius(f)
print(f"{f}°F = {c}°C")
Exercise 2: Word Counter
def count_words(text):
"""Count words in a text."""
words = text.split()
return len(words)
def count_characters(text):
"""Count characters (excluding spaces)."""
return len(text.replace(" ", ""))
# Test
text = "Hello world! This is a test."
print(f"Words: {count_words(text)}")
print(f"Characters: {count_characters(text)}")
Exercise 3: Number Guessing Game
import random
def guessing_game():
"""Simple number guessing game."""
secret_number = random.randint(1, 100)
attempts = 0
print("I'm thinking of a number between 1 and 100.")
while True:
try:
guess = int(input("Enter your guess: "))
attempts += 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print(f"Congratulations! You guessed it in {attempts} attempts!")
break
except ValueError:
print("Please enter a valid number!")
# Uncomment to play
# guessing_game()
Conclusion
You've learned the fundamental Python syntax including:
- Variables and data types (int, float, str, bool, list, dict)
- Control structures (if/elif/else, for/while loops)
- Functions (defining, calling, parameters, return values)
- Error handling (try/except blocks)
- File operations (reading and writing files)
- Modules (importing and using)
Next Steps
- Setting Up Python Workspace with Package Management
- Getting Started with Jupyter Notebooks
- Practice with more complex projects
- Explore Python libraries and frameworks
- Learn about object-oriented programming