Muppai Rojullo Python
Muppai Rojullo Python
🔥
By MASS CODERS - DODAGATTA NIHAR
Tap on the arrow mark below for notes and questions.
Day 1
Why Python?
Python is a popular programming language known for its simplicity, readability,
and versatility. Its numerous benefits and features have gained widespread
adoption in various fields. Some of the main reasons why Python is widely used
are:
1. Web Development
2. Game Development
3. Artificial Intelligence and Machine Learning
Output:
Nenu Python Muppai rojullo nerchkunta
Note:
Syntax sakkaga follow avvali appdudaithe ne correct output ostadi.
Possible Mistakes:
Ilanti tappulu asal cheyyak mowa.
Spelling Mistakes:
prnt(”Hello World!”)
Uppercase ‘P’:
Print(”Hello World!”)
Missing quotes:
print(Hello World!)
Calculations
Nuv Python ni vaadi addition, subtraction, multiplication, division lu kuda
cheyachu!
Assigning Variables
a = "Nihar"
b = "Loves"
c = "Python"
print(a+" "+b+" "+c)
#Output: Nihar Loves Python
a = 2
b = 5
print(a+b)
#Output: 7
Output:
Enter your name: Dodagatta Nihar
Your name is Dodagatta Nihar
Inthe mowa chaala simple ippudu questions ithe practice chesey settu! Emanna
doubt lu osthe telegram community lo adgu nenu, nee mithrulu ready ga untam
neeku help cheyyadaniki.
Variables
a = "Nihar"
print(a) #Output: Nihar
a = "Honey"
print(a) #Output: Honey
Data Types
Mukhyanga naalugu data types untay mowa
2. Create a variable name and assign your name to it. Print a greeting message
using your name.
3. Define a variable pi and assign the value of π (pi) to it. Print the value of
pi .
4. Define a variable is_raining and ask the user to input either "True" or
"False" (as a string). Convert the input to a boolean and print its type.
6. Given two variables x and y , perform the following operations and print the
results:
Addition of x and y .
Subtraction of y from x .
Multiplication of x and y .
Division of x by y .
These questions cover a range of scenarios related to variables and data types
in Python. You can use input() function to get user input for interactive questions.
Order of Instructions
Python line by line code ni execute chestundi mowa
print(a)
a = "Naa peru Nihar!"
Output:
ERROR!
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'a' is not defined
a = 10 + 5
b = 5
print(a/b)
Output:
ERROR!
File "<string>", line 3
BODMAS
The BODMAS rule stands for:
1. B - Brackets first
# Example expression: 10 + 5 * (2 ** 3) - 6 / 2
result = 10 + 5 * (2 ** 3) - 6 / 2
# 1
result = 10 + 3 * 2 - 8 / 4
# 3
result = (8 + 4) * 3 / 2
# 4
result = 16 / 4 + 2 ** 3 - 6
# 5
result = 10 - 3 * (4 + 2) / 5
String Concatenation
Strings ni kalapadaanne string concatenation antaru mowa.
Possible Mistakes
Idi only strings ki maatrame vaadtam. Nuv oka string ni oka number ni kalpalevu,
ala chesthe error ostundi
a = "Hi" + 10
print(a)
Output:
ERROR!
Traceback (most recent call last):
String Repetition
* operator ni vaadi strings ni repeat cheyinchachu neek kaavalsinanni saarlu
a = "Nihar " * 5
print(a)
Output:
s = "Arrow"
s = ("* " * 3) + s + (" *" * 3)
print(s)
Output:
* * * Arrow * * *
Length of String
Nuv string length kanukkovalante len() built-in function vaadu mowa.
name = input()
length = len(name)
print(length)
Output:
Arrow
5
2. Ask the user to enter their name and a greeting. Concatenate the name and
greeting to form a personalized message and print it.
4. Ask the user to enter a word and a number. Repeat the word as many times
as the given number and print the result.
5. Create a string sentence and find its length. Print the length of the sentence.
Expected Output: 27
6. Ask the user to input a sentence. Find the length of the sentence, and print
the last character of the sentence.
7. Create two strings str1 and str2 . Find the lengths of both strings and
concatenate them. Print the concatenated string.
8. Ask the user to enter two words, word1 and word2 . Concatenate the two
words with a space in between and print the result.
Expected Output:
*
**
***
****
*****
Type conversion python la oka data type nunchi inko data type laki convert
cheyyadaniki vaadtam mowa! Idi manam python built-in functions vaadi
chestham.
Example ki int(), float(), str() etc.
For example, "123” ane string ni integer laki maarchali ante int() vaadtam
num_string = "123"
print(type(num_string))
num_int = int(num_string)
print(type(num_int))
Output:
<class 'str'>
<class 'int'>
num_float = 3.14
num_int = int(num_float)
print(num_int)
print(type(num_int))
Output:
num_int = 123
print(type(num_int)) # Output: <class 'int'>
num_string = str(num_int)
print(num_string) # Output: 123
print(type(num_string)) # Output: <class 'str'>
num_float = 3.14
print(type(num_float)) # Output: <class 'float'>
num_string = str(num_float)
print(num_string) # Output: 3.14
print(type(num_string)) # Output: <class 'str'>
Expected Input:
value = 42
Expected Output:
result = "42"
Question 2:
Convert the string "123" to an integer.
Expected Input:
value = "123"
Expected Output:
result = 123
value = 3.14
Expected Output:
result = 3
Question 4:
Convert the string "5.5" to a floating-point number.
Expected Input:
value = "5.5"
Expected Output:
result = 5.5
Question 5:
Convert the integer 100 to a boolean.
Expected Input:
value = 100
Expected Output:
result = True
Question 6:
Convert the boolean True to an integer.
Expected Input:
value = True
Expected Output:
result = 1
Question 7:
Convert the string "False" to a boolean.
Expected Input:
Day 6
String Indexing
String Indexing ni manam String lo individual characters ni extract cheyyadaniki
vaadtam.
Index of first character - 0
Index of last character - (length - 1)
# Define a string
my_string = "Hello, world!"
Negative index vaadi kuda manam characters ni extract cheyyachu. Kinda oka
example undi chudandi
# Define a string
my_string = "Hello, world!"
s = "NIHAR"
Output:
Last character: R
Second last character: A
Third last character: H
Fourth last character: I
First character: N
String Slicing
Manam string lo oka particular portion ni extract cheyyali ante string slicing
vaadtam using :
# Define a string
my_string = "Hello, world!"
# Define a string
my_string = "Hello, world!"
Relational Operators
Veetini manam python lo two values ni compare cheyyadaniki vaadtam.
Equal to (==)
x = 5
y = 7
print(x == y) # False
print(x != y) # True
print(x > y) # False
print(x < y) # True
print(x >= y) # False
print(x <= y) # True
Note: Double equals sign (==) ni comparison kosam vaadtam, single equals sign
(=) ni variable assignment kosam vaadtam.
a = 5
b = 2-7
print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
Logical Operators
Mukhyanga moodu logical operators untay mowa python lo.
x and y ni operands ankunte
Tip:
True and True ⇒ True
True and False ⇒ False
False and True ⇒ False
False and False ⇒ False
result = a and b
print(result) # Output: False
orOperator:
The or operator returns True if at least one of the operands is True. If both
operands are False, it returns False.
not Operator:
The not operator returns the opposite boolean value of the operand. If the
operand is True, it returns False, and vice versa.
result = not a
print(result) # Output: False
In this example, (x < y) and (y < z) evaluates to True , and then the whole
expression becomes True or (x == z) , which is also True . Hence, the final
output is True .
3. Example: "and" operator with one True and one False condition
Input: (5 >= 3) and (10 != 10)
Output: False
if condition1:
# Code block executed if condition1 is True
elif condition2:
# Code block executed if condition1 is False and condition2 is True
else:
# Code block executed if both condition1 and condition2 are False
Using if statement:
The if statement is used to execute a block of code if a specified condition is
True.
Output:
Output:
Output:
Expected Input:
Enter a number: 7
Expected Output:
Question 2:
Write a program that takes two numbers as input and prints the larger number.
Expected Input:
Expected Output:
22
Question 3:
Write a program that takes a character as input and prints "Vowel" if it's a vowel
(a, e, i, o, u), and "Consonant" otherwise.
Expected Input:
Enter a character: a
Expected Output:
Vowel
Question 4:
Write a program that takes a year as input and prints "Leap Year" if it's a leap
year, and "Not a Leap Year" otherwise.
Expected Input:
Expected Output:
Leap Year
Expected Input:
Expected Output:
Pass
if x > 0:
print("x is positive.")
if x % 2 == 0:
print("x is even.")
else:
print("x is odd.")
else:
print("x is not positive.")
Output:
x is positive.
x is even.
Explanation:
In this example, we have a nested if statement inside the outer if statement.
Output:
Grade: B
Good job!
Explanation:
In this example, we have nested if-elif-else statements. The outer if-elif-
else checks the score to assign a grade. If the score is greater than or equal to
90, it prints "Grade: A." If the score is between 80 and 89, it enters the inner if
statement to check if the score is greater than or equal to 85 and prints "Good
job!" along with "Grade: B." If the score is between 70 and 79, it prints "Grade:
C." If the score is less than 70, it prints "Grade: Below C."
Telugu Explanation:
Ee example lo score = 85, bayata unna if condition score≥90, idi tappu kaabatti
next elif statement ki eltadi. Akkada score ≥80 undi, idi correct ee kaabatti
“Grade: B” ani print avtadi. next line lo score≥85 undi, idi kuda correct ee
kaabatti “Good job!” ani print avtadi.
Question 1:
Check if a given number num is positive, negative, or zero.
Expected Input:
num = 8
Expected Output:
Positive
Question 2:
Determine the type of a given number num : even or odd, and whether it is
positive or negative.
Expected Input:
num = -5
Expected Output:
Negative
Odd
Question 3:
Classify a given age into four categories: baby, child, teenager, or adult.
Expected Input:
age = 16
Teenager
Question 4:
Assign a grade to a given percentage , considering the following grade scale: A
(90-100), B (80-89), C (70-79), D (60-69), and F (below 60).
Expected Input:
percentage = 78
Expected Output:
Grade: C
Question 5:
Check if a given year is a leap year, and if it is, find the number of days in
February for that year.
Expected Input:
year = 2000
Expected Output:
While Loop
In Python, a while loop is used to repeatedly execute a block of code as long as
a specified condition is True. The loop continues until the condition becomes
False.
while condition:
# Code block to be executed while the condition is True
Example 1:
Output:
1
2
3
4
5
Explanation:
In this example, we initialize a variable num with the value 1. The while loop
starts executing when the condition num <= 5 is True. It prints the value of num
and then increments it by 1 ( num += 1 ). The loop continues executing the code
block as long as the condition num <= 5 remains True. When num becomes 6, the
condition becomes False, and the loop terminates.
It's important to ensure that the condition in the while loop eventually becomes
False; otherwise, the loop will run indefinitely, leading to an infinite loop.
Telugu Explanation:
Manam num ani variable lo 1 value store chestunnam. while num≤5 inappudu,
lopala unna code execute avtadi. Last lo num value ni +1 increase chestunnam,
ante ippudu num = 2. mari 2 kuda 5 kante takkuve kaabatti loop inkosari execute
Output:
Explanation:
In this example, we use a while loop to find the sum of numbers from 1 to 10.
We initialize a variable num with the value 1 and a variable sum_of_numbers with
the initial value 0. The while loop starts executing when the condition num <= 10
is True. Inside the loop, we add the current value of num to the sum_of_numbers
and then increment num by 1 ( num += 1 ). The loop continues executing the code
block as long as the condition num <= 10 remains True. When num becomes 11,
the condition becomes False, and the loop terminates.
The loop iterates ten times, adding the numbers 1 to 10 to the sum_of_numbers ,
and then stops when the condition becomes False. The final value of
sum_of_numbers is printed as the sum of numbers from 1 to 10, which is 55.
Telugu Explanation:
Ee example lo num = 1 and sum_of_numbers = 0 ki initialise chestunnam.
num≤10 ayyevarku loop execute avtadi. Prathi iteration lo sum_of_numbers ni
num value tho add chestunnam. Loop nunchi bayataki ochaka sum_of_numbers
value ni print chestunnam.
Note:
1
2
3
4
5
6
7
8
9
10
Question 2:
Create a while loop that calculates the sum of numbers from 1 to n, where n is
the input.
Expected Input: 5
Expected Output: 15 (1 + 2 + 3 + 4 + 5)
Question 3:
Write a while loop that prints even numbers from 2 to 10.
Expected Output:
2
4
6
8
10
Question 4:
Create a while loop that keeps prompting the user for a number until they enter a
negative number.
10
9
8
7
6
5
4
3
2
1
Question 6:
Create a while loop that asks the user to guess a secret number (e.g., 7) and
continues until the correct number is guessed.
Expected Output: (Depends on user input)
Question 7:
Write a while loop that calculates the factorial of a given number.
Expected Input: 4
Expected Output: 24 (4! = 4 * 3 * 2 * 1 = 24)
Question 8:
Create a while loop that prints the Fibonacci series up to n.
Expected Input: 10
Expected Output:
0
1
1
2
3
5
8
Question 9:
Write a while loop that reads numbers from the user until they enter the number
0. Then, it prints the sum of all the entered numbers.
Question 10:
Create a while loop that prints the square of numbers from 1 to 5.
Expected Output:
1
4
9
16
25
For Loop
In Python, a for loop is used to iterate over a sequence (such as a list, tuple,
string, or range) and execute a block of code for each item in the sequence. The
loop continues until all items in the sequence have been processed.
Ante ee particular sequence lo unna prathi okka item ki ee loop lopala unna
code ni execute cheyyu ani artham.
Example chuskunte:
Output:
1
2
Explanation:
In this example, we use a for loop to iterate over a range of numbers from 1 to
5 (excluding 6). The range function generates a sequence of numbers starting
from the first argument (1) and up to, but not including, the second argument (6).
For each value of num in the sequence, the loop executes the code block, which
prints the value of num .
The loop iterates five times, printing the numbers 1 to 5, and then stops when all
items in the sequence have been processed.
Telugu Explanation:
Manam ee for loop lo 1 nunchi 5 varku unna numbers ni print chestunnam.
range(1,6) ante 1 nundi 5 varku, 6 excluded ikkada. so 1 nundi 5 varku print
avtundi.
1
2
3
4
5
Input: None
Expected Output:
55
Input: None
Expected Output:
Input: None
Expected Output:
0
2
4
6
8
10
12
14
16
18
Input: None
Expected Output:
2
4
6
8
10
String Methods
Ante String tho aatalu aadkovadam! Randi aadukundam :)
string = "apple,orange,banana"
fruits = string.split(",")
print(fruits) # Output: ['apple', 'orange', 'banana']
find() : Returns the index of the first occurrence of a substring. If not found,
returns -1.
string = "12345"
result = string.isdigit()
print(result) # Output: True
string = "Hello"
result = string.isalpha()
print(result) # Output: True
Inka chaala useful methods unnay mowa ivi kaakunda! Avasaranni batti
vaadukuntam.
2. Given a string "Hello, World!", find its length using the len() method.
Input: "Hello, World!"
Expected Output: 13
5. Write a Python program that takes a user input string with leading and
trailing whitespaces and removes them using the strip() method.
Input: " Python Programming "
Expected Output: "Python Programming"
6. Given a string "I love Python programming", split it into words using the
split() method and print each word on a new line.
Input: "I love Python programming"
Expected Output:
I
love
Python
programming
7. Write a Python program that takes a user input string and replaces all
occurrences of "Python" with "Java" using the replace() method.
Input: "I love Python programming, Python is great."
Expected Output: "I love Java programming, Java is great."
8. Given a string "Hello, World!", check if it starts with the word "Hello" using
the startswith() method.
9. Write a Python function that takes a string as input and checks if it ends with
the word "end" using the endswith() method.
Input: "Hello, World!"
Expected Output: False
10. Given a string "banana", count the occurrences of the letter "a" using the
count() method.
Input: "banana"
Expected Output: 3
11. Write a Python program that takes a user input string and finds the index of
the first occurrence of the letter "l" using the find() method.
Input: "Hello, World!"
Expected Output: 2
12. Given a string "12345", check if it consists of only digits using the isdigit()
method.
Input: "12345"
Expected Output: True
Nested Loops
Oka loop lopala inko loop pedte nested loop mowa.
Output:
Output:
*
* *
* * *
* * * *
* * * * *
Ivi baa nerchkunte manam complex data structures ni manam baaga handle
cheyachu!
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
4. Create a nested loop that prints a hollow square pattern of stars (asterisks).
Expected Input: None
Expected Output:
*****
* *
* *
* *
*****
5. Write a nested loop to calculate and print the sum of numbers from 1 to 5
using nested iteration.
6. Create a nested loop to print the reverse of the multiplication table from 1 to
5 (up to 10 times each).
Expected Input: None
Expected Output:
5 4 3 2 1
10 8 6 4 2
15 12 9 6 3
20 16 12 8 4
25 20 15 10 5
*
**
***
****
*****
8. Create a nested loop to find and print prime numbers from 2 to 20.
Expected Input: None
Expected Output: 2 3 5 7 11 13 17 19
*
***
*****
***
*
10. Create a nested loop to find and print the factorial of numbers from 1 to 5.
Expected Input: None
Expected Output: 1 2 6 24 120
break Statement:
The break statement is used to terminate a loop prematurely when a certain
condition is met.
# Example: Using 'break' to stop the loop when the value reaches 3
for num in range(1, 6):
if num == 3:
break
print(num)
Output:
1
2
Explanation:
In this example, the loop runs from 1 to 5, but when num becomes 3, the break
continueStatement:
The continue statement is used to skip the current iteration of a loop and move
to the next iteration.
Output:
Explanation:
In this example, the loop runs from 1 to 5, but when an even number is
encountered (2 and 4), the continue statement is used, skipping the print
statement, and the loop moves to the next iteration.
Telugu Explanation:
Ikkada loop 1 nundi 5 varku execute itadi mowa, kaani madyalo even numbers
(2 and 4) indi ankondi, continue statement undadam valla, next unna print
statement skip ipoyyi, next iteration loki elpotadi.
Statement:
pass
The pass statement is used as a placeholder when you don't want to execute
any code inside a loop or a conditional block.
Explanation:
In this example, the loop runs from 1 to 5, but the pass statement does nothing
inside the loop.
Telugu Explanation:
pass unte loop lopala unna code edi execute avvad mowa simple.
1. Write a Python program to print all numbers from 1 to 10, but stop the loop
immediately when reaching 5 using the break statement.
Expected Output:
1
2
3
4
Expected Output:
1
2
4
5
3. Write a Python function that takes a string as input and checks if it contains
the letter 'o'. If it does, print "Found 'o'" and use the break statement to stop
searching.
Found 'o'
4. Given a list of numbers [1, 2, 3, 4, 5], use a for loop to double each
element and print the result. However, if the element is 4, use the continue
statement to skip it.
Expected Output:
2
4
6
10
5. Write a Python program to print all numbers from 1 to 20 using a while loop.
However, stop the loop when reaching 15 using the break statement.
Expected Output:
1
2
3
... (up to 15)
if string1 == string2:
print("Both strings are equal.")
else:
print("The strings are not equal.")
if string1 != string2:
print("The strings are not equal.")
else:
print("Both strings are equal.")
Output:
Output:
1. Given two strings "Python" and "python", check if they are equal using the
equality operator ( == ).
Input: "Python", "python"
Expected Output: False
Input: ""
Expected Output: True
Lists
Oka collection of items ni store cheskovadaniki list ni ithe vaadtam mowa!
Lists are mutable, ante nuv daanni modify cheskovachu ante kotha elements ni
add cheyachu, avasaram lenivi teeseyachu, alaaaaa!
List lo unna items ni square brackets [ ] lo esi pedtam, separated by a comma.
Accessing Elements:
Modifying Elements:
List Operations:
# Concatenation
result = list1 + list2
print(result) # Output: [1, 2, 3, 4, 5, 6]
# Repetition
repeated_list = list1 * 3
print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
List Methods:
# Adding elements
fruits.append("grape")
print(fruits) # Output: ['apple', 'banana', 'orange', 'grape']
# Removing elements
fruits.remove("banana")
print(fruits) # Output: ['apple', 'orange', 'grape']
# Sorting elements
fruits.sort()
print(fruits) # Output: ['apple', 'grape', 'orange']
Lists are widely used in Python for storing and manipulating data. They are
flexible, efficient, and an essential tool for various programming tasks.
Understanding lists and their methods will help you work with collections of data
effectively in Python.
1. Write a Python program that takes a list of numbers [1, 2, 3, 4, 5] and prints
each number on a new line.
Input: [1, 2, 3, 4, 5]
Expected Output:
1
2
3
4
5
3. Write a Python function that takes a list of numbers as input and returns the
sum of all the numbers.
4. Given a list of numbers [10, 20, 30, 40, 50], find the maximum number using
the max() function and print the result.
Input: [10, 20, 30, 40, 50]
Expected Output: 50
5. Write a Python program that takes a list of names ["Alice", "Bob", "Charlie"]
and checks if a given name (e.g., "Alice") is present in the list. Print "Name
found" if the name is in the list; otherwise, print "Name not found".
Tuples
Idi kuda list laaga oka data structure eyy! kaani tuples are immutable ante
okasari deenni create chesnaka elements ni nuv add or remove cheyyalev ani.
Elements anni parentheses () lo esi pedtam seperated by a comma.
Example chusthe:
Creating Tuples:
Accessing Elements:
Tuple Functions:
Tuples support various built-in functions like len() , min() , and max() .
# Concatenation
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4, 5, 6)
# Repetition
repeated_tuple = tuple1 * 3
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Tuples are handy when you need to store data that should remain unchanged
throughout your program's execution. Their immutability makes them suitable for
certain use cases, providing a safe and efficient way to group related data.
2. Access the second element from the given tuple: ('cat', 'dog', 'bird', 'fish').
Expected Input: No input required.
Expected Output: 'dog'
4. Find the length of the tuple: (10, 20, 30, 40, 50).
Expected Input: No input required.
Expected Output: 5
5. Check if the element 25 exists in the tuple: (10, 20, 30, 40, 50).
Expected Input: No input required.
Expected Output: False
6. Create a new tuple with elements from the given tuple (3, 6, 9) repeated 3
times.
Expected Input: No input required.
Expected Output: (3, 6, 9, 3, 6, 9, 3, 6, 9)
fruit1 = 'apple'
fruit2 = 'banana'
fruit3 = 'orange'
Dictionaries
Examples chuskunte:
Creating Dictionaries:
You can create a dictionary by enclosing key-value pairs in curly braces.
Accessing Values:
You can access values in a dictionary using keys. Dictionary keys are unique.
2. Question: Create a dictionary to store the age of two people, "John" and
"Alice." John is 25 years old, and Alice is 30 years old.
Expected Output: {"John": 25, "Alice": 30}
5. Question: Access the value associated with the key "score" from the given
dictionary.
Expected Input: Dictionary: {"name": "John", "age": 22, "score": 85}
Expected Output: 85
7. Question: Access the value associated with the key "phone" from the given
dictionary. If the key does not exist, return "Not available."
Expected Input: Dictionary: {"name": "Eve", "age": 27}
Expected Output: "Not available"
# Modifying value
student["gpa"] = 4.0
print(student)
Dictionary Methods:
Python provides various built-in methods to perform common operations on
dictionaries.
2. Question: Add a new key-value pair to the dictionary fruits , where the key
is "orange" and the value is 3.
3. Question: Given the dictionary inventory , remove the key "sugar" and its
associated value from the dictionary.
Expected Input: inventory = {"apple": 10, "banana": 15, "sugar": 2}
Expected Output: {"apple": 10, "banana": 15}
5. Question: Given the dictionary scores , check if the key "Alice" exists. If it
exists, print the associated value; otherwise, print "Key not found."
Expected Input: scores = {"Bob": 85, "Charlie": 90, "Alice": 78}
Expected Output: 78
7. Question: Given the dictionary student_grades , find the highest grade and its
corresponding student name. The dictionary contains student names as
keys and their grades as values.
Expected Input: student_grades = {"Alice": 85, "Bob": 90, "Charlie": 78}
Expected Output: ("Bob", 90)
Sets
Sets ante oka unordered collection of unique elements mowa, ante oka element
set ki rendu rendu moodu moodu undav okate untadi and then ee particular
order lone align ayyi undali ee elements ani em ledu, vaatiki istam ochinattu avi
undachu.
constructor.
Creating a Set:
my_set = {1, 2, 3}
my_set.add(4)
my_set.add(5)
print(my_set) # Output: {1, 2, 3, 4, 5}
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set) # Output: {1, 2, 4, 5}
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
my_set = {1, 2, 3, 4, 5}
print(3 in my_set) # Output: True
print(6 not in my_set) # Output: True
Functions Part - 1
Creating a Function:
To define a function, you use the def keyword, followed by the function name, a
pair of parentheses () , and a colon : . The code block inside the function is
indented and contains the instructions that the function will execute when called.
def greet():
print("Hello, World!")
Function Parameters:
You can define parameters inside the parentheses to pass data into the function.
Parameters act as placeholders for the actual values that you provide when
calling the function.
def greet_user(name):
print(f"Hello, {name}!")
Return Statement:
Functions can return values using the return keyword. When a function returns
a value, you can capture it and use it elsewhere in your code.
Expected Output:
message = greet()
print(message) # Output: Hello, World!
message = greet_user("Alice")
print(message) # Output: Hello, Alice!
Expected Output:
Expected Output:
result = check_even_odd(7)
print(result) # Output: Odd
Expected Output:
message = greet_user()
print(message) # Output: Hello, Guest!
Expected Output:
result = square(5)
print(result) # Output: 25
Functions Part - 2
Default Parameters:
def greet_user(name="Guest"):
print(f"Hello, {name}!")
def greet(name):
return f"Hello, {name}!"
def greet_and_emphasize(name):
greeting = greet(name)
return greeting.upper() + "!!!"
result = greet_and_emphasize("Alice")
print(result) # Output: HELLO, ALICE!!!
Scope of Variables:
Global ga declare chesina variables ni program lo nuv ekkadpadte akkad
vaadkovach mowa! Ade nuv oka variable ni function lopata declare chesthe nuv
daani aa particular function lo maatrame vaadkogalav.
def function_with_local_variable():
local_variable = "I'm local"
print(global_variable) # Output: I'm global
print(local_variable) # Output: I'm local
function_with_local_variable()
print(global_variable) # Output: I'm global
# print(local_variable) # Raises NameError: name 'local_variable' is not def
ined
Expected Output:
Expected Output:
Expected Output:
result = square_and_double(5)
print(result) # Output: 50
the function.
Expected Output:
Expected Output:
result = divide_and_remainder(15, 4)
print(result) # Output: (3, 3)
Expected Output:
result = factorial(5)
print(result) # Output: 120
Function Arguments
Positional Arguments:
Positional arguments are the most basic type of arguments. They are matched
to function parameters based on their order of appearance.
Default Values:
You can provide default values for function parameters. If a value is not passed
for that parameter when the function is called, the default value will be used.
Expected Output:
Expected Output:
Expected Output:
result = multiply(5)
print(result) # Output: 10
Expected Output:
print_info("Alice", 25, "USA") # Output: Name: Alice, Age: 25, Country: USA
Built-in Functions
max() and min() - Returns the maximum and minimum values from a sequence.
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 1, 2, 3, 4, 5, 6, 9]
These are just a few examples of the built-in functions available in Python. There
are many more built-in functions that can be utilized for various purposes, and
you can find more details in the Python documentation.
Expected Output:
print(max_value) # Output: 15
print(min_value) # Output: 3
Write a Python program that takes a list of numbers as input and prints the sum
of all the elements in that list.
Expected Output:
print(total_sum) # Output: 15
Expected Output:
Expected Output:
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
Expected Output:
Expected Output:
number = -10
Pattern Printing
Right Triangle Star Pattern
def right_triangle(rows):
for i in range(1, rows + 1):
print("*" * i)
right_triangle(5)
# Output:
# *
# **
# ***
# ****
# *****
pyramid(5)
# Output:
# *
# ***
# *****
# *******
# *********
def hollow_square(rows):
for i in range(rows):
if i == 0 or i == rows - 1:
print("*" * rows)
else:
print("*" + " " * (rows - 2) + "*")
hollow_square(5)
# Output:
# *****
# * *
# * *
# * *
# *****
These are just a few examples of star patterns you can create using loops in
Python. You can modify the number of rows or add more patterns by adjusting
the loop ranges and the number of stars and spaces printed in each row.
*****
****
*
**
***
****
*****
*
**
* *
* *
*****
*
***
*****
*******
*********
*
**
***
****
*****
1. Create a variable name and assign your name to it. Print a greeting message
using the variable.
2. Convert the string "42" to an integer and assign it to a variable num . Print
the value and type of num .
3. Define a tuple with three elements: "cat" , "dog" , and "rabbit" . Print the
third element.
5. Write a program that takes your age as input and prints a message: "You are
6. Calculate the product of two numbers entered by the user and print the
result.
7. Format the variables item = "book" and price = 25.99 into a sentence.
10. Write a program that determines if a year entered by the user is a leap year.
12. Write a while loop that calculates the sum of numbers from 1 to 20.
14. Create a list of your favorite fruits and print the second fruit on the list.
15. Add the number 7 to a set. Add the number 7 again and observe the set's
behavior.
17. Create a tuple containing your birth year, birth month, and birth day.
18. Define a function calculate_average that takes a list of numbers as input and
returns their average.
19. Write a function power that takes two arguments, base and exponent , and
calculates base raised to the power of exponent .
20. Define a function that takes any number of strings as arguments and returns
them concatenated.
21. Check if the word "apple" is present in the string "I like apples and oranges" .
22. Count the occurrences of the letter "i" in the string "Mississippi" .
24. Create a dictionary representing a car with keys "make" , "model" , and
"year" . Print the car's model.
25. Add a new car to the dictionary, modify the year of an existing car, and
retrieve the make of a specific car.
1. Create a variable name and assign your name to it. Print a message using
the variable, such as: "Hello, [name]!"
2. Convert the string "37" to an integer and assign it to a variable num . Print
the value and type of num .
3. Define a tuple with four elements: "apple" , "banana" , "cherry" , and "date" .
Print the second element.
5. Write a program that takes your age as input and prints a sentence like: "You
are [age] years old."
6. Calculate the product of two numbers entered by the user and print the
result.
8. Write a function that takes an integer as input and returns whether it's a
prime number or not.
10. Write a program that prints the Fibonacci sequence up to a specified number
of terms.
12. Print each character of the string "Python" on a new line using nested loops.
13. Create a list of your favorite colors and print each color in a sentence: "I like
[color]."
14. Add the number 5 to a set. Add the number 5 again and observe the set's
behavior.
15. Write a function that takes a list as input and returns a new list with unique
elements only.
16. Create a tuple containing your birth year, birth month, and birth day. Print
each element separately.
17. Define a function calculate_average that takes a list of numbers as input and
returns their average.
18. Write a function factorial that calculates the factorial of a given number
using recursion.
19. Define a function that takes any number of strings as arguments and returns
them concatenated.
20. Check if the word "apple" is present in the string "I like apples and oranges."
21. Count the occurrences of the letter "t" in the string "Testing the text for
t's."
23. Create a dictionary representing a book with keys "title" , "author" , and
"year" . Print the author's name.
24. Add a new book to the dictionary, modify the title of an existing book, and
retrieve the year of a specific book.
*
**
***
****
*****
x = 5
x += 3
print(x)
d) read_input()
c) elif
d) then
d) Hello\\nWorld
11. Which data type is best suited to store a collection of unique values?
a) List
b) Set
c) Dictionary
d) Tuple
for i in range(5):
print(i * "*")
17. Which of the following is a valid way to add a key-value pair to a dictionary?
a) dict.add(key, value)
b) dict[key] = value
c) dict.insert(key, value)
d) dict.append(key, value)
num = 10
while num > 0:
print(num)
num -= 2
*
**
***
****
d) _underscore
d) Generates an error
27. How do you access the value associated with the key "age" in a dictionary
person ?
a) `person("age")
b)person["age"]
c)person.get("age")
d)person.value("age")`
c) 3
d) 3.333
*
***
*****
*******
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
self.grades = []
Args:
grade (float): The grade to be added to the list.
"""
def calculate_average(self):
"""
Calculate the average of all grades in the list.
Returns:
float: The average grade.
"""
student1.display_student_info()