0% found this document useful (0 votes)
4 views2 pages

Python Syntax Summary

This document provides a summary of Python syntax covering variables and data types, control flow, functions, classes, built-in functions, list comprehension, exception handling, file I/O, importing modules, and lambda functions. It includes examples for each topic to illustrate their usage. Overall, it serves as a quick reference guide for Python programming concepts.

Uploaded by

Khyati Karia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Python Syntax Summary

This document provides a summary of Python syntax covering variables and data types, control flow, functions, classes, built-in functions, list comprehension, exception handling, file I/O, importing modules, and lambda functions. It includes examples for each topic to illustrate their usage. Overall, it serves as a quick reference guide for Python programming concepts.

Uploaded by

Khyati Karia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python Syntax Summary

1. Variables & Data Types


x = 5 # int
y = 3.14 # float
name = "Alice" # str
is_happy = True # bool
fruits = ["apple", "banana"] # list
point = (4, 5) # tuple
person = {"name": "Bob", "age": 25} # dict

2. Control Flow
# if-elif-else
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")

# for loop
for fruit in fruits:
print(fruit)

# while loop
i = 0
while i < 5:
print(i)
i += 1

3. Functions
def greet(name):
return "Hello, " + name

print(greet("Alice"))

4. Classes & Objects


class Dog:
def __init__(self, name):
self.name = name

def bark(self):
print(self.name + " says woof!")

my_dog = Dog("Rex")
my_dog.bark()

5. Built-in Functions
Python Syntax Summary
len(), type(), int(), str(), float(), range(), sum(), max(), min()

6. List Comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]

7. Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This runs no matter what")

8. File I/O
# Write to a file
with open("file.txt", "w") as f:
f.write("Hello world")

# Read from a file


with open("file.txt", "r") as f:
content = f.read()

9. Importing Modules
import math
print(math.sqrt(16))

from random import randint


print(randint(1, 10))

10. Lambda & Map


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

nums = [1, 2, 3]
squares = list(map(lambda x: x**2, nums)) # [1, 4, 9]

You might also like