Python Basics
Hello World
print("Hello, World!")
Output:
Hello, World!
Variables and Data Types
num = 42
pi = 3.14
name = "Alice"
is_student = True
Playing with Strings
# Define a sample string
sample_string = "Hello, World!"
# Indexing: Accessing characters by index
print("Indexing:")
print("Character at index 0:", sample_string[0]) # Output: H
print("Character at index 7:", sample_string[7]) # Output: W
# Slicing: Extracting substrings
print("\nSlicing:")
print("Substring [0:5]:", sample_string[0:5]) # Output: Hello
print("Substring [7:]:", sample_string[7:]) # Output: World!
print("Substring [:5]:", sample_string[:5]) # Output: Hello
# Reverse the string
print("\nReversed:")
reversed_string = sample_string[::-1]
print("Reversed string:", reversed_string) # Output: !dlroW ,olleH
# Length of the string
print("\nLength:")
print("Length of the string:", len(sample_string)) # Output: 13
# Uppercase and lowercase letters
print("\nUppercase and Lowercase:")
print("Uppercase:", sample_string.upper()) # Output: HELLO, WORLD!
print("Lowercase:", sample_string.lower()) # Output: hello, world!
# Split the string into a list of words
print("\nSplit:")
split_words = sample_string.split(', ')
print("Split words:", split_words) # Output: ['Hello', 'World!']
# Looping through the string
print("\nLooping:")
print("Characters in the string:")
for char in sample_string:
print(char, end=' ') # Output: H e l l o , W o r l d !
Loops
Using loops to iterate through a range and a while loop.
for i in range(5):
print(i)
num = 1
while num <= 5:
print(num)
num += 1
Output:
For loop Output
0
1
2
3
4
While loop output
1
2
3
4
5
Functions
Defining and calling functions.
def greet(name):
print("Hello,", name)
greet("Alice")
def add(a, b):
return a + b
result = add(5, 6)
print("Sum:", result)
Output:
The output for the above three functions are as follows
Hello,
Alice
Sum: 11
Lists
Working with lists and loop through elements.
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
mixed = [1, "Alice", True]
# Append to a list
numbers.append(6)
# Loop through a list
for num in numbers:
print(num)
Output:
1
2
3
4
5
6
Tuples
Working with tuples and unpacking.
# Creating a tuple
fruits = ("apple", "banana", "orange", "grape", "kiwi")
# Accessing elements by index
print("Accessing elements by index:")
print("First fruit:", fruits[0]) # Output: apple
print("Third fruit:", fruits[2]) # Output: orange
# Trying to modify a tuple (will result in an error)
# fruits[0] = "pear" # Uncommenting this line will raise a TypeError
# Unpacking a tuple
first, second, *rest = fruits
print("\nUnpacking a tuple:")
print("First fruit:", first) # Output: apple
print("Second fruit:", second) # Output: banana
print("Rest of the fruits:", rest) # Output: ['orange', 'grape', 'kiwi']
# Concatenating tuples
more_fruits = ("pineapple", "mango")
all_fruits = fruits + more_fruits
print("\nConcatenating tuples:")
print("All fruits:", all_fruits) # Output: ('apple', 'banana', 'orange', 'grape', 'kiwi', 'pineapple', 'mango')
# Length of the tuple
print("\nLength of the tuple:")
print("Number of fruits:", len(fruits)) # Output: 5
# Checking if an element exists in the tuple
print("\nChecking for element existence:")
print("Is 'banana' in fruits?", "banana" in fruits) # Output: True
print("Is 'pear' in fruits?", "pear" in fruits) # Output: False
# Iterating through the tuple
print("\nIterating through the tuple:")
for fruit in fruits:
print(fruit)
# Slicing a tuple
print("\nSlicing a tuple:")
print("Slice [1:4]:", fruits[1:4]) # Output: ('banana', 'orange', 'grape')
# Attempting to unpack more variables than available (will result in an error)
# a, b, c, d, e, f, g = fruits # Uncommenting this line will raise a ValueError
# Creating a single-element tuple
single_tuple = ("single",) # Note the comma after the single element
print("\nCreating a single-element tuple:")
print("Single tuple:", single_tuple) # Output: ('single',)
Dictionaries
Creating and accessing dictionary elements.
student = {
"name": "Alice",
"age": 20,
"course": "Computer Science"
}
# Accessing values
print("Name:", student["name"])
print("Age:", student["age"])
print("Course:", student["course"])
Output:
Name: Alice
Age: 20
Course: Computer Science
Sets
Working with sets and performing set operations.
numbers = {1, 2, 3, 4, 5}
even = {2, 4, 6, 8}
odd = numbers - even
# Add elements to a set
numbers.add(6)
# Loop through a set
for num in numbers:
print(num)
Output:
1
2
3
4
5
6
Click this for OOPs in Python
Click this for Exception Handling
Click this for File Handling
Comments
Post a Comment