Python Basics Simplified (1)
Python Basics Simplified (1)
Explanation
Syntax
print("Hello, World!")
Example
print("Welcome to Python Basics!")
5 Easy Exercises
Comments are lines in the code that are ignored by Python. They help explain the code.
Explanation
Syntax
# This is a single-line comment
''' This is a
multi-line comment '''
Example
# Printing a message
print("Hello, World!") # This prints Hello, World!
5 Easy Exercises
3. Literals in Python
Definition
Explanation
Example
name = "Alice" # String literal
age = 25 # Integer literal
pi = 3.14 # Float literal
complex_num = 2 + 3j # Complex number literal
is_student = True # Boolean literal
empty_value = None # Special literal
5 Easy Exercises
Operators in Python are special symbols that perform operations on variables and values. They
are used for arithmetic calculations, comparisons, logical operations, and more.
1. Arithmetic Operators
Example
x = 10
y=5
print(x + y) # Addition: 15
print(x - y) # Subtraction: 5
print(x * y) # Multiplication: 50
print(x % y) # Modulus: 0
Example:
a = 10
b = 20
print(a == b) # False
print(a != b) # True
3. Logical Operators
x = True
y = False
4. Bitwise Operators
Example:
x = 5 # 0101 in binary
y = 3 # 0011 in binary
Example:
x = 10
x += 5 # x = x + 5 -> 15
x -= 3 # x = x - 3 -> 12
x *= 2 # x = x * 2 -> 24
x /= 4 # x = x / 4 -> 6.0
x %= 2 # x = x % 2 -> 0.0
6. Identity Operators
Identity operators check whether two variables refer to the same object in memory.
Example:
x = [1, 2, 3]
y=x
z = [1, 2, 3]
Example
word = "Python"
5 Exercises
If-Else statements are used to execute different blocks of code based on conditions.
Explanation
Syntax
if condition:
statement
else:
statement
Example
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
5 Easy Exercises
Explanation
Syntax
if condition1:
statement1
elif condition2:
statement2
else:
statement3
Example
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F")
5 Easy Exercises
Types of Loops
Syntax
For loop:
for variable in sequence:
statement
While loop:
while condition:
statement
Examples
# For loop example
for i in range(5):
print(i)
5 Easy Exercises
Types
Syntax
for i in range(5):
if i == 3:
break # Exits the loop at i = 3
print(i)
Examples
# Break Example
for i in range(5):
if i == 3:
break
print(i)
# Continue Example
for i in range(5):
if i == 2:
continue
print(i)
# Pass Example
for i in range(5):
if i == 2:
pass # Placeholder
print(i)
5 Easy Exercises
1. Use a break statement to exit a loop at a specific value.
2. Use continue to skip printing a specific number.
3. Implement a pass statement in a loop.
4. Create a loop with break and continue conditions.
5. Build a loop with a condition that stops at user input.