Python Syntax Tutorial
Introduction to Python Syntax
Python is a powerful and versatile programming language known for its readability and simplicity. In this tutorial, we will explore the fundamental syntax elements of Python, including variables, data types, operators, control structures, functions, and more.
1. Hello, World!
Let's start with the traditional "Hello, World!" program to get familiar with Python syntax.
print("Hello, World!")
In Python, print()
is used to display output on the screen.
2. Variables and Data Types
In Python, you don't need to declare the data type of a variable explicitly. Python infers the data type dynamically.
age = 25
name = "Alice"
is_adult = True
3. Basic Operators
Python supports various operators for arithmetic, comparison, logical operations, etc.
# Arithmetic operators
result = 10 + 5 # Addition
result = 10 - 5 # Subtraction
result = 10 * 5 # Multiplication
result = 10 / 5 # Division
# Comparison operators
is_equal = (10 == 5) # Equal to
is_not_equal = (10 != 5) # Not equal to
is_greater = (10 > 5) # Greater than
is_less = (10 < 5) # Less than
# Logical operators
is_and = (True and False) # Logical AND
is_or = (True or False) # Logical OR
is_not = not True # Logical NOT
4. Control Structures
4.1 Conditional Statements
if condition:
# Code to be executed if the condition is true
elif another_condition:
# Code to be executed if another_condition is true
else:
# Code to be executed if none of the above conditions are true
4.2 Loops
# For loop
for i in range(5):
print(i)
# While loop
count = 0
while count < 5:
print(count)
count += 1
5. Functions
Functions in Python are defined using the def
keyword.
def greet(name):
print("Hello, " + name + "!")
greet("Alice")
6. Data Structures
6.1 Lists
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # Accessing elements
my_list.append(6) # Adding elements
6.2 Dictionaries
my_dict = {"name": "Alice", "age": 30}
print(my_dict["name"]) # Accessing values
my_dict["city"] = "New York" # Adding key-value pairs
6.3 Tuples
my_tuple = (1, 2, 3)
6.4 Sets
my_set = {1, 2, 3, 4}
my_set.add(5) # Adding elements to a set
7. Exception Handling
try:
# Code that might raise an exception
except SomeException as e:
# Handle the exception
else:
# Code to be executed if no exception occurred
finally:
# Code that will be executed regardless of an exception
8. Classes and Objects
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name + " and I am " + str(self.age) + " years old.")
person = Person("Alice", 25)
person.greet()
9. Modules and Packages
Python allows you to organize your code into modules and packages for better maintainability.
# Importing a module
import math
print(math.sqrt(16)) # Using functions from the math module
10. File Handling
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, World!")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
Conclusion
This tutorial provides a solid foundation in Python syntax. Practice is key to mastering these concepts, so don't hesitate to experiment and build your own Python programs. Happy coding!