Python Programming Basics Guide
Python Programming Basics Guide
1. What is Python?
Python is a high-level, interpreted programming language known for its simplicity and
readability. It allows developers to write clear programs for both small and large-scale
projects. Python is used for:
• Easy to learn: Python’s syntax is simple and very close to natural language,
making it a great language for beginners.
• Community support: It has a massive community, meaning you'll find lots of
tutorials, resources, and libraries.
• Cross-platform: Python works on different operating systems (Windows, macOS,
Linux, etc.).
• Versatile: Whether it's web development, data analysis, or automation, Python
has libraries for almost everything.
• IDE Options: Python can be written in any text editor, but for ease, it's better to
use an IDE. Some popular ones are:
o PyCharm: A full-featured IDE (Download from here).
o VS Code: A lightweight editor with Python support (Download from here)
- Recommended
o Jupyter Notebook: Great for data science and learning Python
interactively (Install with pip install notebook).
• Open any text editor like Notepad or an IDE like PyCharm/VS Code.
print("Hello, World!")
Unlike other compiled languages like C or Java, Python executes the code line by line,
which makes debugging easy. Python doesn't require you to compile your code into
machine language; the Python interpreter takes care of it.
1. Variables in Python
Variables in Python are used to store data values. They are created when you assign a
value to them, and you don’t need to declare their type (Python is dynamically typed).
• Variable names can contain letters (a-z, A-Z), numbers (0-9), and underscores (_).
• Variable names must start with a letter or an underscore.
• Variable names are case-sensitive (Name and name are different).
Example:
age = 25
name = "John"
is_student = True
Python has various built-in data types. Some common ones are:
Type Checking:
You can use the type() function to check the type of a variable.
x = 10
print(type(x)) # Output: <class 'int'>
3. Type Conversion
Python allows you to convert between data types using functions like
Example:
x = "10" # x is a string
y = int(x) # Convert string to integer
z = float(y) #Convert integer to float
print(z) #Output: 10.0
4. Arithmetic Operators
Common Operators:
• + (Addition)
• - (Subtraction)
• * (Multiplication)
• / (Division)
• // (Floor Division)
• % (Modulus)
• ** (Exponentiation)
Examples:
a = 10
b = 3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.3333...
print(a // b) # Output: 3 (Floor Division)
print(a % b) # Output: 1 (Modulus)
print(a ** b) # Output: 1000 (Exponentiation)
Example:
x, y, z = 10, 20, 30
print(x) # Output: 10
print(y) # Output: 20
print(z) # Output: 30
You can also assign the same value to multiple variables in one line:
x = y = z = 100
print(x, y, z) # Output: 100 100 100
6. Variable Reassignment
You can change the value of a variable at any point in your program.
Example:
x = 5
print(x) # Output: 5
x = 10
print(x) # Output: 10
In Python, we use the input() function to take input from the user. The data entered by
the user is always received as a string, so if you want to use it as a different data type
(e.g., integer or float), you'll need to convert it using type conversion functions like int()
or float().
The print() function is used to display output to the console. You can use it to display
text, variables, or results of expressions.
print("Hello, " + name + "! You are " + str(age) + " years old.")
You can also use f-strings (formatted string literals) for more readable code:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: "John Doe"
You can access individual characters in a string using indexing. Python uses zero-based
indexing, so the first character has an index of 0.
text = "Python"
print(text[0]) # Output: P
print(text[2]) # Output: t
You can also use negative indexing to start counting from the end of the string.
print(text[-1]) # Output: n
print(text[-3]) # Output: h
3. Comments in Python
Comments are ignored by the Python interpreter and are used to explain the code or
leave notes for yourself or others. They do not affect the execution of the program.
• Multi-line comments can be written using triple quotes ( """ or '''). These are
often used to write detailed explanations or temporarily block sections of code:
"""
This is a multi-line comment.
It can span multiple lines.
"""
print("Hello, Python!")
4. Escape Sequences
Escape sequences are special characters in strings that start with a backslash ( \). They
are used to represent certain special characters.
Example:
print("Hello\nWorld") # Output:
# Hello
# World
1. Assignment Operators
Assignment operators are used to assign values to variables. The simplest one is = which
assigns the value on the right to the variable on the left. There are also compound
assignment operators that combine arithmetic operations with assignment.
Examples:
x = 5 # Assigns 5 to x
x += 3 # Equivalent to x = x + 3, now x is 8
x -= 2 # Equivalent to x = x - 2, now x is 6
x *= 4 # Equivalent to x = x * 4, now x is 24
x /= 6 # Equivalent to x = x / 6, now x is 4.0
2. Comparison Operators
Comparison operators are used to compare two values. They return either True or False
depending on the condition.
Examples:
a = 10
b = 20
3. Logical Operators
Examples:
x = 5
y = 10
z = 15
# and operator
print(x > 0 and y > 5) # Output: True (both conditions are True)
# or operator
print(x > 10 or z > 10) # Output: True (one of the conditions is True)
# not operator
print(not(x > 10)) # Output: True (reverses False to True)
4. Membership Operators
Membership operators test for membership within a sequence, such as a list, string, or
tuple. They return True or False based on whether the value is found in the sequence.
Membership Operators:
Examples:
my_list = [1, 2, 3, 4, 5]
my_string = "Python"
5. Bitwise Operators
• &: Bitwise AND (sets each bit to 1 if both bits are 1).
• |: Bitwise OR (sets each bit to 1 if one of the bits is 1).
• ^: Bitwise XOR (sets each bit to 1 if only one of the bits is 1).
• ~: Bitwise NOT (inverts all the bits).
• <<: Left shift (shifts bits to the left by a specified number of positions).
• >>: Right shift (shifts bits to the right by a specified number of positions).
Examples:
a = 5 # In binary: 101
b = 3 # In binary: 011
# Bitwise AND
print(a & b) # Output: 1 (binary: 001)
# Bitwise OR
print(a | b) # Output: 7 (binary: 111)
# Bitwise XOR
print(a ^ b) # Output: 6 (binary: 110)
# Bitwise NOT
print(~a) # Output: -6 (inverts all bits)
# Left shift
print(a << 1) # Output: 10 (binary: 1010)
# Right shift
print(a >> 1) # Output: 2 (binary: 010)
6. Arithmetic Operators (Already Covered in Chapter 2)
Common Operators:
• + (Addition)
• - (Subtraction)
• * (Multiplication)
• / (Division)
• // (Floor Division)
• % (Modulus)
• ** (Exponentiation)
Examples:
a = 10
b = 3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.3333...
print(a // b) # Output: 3 (Floor Division)
print(a % b) # Output: 1 (Modulus)
print(a ** b) # Output: 1000 (Exponentiation)
Lists in Python
1. What is a List?
A list is a collection of items that are ordered, mutable (changeable), and allow
duplicate elements. Lists can hold items of different data types, such as integers,
strings, or even other lists.
Syntax:
Example:
You can access individual elements in a list using indexing. Remember that Python uses
zero-based indexing, so the first item is at index 0.
Syntax:
list_name[index]
Example:
You can also use negative indexing to access elements from the end of the list:
3. Modifying Lists
Lists are mutable, which means you can change the value of items in a list.
fruits[1] = "orange"
print(fruits) # Output: ['apple', 'orange', 'cherry']
Adding elements:
[Link]("grape")
print(fruits) # Output: ['apple', 'orange', 'cherry', 'grape']
[Link](1, "kiwi")
print(fruits) # Output: ['apple', 'kiwi', 'orange', 'cherry']
Removing elements:
[Link]("orange")
print(fruits) # Output: ['apple', 'kiwi', 'cherry']
• pop():Removes the element at a specific index (or the last item if no index is
provided).
[Link]()
print(fruits) # Output: []
4. Slicing Lists
Syntax:
list_name[start:stop:step]
• start: The index to start the slice (inclusive).
• stop: The index to stop the slice (exclusive).
• step: The number of steps to skip elements (default is 1).
Examples:
numbers = [0, 1, 2, 3, 4, 5, 6]
print(numbers[1:4]) # Output: [1, 2, 3] (from index 1 to 3)
print(numbers[:4]) # Output: [0, 1, 2, 3] (from start to index 3)
print(numbers[2:]) # Output: [2, 3, 4, 5, 6] (from index 2 to end)
print(numbers[::2]) # Output: [0, 2, 4, 6] (every 2nd element)
Python provides several built-in functions and methods for working with lists.
print(len(fruits)) # Output: 3
• sorted(list): Returns a new sorted list without changing the original list.
numbers = [5, 2, 9, 1]
print(sorted(numbers)) # Output: [1, 2, 5, 9]
print(numbers) # Original list remains unchanged: [5, 2, 9, 1]
numbers = [1, 2, 3, 4]
print(sum(numbers)) # Output: 10
• index(element): Returns the index of the first occurrence of the specified element.
print([Link]("apple")) # Output: 0
[Link]()
print(fruits) # Output: ['cherry', 'orange', 'apple']
numbers = [5, 2, 9, 1]
[Link]()
print(numbers) # Output: [1, 2, 5, 9]
6. Nested Lists
Lists can contain other lists, allowing you to create nested lists. This can be useful for
storing matrix-like data structures.
Example:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
1. Tuples in Python
Example:
single_element_tuple = ("apple",)
You can access elements in a tuple using indexing, just like with lists. Tuples also
support negative indexing.
Example:
Slicing Tuples:
3. Tuple Operations
Although tuples are immutable, you can perform various operations with them.
Tuple Concatenation:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple) # Output: (1, 2, 3, 4, 5, 6)
Tuple Repetition:
repeated_tuple = (1, 2) * 3
print(repeated_tuple) # Output: (1, 2, 1, 2, 1, 2)
Checking Membership:
4. Tuple Methods
Though tuples are immutable, Python provides some built-in methods for working with
tuples.
my_tuple = (1, 2, 3, 1, 1)
print(my_tuple.count(1)) # Output: 3
• Immutable: This property ensures that tuple data cannot be modified after
creation, making them useful for fixed data.
• Faster than Lists: Due to immutability, tuples are generally faster than lists.
• Can Be Used as Keys in Dictionaries: Since tuples are hashable, they can be
used as keys in dictionaries, unlike lists.
6. Sets in Python
A set is a collection of unique items that is unordered and unindexed. Sets do not
allow duplicate values. Sets are useful for performing operations like union, intersection,
and difference.
Syntax:
Example:
Empty Set:
To create an empty set, use the set() function (not {}, which creates an empty
dictionary).
empty_set = set()
7. Set Operations
The union of two sets combines all elements from both sets, removing duplicates.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # Output: {1, 2, 3, 4, 5}
Intersection:
The intersection of two sets returns elements that are common to both sets.
Difference:
The difference between two sets returns elements that are in the first set but not in the
second.
Symmetric Difference:
The symmetric difference returns elements that are in either of the sets but not in both.
8. Set Methods
Sets come with several useful methods for performing common tasks.
fruits_set.add("orange")
print(fruits_set) # Output: {'apple', 'banana', 'cherry', 'orange'}
• remove(): Removes a specified element from the set. Raises an error if the element
does not exist.
fruits_set.remove("banana")
print(fruits_set) # Output: {'apple', 'cherry'}
fruits_set.pop()
fruits_set.clear()
Common
General collection Fixed data Unique items
Uses
Dictionaries in Python
You can create a dictionary using curly braces {} or the dict() function.
Syntax:
my_dict = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Example:
Let's create a dictionary of famous cities in Karnataka and their popular dishes.
karnataka_food = {
"Bengaluru": "Bisi Bele Bath",
"Mysuru": "Mysore Pak",
"Mangaluru": "Neer Dosa"
}
Example:
You can also use the get() method to access values, which is safer because it doesn’t
throw an error if the key doesn’t exist.
You can add new key-value pairs or update existing values in a dictionary.
Adding an Item:
karnataka_food["Shivamogga"] = "Kadubu"
print(karnataka_food)
Updating an Item:
• pop(): Removes the specified key and returns the associated value.
mysuru_food = karnataka_food.pop("Mysuru")
print(mysuru_food) # Output: Mysore Pak
del karnataka_food["Mangaluru"]
karnataka_food.clear()
5. Dictionary Methods
6. Dictionary Characteristics
The if statement is used to test a condition. If the condition is True, the block of code
under the if statement is executed.
Syntax:
if condition:
# Code block to execute if the condition is True
Example:
Let's say you want to check if it's time for dinner (assuming dinner time is 8 PM).
Here, the program checks if the variable time is equal to 20 (8 PM). If it's 20, the
message "It's time for dinner!" is printed.
The else statement provides an alternative block of code to execute when the if
condition is False.
Syntax:
if condition:
# Code block if the condition is True
else:
# Code block if the condition is False
Example:
Let's extend the dinner example by adding an alternative action if it's not 8 PM.
time = 18 # 6 PM
if time == 20:
print("It's time for dinner!")
else:
print("It's not dinner time yet." )
If the condition (time == 20) is False (because the time is 6 PM), the program prints "It's
not dinner time yet."
The elif (short for "else if") statement checks another condition if the previous if or
elif condition was False. You can have multiple elif statements to test various
conditions.
Syntax:
if condition1:
# Code block if condition1 is True
elif condition2:
# Code block if condition2 is True
else:
# Code block if none of the above conditions are True
Example:
Let’s create a system to check meal times based on the time of the day:
time = 15 # 3 PM
if time == 8:
print("It's breakfast time!")
elif time == 13:
print("It's lunch time!")
elif time == 20:
print("It's dinner time!")
else:
print("It's not a meal time.")
• ==: Equal to
• !=: Not equal to
• <: Less than
• >:Greater than
• <=: Less than or equal to
• >=: Greater than or equal to
Example:
Let’s check if someone is eligible to vote in Karnataka (minimum age for voting is 18).
age = 19
Here, the condition age >= 18 checks if the age is greater than or equal to 18. If True, it
prints that the person is eligible to vote. Otherwise, it prints that they are not eligible.
You can also use logical operators to combine multiple conditions in if statements:
Example:
Let’s say you want to check if someone is eligible for a student discount. The person
must be both under 18 years of age and have a student ID.
age = 16
has_student_id = True
if age < 18 and has_student_id:
print("You are eligible for the student discount!")
else:
print("You are not eligible for the student discount." )
Here, the condition age < 18 and has_student_id checks if both conditions are True. If so,
the message "You are eligible for the student discount!" is printed.
Let’s create an example based on ticket prices for a Karnataka KSRTC bus. If the
passenger is under 5 years old, the ticket is free. If the passenger is between 5 and 12
years old, they get a child discount. If the passenger is 60 years or older, they get a
senior citizen discount. Otherwise, they pay the full fare.
age = 65
if age < 5:
print("Ticket is free.")
elif age <= 12:
print("You get a child discount." )
elif age >= 60:
print("You get a senior citizen discount." )
else:
print("You pay the full fare." )
In this example:
7. Nested if Statements
You can also use if statements inside other if statements. This is called nesting.
Example:
Let’s say you’re planning to visit Mysuru. You want to decide whether to go based on
the day of the week and the weather.
day = "Saturday"
is_raining = False
Here, the program first checks if it’s a weekend. If it is, it checks the weather. If it’s not
raining, it prints "Let's visit Mysuru!", otherwise, it prints "It's raining, let's stay
home." On weekdays, it prints "It's a weekday, let's wait for the weekend."
8. Indentation in Python
Python uses indentation (spaces at the beginning of a line) to define blocks of code.
The indented code after an if, elif, or else statement belongs to that condition. Make
sure to use consistent indentation to avoid errors.
Example:
age = 19
In the example above, the two print() statements are part of the if block because they
are indented. Be careful to maintain the correct indentation for your code to run
correctly.
9. The match-case Statement (Python 3.10+)
Starting from Python 3.10, you can use the match-case statement for pattern
matching—similar to switch-case in other languages like C or JavaScript. It helps you
write cleaner and more readable code when checking a variable against multiple
constant values.
Syntax:
match variable:
case value1:
# Code block for value1
case value2:
# Code block for value2
case _:
# Default case (like else)
Example:
day = "Sunday"
match day:
case "Monday":
print("Start of the work week.")
case "Friday":
print("Almost weekend!")
case "Saturday" | "Sunday":
print("It's the weekend!")
case _:
print("Just another weekday.")
The while loop repeatedly executes a block of code as long as the condition is True.
Syntax:
while condition:
# Code to execute as long as condition is True
Example:
i = 1
while i <= 5:
print(i)
i += 1 # Incrementing i by 1 after each iteration
Let’s relate this to a common example: Imagine you're counting sheep to fall asleep.
sheep_count = 1
while sheep_count <= 10:
print(f"Sheep {sheep_count}")
sheep_count += 1
This prints "Sheep 1", "Sheep 2", and so on, until "Sheep 10". After that, the loop
stops.
A while loop can run indefinitely if the condition is always True. To prevent this, ensure
that the condition eventually becomes False.
i = 1
while i <= 5:
print(i)
# Forgot to update i, so the condition remains True forever!
In this case, the loop will keep printing 1 forever because i is never incremented, so the
condition i <= 5 will always be True.
To avoid this, make sure to update the variable that controls the condition within the
loop.
4. Using break to Exit a while Loop
You can use the break statement to exit a loop when a certain condition is met.
Example:
Let’s stop counting sheep after 5 sheep, even though the condition allows counting up
to 10:
sheep_count = 1
while sheep_count <= 10:
print(f"Sheep {sheep_count}")
if sheep_count == 5:
print("That's enough counting!")
break
sheep_count += 1
• The loop stops after "Sheep 5" because of the break statement, even though
the condition was sheep_count <= 10.
Output:
Sheep 1
Sheep 2
Sheep 3
Sheep 4
Sheep 5
That's enough counting!
The continue statement is used to skip the current iteration and move on to the next
one.
Example:
Let’s say you want to skip counting sheep that are number 4:
sheep_count = 1
while sheep_count <= 5:
if sheep_count == 4:
sheep_count += 1
continue
print(f"Sheep {sheep_count}")
sheep_count += 1
Here, when sheep_count is 4, the continue statement skips printing "Sheep 4", and
the loop continues with sheep_count = 5.
Output:
Sheep 1
Sheep 2
Sheep 3
Sheep 5
You can use a while loop to repeatedly ask the user for input until they provide valid
data.
Example:
Let’s ask the user for a PIN until they enter the correct one:
pin = ""
correct_pin = "1234"
while pin != correct_pin:
pin = input("Enter your PIN: ")
if pin != correct_pin:
print("Incorrect PIN. Try again.")
print("PIN accepted. You can proceed.")
• The loop keeps running until the user enters the correct PIN.
• If the user enters an incorrect PIN, they are prompted to try again.
7. Real-life Example: KSRTC Bus Seats Availability
Let’s say you want to simulate a KSRTC bus seat booking system. The bus has 5 available
seats. Each time a seat is booked, the available seats decrease.
available_seats = 5
if booking == "yes":
available_seats -= 1
print("Seat booked!")
else:
print("No booking made.")
Here, the loop keeps running until all seats are booked. It checks the available seats and
asks the user if they want to book one. The loop stops when there are no more seats
available.
Output Example:
5 seats available.
Do you want to book a seat? (yes/no): yes
Seat booked!
4 seats available.
Do you want to book a seat? (yes/no): yes
Seat booked!
...
1 seats available.
Do you want to book a seat? (yes/no): yes
Seat booked!
All seats are booked!
8. Nested while Loops
You can also nest while loops inside each other. This can be useful in more complex
scenarios, such as checking multiple conditions or dealing with multi-level data.
Example:
Let’s simulate a snack machine that allows users to buy snacks as long as both the
machine has snacks and the user has money:
snacks_available = 3
money = 10
This loop will continue as long as there are snacks available and the user has money.
Once one condition is no longer True, the loop stops.
In Python, a for loop is used to iterate over a sequence (like a list, tuple, string, or range)
and execute a block of code repeatedly for each element in the sequence.
1. The Basic Structure of a for Loop
A for loop allows you to repeat a block of code a fixed number of times, or once for
each element in a sequence.
Syntax:
Example:
Output:
Bengaluru
Mysuru
Hubballi
Mangaluru
• Here, cities is a list, and the for loop iterates over each item (city) in that list.
The range() function generates a sequence of numbers, which you can use in a for loop
when you want to repeat a block of code a specific number of times.
Syntax of range():
Output:
1
2
3
4
5
6
7
8
9
10
This loop prints only the odd numbers between 1 and 10.
Output:
1
3
5
7
9
You can also loop over each character in a string using a for loop.
Example: Printing each character in a string
name = "Karnataka"
for letter in name:
print(letter)
Output:
K
a
r
n
a
t
a
k
a
This loop goes through the string "Karnataka" one character at a time.
You can also have nested for loops, which means a loop inside another loop. This is
useful when working with multi-level data, like lists inside lists.
Let’s print the multiplication table from 1 to 5 using a nested for loop.
Output:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
...
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
Here, the outer loop controls the first number ( i), and the inner loop controls the
second number (j). Together, they generate the multiplication table.
The break statement is used to exit a loop early when a certain condition is met.
In this case, the loop stops when it finds "Hubballi" and prints "Found Hubballi!".
Output:
Bengaluru
Mysuru
Found Hubballi!
6. Using continue in a for Loop
The continue statement is used to skip the current iteration of the loop and move on to
the next one.
Output:
Bengaluru
Mysuru
Mangaluru
Here, "Hubballi" is skipped, and the loop continues with the next city.
The enumerate() function allows you to loop over a sequence and get both the index and
the value of each item.
Output:
City 1: Bengaluru
City 2: Mysuru
City 3: Hubballi
City 4: Mangaluru
8. Using else with for Loops
You can also use an else clause with a for loop. The code inside the else block will
execute once the loop finishes, unless the loop is terminated by a break statement.
Example:
Output:
Bengaluru
Mysuru
Hubballi
Mangaluru
No more cities!
In this case, after the loop has finished going through all the cities, it prints "No more
cities!".
Imagine you have 5 laddus to distribute among friends. You can use a for loop to give
each friend one laddu.
laddus = 5
friends = ["Rahul", "Sneha", "Aman", "Priya"]
Output:
Here, the loop goes through the list of friends and distributes the laddus one by one.
Lists and Dictionaries with For Loops, List Comprehension, and Dictionary
Comprehension
In this video, we will learn how to use for loops with Lists and Dictionaries, followed by
advanced techniques using List Comprehension and Dictionary Comprehension.
These tools are essential for writing concise and efficient Python code.
A for loop is the most common way to iterate through items in a list.
Output:
numbers = [1, 2, 3, 4, 5]
doubled = []
for num in numbers:
[Link](num * 2)
Output:
Output:
I like Dosa
I like Idli
I like Vada
I like Bisibelebath
You can use for loops to iterate over dictionaries by accessing both keys and values.
Output:
Anand
Geetha
Kumar
Example: Iterating over dictionary values
Output:
85
90
78
Output:
You can also use for loops with the range() function to loop through a sequence of
numbers.
student_marks = {}
for i in range(len(students)):
student_marks[students[i]] = marks[i]
print(student_marks)
Output:
4. List Comprehension
Syntax:
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares)
Output:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
Output:
[2, 4, 6]
Example 3: Uppercasing Kannada city names
Output:
5. Dictionary Comprehension
Syntax:
numbers = [1, 2, 3, 4, 5]
squares_dict = {num: num ** 2 for num in numbers}
print(squares_dict)
Output:
Output:
city_population = {
"Bengaluru": 84,
"Mysuru": 11,
"Hubballi": 9,
"Mangaluru": 5
}
large_cities = {city: population for city, population in city_population.items() if
population > 10}
print(large_cities)
Output:
In Python, the split() method allows you to break a string into a list of words or
elements based on a specified separator (like space, comma, etc.). This is very useful
when you have data in string format and want to convert it into a list.
Syntax:
[Link](separator, maxsplit)
Output:
['I', 'love', 'coding', 'in', 'Python']
Here, the default separator (space) is used to split the string into individual words.
data = "apple,banana,mango"
fruits = [Link](",")
print(fruits)
Output:
Here, the comma (,) is used as the separator to split the string into different fruit names.
Output:
In this example, the string is split only twice. The rest of the string remains as the final
Practical Application
You can use the split() method when reading data from a text file or processing input
from a user where the data is separated by spaces, commas, or any other delimiters.
Once you split the data, you can work with it as a list, applying any list manipulation
techniques you've learned.
Functions
1. Basics of Functions
A function is a reusable block of code that performs a specific task when called.
Functions are useful to organize code, make it reusable, and reduce redundancy.
2. Defining a Function
You define a function using the def keyword followed by the function name,
parentheses, and a colon :.
Syntax:
def function_name(parameters):
# Block of code
def greet():
print("Hello! Welcome to the Python course.")
greet()
Output:
3. Function Parameters
def greet_user(name):
print(f"Hello, {name}! Welcome to the Python course.")
greet_user("Anand")
Output:
A function can return a value using the return keyword, which allows the output of the
function to be reused elsewhere.
Example: Function that adds two numbers and returns the result
Output:
You can define a default value for a parameter, which is used if no argument is passed
when the function is called.
def greet(name="Student"):
print(f"Hello, {name}! Welcome to the Python course.")
Here are the sections for Nested Functions and Local/Global Variables:
• Local Variables are defined inside a function and are only accessible within that
function.
• Global Variables are defined outside all functions and are accessible from
anywhere in the code.
def greet():
name = "Local Name"
print(name)
Output:
Local Name
Global Name
In this example, the local variable name inside the function does not affect the global
variable name.
In this part, we'll explore more advanced function concepts, including recursion, lambda
functions, and variable-length arguments.
1. Keyword Arguments
With keyword arguments, you can pass values to a function by specifying the parameter
names.
Example:
display_info(age=25, name="Kumar")
Output:
2. Variable-Length Arguments
You can use *args and **kwargs to accept a variable number of arguments in a function.
def total_sum(*numbers):
result = 0
for num in numbers:
result += num
return result
print(total_sum(1, 2, 3, 4))
Output:
10
Example: Using **kwargs
def student_info(**details):
for key, value in [Link]():
print(f"{key}: {value}")
Output:
name: Anand
age: 22
course: Python
3. Lambda Functions
A lambda function is a small anonymous function that can take any number of
arguments but has only one expression.
Syntax:
double = lambda x: x * 2
print(double(5))
Output:
10
4. Recursion
Recursion occurs when a function calls itself. It's used to solve problems that can be
broken down into smaller, similar problems.
Example: Recursive function to calculate factorial
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
Output:
120
Here are the sections for Nested Functions and Local/Global Variables:
5. Nested Functions
A nested function is a function defined inside another function. The inner function is only
accessible within the outer function, allowing for more modular and controlled code
execution.
def outer_function(name):
def inner_function():
print(f"Hello, {name}!")
inner_function()
outer_function("Anand")
Output:
Hello, Anand!
In this example, the inner_function() is called within outer_function() and uses the name
parameter of the outer function.