| id | python-syntax | |||
|---|---|---|---|---|
| title | Python Syntax | |||
| sidebar_label | Python Syntax | |||
| sidebar_position | 2 | |||
| tags |
|
Python is known for its clean and readable syntax. It emphasizes code readability and allows developers to write fewer lines of code compared to other programming languages.
Python uses indentation instead of curly braces {} to define blocks of code.
if 5 > 2:
print("Five is greater than two!")- Indentation is crucial in Python. Missing or incorrect indentation will raise an error.
# This is a comment
print("Hello, World!")"""
This is a
multi-line comment
"""
print("Hello again!")Python does not require you to declare the type of a variable.
x = 10 # integer
y = "Hello" # string
z = 3.14 # floata, b, c = 1, 2, 3Some common data types in Python:
int: Integerfloat: Floating pointstr: Stringbool: Booleanlist: List of itemstuple: Immutable listdict: Key-value pairset: Unique unordered collection
num = 10 # int
name = "Alice" # str
items = [1, 2, 3] # list
person = {"name": "Bob", "age": 25} # dictage = 18
if age >= 18:
print("Adult")
elif age > 12:
print("Teenager")
else:
print("Child")for i in range(5):
print(i)count = 0
while count < 5:
print(count)
count += 1Functions are defined using the def keyword.
def greet(name):
print("Hello, " + name)
greet("Alice")def add(a, b):
return a + b
result = add(2, 3)
print(result) # Output: 5You can import built-in or custom modules.
import math
print(math.sqrt(16)) # Output: 4.0+ - * / // % **== != > < >= <=and or notPython uses 4 spaces (by convention) for indentation. Do not mix tabs and spaces.
Incorrect:
if True:
print("Hello") # IndentationErrorCorrect:
if True:
print("Hello") Python syntax is simple, readable, and beginner-friendly. With its use of indentation and minimalistic style, it allows you to focus on solving problems rather than worrying about complex syntax rules.
📌 Note: Make sure your Python files have the
.pyextension and you're using Python 3.x version for compatibility with modern features.