Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Syntax

The document outlines the essential rules and structures of Python syntax, including indentation, comments, variable naming, data types, operators, conditional statements, loops, functions, exception handling, and importing modules. Key takeaways emphasize Python's indentation sensitivity, dynamic typing, and case sensitivity. Examples are provided for each aspect to illustrate proper usage.

Uploaded by

Amadi Samuel
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Syntax

The document outlines the essential rules and structures of Python syntax, including indentation, comments, variable naming, data types, operators, conditional statements, loops, functions, exception handling, and importing modules. Key takeaways emphasize Python's indentation sensitivity, dynamic typing, and case sensitivity. Examples are provided for each aspect to illustrate proper usage.

Uploaded by

Amadi Samuel
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

Python syntax refers to the set of rules that define how Python code is written and

structured. It includes rules for indentation, keywords, operators, identifiers,


and statements. Here are some key aspects of Python syntax:

### 1. **Indentation**
Python uses indentation (whitespace) to define blocks of code instead of braces
`{}` (like in C or Java).

**Example:**
```python
if 5 > 2:
print("Five is greater than two!") # Indented block
```

❌ **Wrong Indentation:**
```python
if 5 > 2:
print("Five is greater than two!") # Error: expected an indented block
```

---

### 2. **Comments**
- Single-line comments start with `#`.
- Multi-line comments can be written using triple quotes (`'''` or `"""`), but
these are actually string literals (not true comments).

**Example:**
```python
# This is a single-line comment

"""
This is a multi-line
comment (technically a string).
"""
```

---

### 3. **Variables & Naming Rules**


- Variables are created when assigned (no explicit declaration).
- Names can contain letters, digits, and underscores (`_`), but cannot start with a
number.
- Case-sensitive (`myVar` ≠ `myvar`).

**Example:**
```python
x = 5 # Integer
name = "Alice" # String
is_valid = True # Boolean
```

---

### 4. **Data Types**


Python has built-in data types like:
- `int` (integer), `float` (decimal), `str` (string)
- `list`, `tuple`, `dict`, `set`
- `bool` (`True` or `False`)
**Example:**
```python
num = 10 # int
pi = 3.14 # float
text = "Hello" # str
my_list = [1, 2, 3] # list
```

---

### 5. **Operators**
- Arithmetic: `+`, `-`, `*`, `/`, `//` (floor division), `%` (modulus), `**`
(exponent)
- Comparison: `==`, `!=`, `>`, `<`, `>=`, `<=`
- Logical: `and`, `or`, `not`

**Example:**
```python
sum = 5 + 3 # 8
is_true = (5 > 3) # True
```

---

### 6. **Conditional Statements (`if-elif-else`)**


```python
age = 18
if age < 13:
print("Child")
elif age < 20:
print("Teenager") # This will execute
else:
print("Adult")
```

---

### 7. **Loops**
- `for` loop (iterates over sequences)
- `while` loop (executes while condition is `True`)

**Example:**
```python
# For loop
for i in range(3): # 0, 1, 2
print(i)

# While loop
count = 0
while count < 3:
print(count)
count += 1
```

---

### 8. **Functions**
Defined using `def` keyword.
**Example:**
```python
def greet(name):
return f"Hello, {name}!"

print(greet("Alice")) # Output: Hello, Alice!


```

---

### 9. **Exceptions (Error Handling)**


Use `try-except` blocks.

**Example:**
```python
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
```

---

### 10. **Importing Modules**


Use `import` to include external modules.

**Example:**
```python
import math
print(math.sqrt(16)) # 4.0
```

---

### Key Takeaways:


- Python is **indentation-sensitive** (unlike C/Java).
- No semicolons (`;`) needed (unlike JavaScript/C++).
- Dynamic typing (no need to declare variable types).
- Case-sensitive (`Print` ≠ `print`).

Would you like a deeper explanation of any specific part? 😊

You might also like