=
. # Variable assignment
x = 10
name = "John"
is_student = True
# Data types
age = 25 # Integer
height = 5.9 # Float
message = "Hello" # String
#
, while multi-line comments can be enclosed within triple quotes '''
or """
. # This is a single-line comment
'''
This is a multi-line
comment
'''
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
input()
) and displaying output (print()
). # Input from user
name = input("Enter your name: ")
# Output
print("Hello,", name)
x = 10
y = 5
addition = x + y
subtraction = x - y
multiplication = x * y
division = x / y
True
or False
). x = 10
y = 5
greater_than = x > y
less_than_or_equal = x <= y
equal = x == y
not_equal = x != y
x = 10
y = 5
logical_and = (x > 5) and (y < 10)
logical_or = (x > 5) or (y > 10)
logical_not = not (x > 5)
age = 20
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child")
for
loop is used when you know the number of iterations in advance, while the while
loop is used when you want to repeat a block of code until a condition is met. # For loop
for i in range(5):
print(i)
# While loop
x = 0
while x < 5:
print(x)
x += 1
break
statement is used to exit a loop prematurely, while the continue
statement is used to skip the rest of the code inside the loop for the current iteration and move to the next iteration. # Break example
for i in range(10):
if i == 5:
break
print(i)
# Continue example
for i in range(5):
if i == 2:
continue
print(i)
# Creating a list
numbers = [1, 2, 3, 4, 5]
# Accessing elements
print(numbers[0]) # Output: 1
# Modifying elements
numbers[0] = 10
# Adding elements
numbers.append(6)
# Removing elements
numbers.remove(3)
# Creating a tuple
person = ("John", 25, "Male")
# Accessing elements
print(person[0]) # Output: John
# Tuples are immutable
# person[0] = "Jane" # This will raise an error
:
and different pairs are separated by commas ,
.Example: ```python # Creating a dictionary student = { “name”: “John”, “age”: 25, “gender”: “Male” }
# Accessing elements print(student[“name”]) # Output: John
# Modifying elements student[“age”] = 26
# Adding elements student[“grade”] = “A”
# Removing elements del student[“gender”]
# Creating a set
fruits = {"apple", "banana", "cherry"}
# Adding elements
fruits.add("orange")
# Removing elements
fruits.remove("banana")
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1.union(set2)
intersection = set1.intersection(set2)
difference = set1.difference(set2)
Functions:
def greet(name):
return f"Hello, {name}"
# Calling the function
print(greet("Alice")) # Output: Hello, Alice
def add(a, b):
return a + b
# Calling the function with arguments
print(add(3, 4)) # Output: 7
def greet(name="Guest"):
return f"Hello, {name}"
# Calling the function without an argument
print(greet()) # Output: Hello, Guest
# Calling the function with an argument
print(greet("Alice")) # Output: Hello, Alice
def my_function():
x = 10 # Local variable
print(x)
my_function() # Output: 10
# print(x) # This will raise an error because x is not defined outside the function
Modules:
# Importing the math module
import math
# Using a function from the math module
result = math.sqrt(16)
print(result) # Output: 4.0
.py
extension.# Create a file named mymodule.py with the following code:
def greet(name):
return f"Hello, {name}"
# Importing and using the custom module
import mymodule
print(mymodule.greet("Alice")) # Output: Hello, Alice
File Handling:
# Opening a file in read mode
file = open("example.txt", "r")
# Reading the content of the file
content = file.read()
print(content)
# Closing the file
file.close()
# Opening a file in write mode
file = open("example.txt", "w")
# Writing content to the file
file.write("Hello, World!")
# Closing the file
file.close()
# Opening a file in append mode
file = open("example.txt", "a")
# Appending content to the file
file.write("\nAppend this text.")
# Closing the file
file.close()
Exception Handling:
try
, except
, and finally
blocks to catch and handle errors.try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This will always execute")
Object-Oriented Programming (OOP):
# Defining a class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name}"
# Creating an object of the class
person1 = Person("John", 25)
# Accessing attributes and methods
print(person1.name) # Output: John
print(person1.greet()) # Output: Hello, my name is John
# Defining a base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some sound"
# Defining a derived class
class Dog(Animal):
def speak(self):
return "Bark"
# Creating an object of the derived class
dog = Dog("Buddy")
# Accessing attributes and methods
print(dog.name) # Output: Buddy
print(dog.speak()) # Output: Bark
Conclusion:
This tutorial covered the basics of Python, including its syntax, control flow, data structures, functions, modules, file handling, exception handling, and object-oriented programming. Python is a versatile language with a wide range of applications. Keep practicing and exploring more advanced topics to enhance your Python skills. Happy coding!