Python is a powerful programming language with a simple and readable syntax. Ideal for beginners, Python is also frequently preferred by professional developers. In this article, we will explore Python’s basic syntax with example code blocks.
1. Comments
In Python, comments are used to explain the code and make it more understandable. Comments begin with the #
character.
# This is a comment
print("Hello, World!") # This is also a comment
2. Variables and Data Types
In Python, variables are defined by directly assigning them a name. You don’t need to specify data types because Python has dynamic typing.
number = 10 # Integer
name = "Ali" # String
pi = 3.14 # Float
is_true = True # Boolean
print(number)
print(name)
print(pi)
print(is_true)
3. Operators
Python uses operators for mathematical and logical operations.
Mathematical Operators
a = 10
b = 5
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
Logical Operators
x = True
y = False
print(x and y) # Logical AND
print(x or y) # Logical OR
print(not x) # Logical NOT
4. Control Structures
In Python, conditional statements and loops are used to control the flow of the program.
Conditional Statements (if-elif-else)
number = 20
if number > 10:
print("The number is greater than 10")
elif number < 10:
print("The number is less than 10")
else:
print("The number is equal to 10")
Loops (for and while)
For Loop
for i in range(5): # From 0 to 4
print(i)
While Loop
j = 0
while j < 5:
print(j)
j += 1
5. Functions
In Python, functions are defined using the def
keyword.
def greet(name):
print("Hello, " + name)
greet("Ahmet")
greet("Ayşe")
6. Lists
Lists are used to store multiple values in a single variable.
fruits = ["Apple", "Pear", "Strawberry"]
print(fruits)
print(fruits[0]) # First element
print(fruits[1]) # Second element
fruits.append("Banana") # Adding a new element
print(fruits)
7. Dictionaries
Dictionaries are used to store key-value pairs.
people = {
"Ahmet": 25,
"Ayşe": 30,
"Mehmet": 35
}
print(people)
print(people["Ayşe"]) # Prints Ayşe's age
people["Ali"] = 40 # Adding a new key-value pair
print(people)
8. File Operations
Reading and writing files in Python is quite simple.
Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, File!")
Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
Conclusion
Python, with its simple and understandable syntax, is a powerful tool for both beginners and experienced programmers. In this article, we have explored Python’s basic syntax and some fundamental features. Starting to program with Python begins with learning these basic concepts. For more in-depth information and advanced topics, you can continue exploring Python documentation and various resources.