DEV Community

Hamidul Islam
Hamidul Islam

Posted on

Mastering Python : Essential Syntax You Need to Know

1. Variables and Data Types:

# Variable assignment
x = 10
name = "John"
is_active = True

# Basic data types
integer_variable = 10
float_variable = 3.14
string_variable = "Hello, world!"
list_variable = [1, 2, 3]
tuple_variable = (1, 2, 3)
dictionary_variable = {"name": "John", "age": 30}
set_variable = {1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

2. Control Structures:

# If-elif-else statement
x = 10
if x > 0:
    print("Positive")
elif x < 0:
    print("Negative")
else:
    print("Zero")

# For loop
for i in range(5):
    print(i)

# While loop
i = 0
while i < 5:
    print(i)
    i += 1
Enter fullscreen mode Exit fullscreen mode

3. Functions and Modules:

# Function definition and call
def greet(name):
    return "Hello, " + name

print(greet("John"))

# Module creation
# module.py
# def greet(name):
#     return "Hello, " + name
# import module
# print(module.greet("John"))
Enter fullscreen mode Exit fullscreen mode

4. Object-Oriented Programming (OOP):

# Class definition and object creation
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return "Hello, my name is " + self.name

person = Person("John", 30)
print(person.greet())
Enter fullscreen mode Exit fullscreen mode

5. Exception Handling:

# Try-except block
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Division by zero")
Enter fullscreen mode Exit fullscreen mode

6. File Handling:

# File input/output
# 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)
Enter fullscreen mode Exit fullscreen mode

7. List Comprehensions:

# List comprehension
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x**2 for x in numbers]
print(squared_numbers)
Enter fullscreen mode Exit fullscreen mode

8. Dictionaries and Sets:

# Dictionary and set creation
person = {"name": "John", "age": 30}
print(person["name"])

unique_numbers = {1, 2, 3, 4, 5, 5}
print(unique_numbers)
Enter fullscreen mode Exit fullscreen mode

9. Lambda Functions and Functional Programming:

# Lambda function
add = lambda x, y: x + y
print(add(2, 3))

# Functional programming
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)
Enter fullscreen mode Exit fullscreen mode

10. Comprehensive Documentation:

No code example needed, but remember to refer to the official Python documentation at docs.python.org for detailed explanations and examples of all Python syntax and built-in functions.

Top comments (0)