Complete Python Basic Syntax Guide
1. Print Statement
print("Hello, World!")
2. Comments
# This is a comment
3. Variables
x = 10
name = "Rahul"
4. Data Types
int, float, str, bool, list, tuple, dict, set
5. Type Casting
x = int("5")
y = float("3.14")
z = str(100)
6. String Methods
name = "Rahul"
print(name.upper())
print(name.lower())
print(name[0:2])
7. If Statement
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is 5")
else:
print("x is less than 5")
8. Loops - for
for i in range(5):
print(i)
9. Loops - while
x=0
while x < 5:
print(x)
x += 1
10. Loops with else
for i in range(3):
print(i)
else:
print("Done!")
11. Break & Continue
for i in range(5):
if i == 3:
break
print(i)
12. Functions
def greet(name):
print("Hello", name)
greet("Rahul")
13. Lists
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
14. List Methods
fruits.append("mango")
fruits.remove("banana")
print(fruits)
15. Tuples
colors = ("red", "green", "blue")
print(colors[1])
16. Sets
nums = {1, 2, 3}
nums.add(4)
print(nums)
17. Dictionaries
person = {"name": "Rahul", "age": 17}
print(person["name"])
18. Input
name = input("Enter your name: ")
print("Hi", name)
19. Try-Except
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
20. Class & Object
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello", self.name)
p = Person("Rahul")
p.greet()