Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability. It is widely used in Web Development, Data Science, Automation, & Artificial Intelligence.
1. Python Basics
Hello, World!
pythonCopyEditprint("Hello, World!")
Variables & Data Types
pythonCopyEditname = "Alice" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
User Input
pythonCopyEditname = input("Enter your name: ")
print("Hello, " + name)
Type Casting
pythonCopyEditage = int(input("Enter your age: "))
print("Next year, you will be", age + 1)
Operators
pythonCopyEdita = 10
b = 3
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a // b) # Floor Division
print(a % b) # Modulus
print(a ** b) # Exponentiation
2. Conditional Statements
pythonCopyEditage = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
3. Loops
For Loop
pythonCopyEditfor i in range(1, 6):
print(i)
While Loop
pythonCopyEditcount = 1
while count <= 5:
print(count)
count += 1
Loop Control
pythonCopyEditfor i in range(1, 10):
if i == 5:
break # Stops loop
print(i)
for i in range(1, 10):
if i == 5:
continue # Skips iteration
print(i)
4. Functions
pythonCopyEditdef greet(name):
return "Hello, " + name
print(greet("Alice"))
Default and Keyword Arguments
pythonCopyEditdef power(base, exponent=2):
return base ** exponent
print(power(3)) # Default exponent is 2
print(power(3, 3)) # Exponent is 3
5. Data Structures
Lists
pythonCopyEditfruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits[0]) # Access first element
print(fruits[-1]) # Access last element
Tuples (Immutable Lists)
pythonCopyEditcoordinates = (4, 5)
print(coordinates[0])
Sets (Unique Items)
pythonCopyEditunique_numbers = {1, 2, 3, 4, 4}
print(unique_numbers) # Output: {1, 2, 3, 4}
Dictionaries (Key-Value Pairs)
pythonCopyEditperson = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person["name"])