Python Module 1 Important Topics (1)
Python Module 1 Important Topics (1)
https://rtpnotes.vercel.app
Python-Module-1-Important-Topics
1. Data types
2. Operator's
3. Expressions
4. Int, float
5. Strings
6. Control statements
What are control statements
Iteration Structure
For loop
While loop
Selection statements
7. Switch
Python-Module-1-University-Questions-Part-A
1. What is the output of the following print statement in Python? (a) print (9//2) (b)
print (9/2)
2. Write a Python program to count number of even numbers and odd numbers in a
given set of n numbers.
3. What is the output of the following Python code. Justify your answer.
4. Jack says that he will not bother with analysis and design but proceed directly to
coding his programs. Why is that not a good idea?
5. Write the output of the following python statements :
6. Explain type conversion with example.
7. Write a program that accepts the lengths of three sides of a triangle as inputs and
outputs whether or not the triangle is a right triangle
8. Write a Python program to reverse a number and also find the sum of digits of the
number.Prompt the user for input
9. Explain the concept of scope and lifetime of variables in Python programming
language, with a suitable example.
Example
Python-Module-1-University-Questions-Part-B
1. Write a python program to generate the following type of pattern for the given N
rows .
2. Write the python program to print all prime numbers less than 1000.
3. Write a Python program to find distance between two points (x1,y1) and (x2,y2).
4. Write a Python program to find the roots of a quadratic equation, ax2+ bx + c =0 .
5. Write a Python program to check whether a number is Armstrong number or not.
6. Write a Python program to display the sum of odd numbers between a programmer
specified upper and lower limit.
7. Given the value of x, write a Python program to evaluate the following series upto n
terms:
8. Write a python program to find X^Y or pow(X,Y) without using standard function.
9. Write a python program to generate the following type of pattern for the given N
rows where N <= 26.
10. Discuss the steps involved in the waterfall model of software development
process with the help of a neat diagram.
11. Write a Python program to print all numbers between 100 and 1000 whose sum of
digits is divisible by 9.
12. Illustrate the use of range() in Python.
What is range?
Example
13. Write a Python program to print all prime factors of a given number.
14. Write a Python code to check whether a given year is a leap year or not
15. What are the possible errors in a Python program.
16. Write a Python program to print the value of 2^(2n)+n+5 for n provided by the
user.
17. Write a Python code to determine whether the given string is a Palindrome or not
using slicing. Do not use any string function.
1. Data types
A data type consists of a set of values and a set of operations that can be performed on
those values.
A literal is the way a value of a data type looks to a programmer. The programmer can use
a literal in a program to mention a data value.
2. Operator's
3. Expressions
Expressions provide an easy way to perform operations on data values to
produce other data values.
Arithmetic Expressions
An arithmetic expression consists of operands and operators.
4. Int, float
Integers - the integers include 0, all of the positive whole numbers, and all of the negative
whole numbers.
Floating - Point Numbers - A real number in mathematics, such as the value of pi
(3.1416...), consists of a whole number, a decimal point, and a fractional part.
5. Strings
In python, a string literal is a sequence of characters enclosed in single or double
quotation marks
"Hello There"
6. Control statements
What are control statements
Statements that allow the computer to select an action to perform in a particular action or
to repeat a set of actions.
Two types of control statements are there:
Selection structure
Iteration structure
Iteration Structure
Syntax
Example
Output
Its alive!
Its alive!
Its alive!
Its alive!
While loop
Conditional iteration requires that a condition be tested within the loop to determine
whether the loop should continue. Such a condition is called the loop’s continuation
condition.
If the continuation condition is false, the loop ends. If the continuation condition is true, the
statements within the loop are executed again
Syntax
while <condition>:
<sequence of statements>
Example
num = 10
while(num>0):
num = num - 1
print("Subtracting")
Selection statements
In some cases, instead of moving straight ahead to execute the next instruction, the
computer might be faced with two alternative courses of action.
The condition in a selection statement often takes the form of a comparison. The result of
the comparison is a Boolean value True or False.
if <condition>:
<sequence of statements-1>
elif <condition-n>
<sequence of statements-n>
else:
<default sequence of statements>
Example
num = 10
if(num > 10):
print("Num greater than 10")
elif(num == 10):
print("Num is equal to 10")
else:
print("Num is less than 10")
Output
7. Switch
A switch statement is a very useful and powerful programming feature. It is an alternate to
if-else-if ladder statement and provides better performance and more manageable code
than an if-else-if ladder statement.
Python does not provide inbuilt switch statements, we can implement on our own
Example
def get_week_day(argument):
switcher =
{
0: "Sunday" ,
1: "Monday" ,
2: "Tuesday" ,
3: "Wednesday" ,
4: "Thursday" ,
5: "Friday" ,
6: "Saturday"
}
return switcher.get(argument, "Invalid day")
print (get_week_day(6))
print (get_week_day(8))
print (get_week_day(0))
Output
Saturday
Invalid day
Sunday
Python-Module-1-University-Questions-
Part-A
1. What is the output of the following print statement in
Python? (a) print (9//2) (b) print (9/2)
(a) 4 (b) 4.5
Args:
numbers: A list of integers.
Returns:
A tuple containing the count of even numbers and odd numbers.
"""
even_count = 0
odd_count = 0
for num in numbers:
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
return even_count, odd_count
0
1
2
3
4. Jack says that he will not bother with analysis and design
but proceed directly to coding his programs. Why is that not
a good idea?
There are several reasons why skipping analysis and design and going straight to coding
is not a good idea for Jack:
Errors and rework: Without proper analysis, Jack might miss crucial requirements or
misunderstand the problem he's trying to solve. This can lead to errors in the code
that may not be apparent until later stages, requiring significant rework.
Inefficient solutions: Without design, Jack might write code that works but is
inefficient, poorly structured, or difficult to maintain. Design helps create a well-
organized and optimized solution.
Maintenance challenges: Code written without proper planning can be difficult to
understand and maintain for Jack himself or anyone else who might need to work on
it later. This can lead to time-consuming debugging and modifications in the future.
num = 3.8
converted_num = int(num)
print(converted_num) # Output: 3 (Decimal part truncated)
num = 10
converted_num = float(num)
print(converted_num) # Output: 10.0 (Integer converted to float)
Args:
a: Length of the first side.
b: Length of the second side.
c: Length of the third side.
Returns:
True if the triangle is right-angled, False otherwise.
"""
Scope refers to the part of your code where a variable is accessible. It determines
where you can use the variable's name to refer to its value.
There are two primary scopes in Python:
Global Scope: Variables defined outside any function are in the global scope. They
are accessible throughout the entire program.
Local Scope: Variables defined inside a function are in the local scope. They are
only accessible within that function.
Lifetime:
Lifetime refers to the duration for which a variable exists in memory. It determines how
long the memory allocated to the variable is reserved.
The lifetime of a variable is closely tied to its scope. A variable's memory is released when
it goes out of scope.
Example
# Global variable
message = "This message is accessible throughout the program."
# Main program
rectangle_length = 5
rectangle_width = 3
# This line would cause an error because 'length' and 'width' are local to
the function
# print("Length outside the function:", length)
# print("Width outside the function:", width)
message is defined outside any function, so it has global scope and is accessible
throughout the program. Its lifetime lasts until the program ends.
length , width , and area are defined inside the calculate_area function, so they
have local scope. They are only accessible within that function and their lifetime ends
when the function execution finishes.
Python-Module-1-University-Questions-
Part-B
1. Write a python program to generate the following type of
pattern for the given N rows .
1
12
123
1234
def generate_pattern(n):
"""
Generates a pattern of increasing numbers for the given number of rows.
Args:
n: The number of rows in the pattern.
"""
import math
# Example usage
x1, y1 = 1, 2
x2, y2 = 4, 6
distance = calculate_distance(x1, y1, x2, y2)
print(f"The distance between points ({x1}, {y1}) and ({x2}, {y2}) is
{distance}")
Here we import math module and compute the square root using math.sqrt()
Quadratic Formula
import math
# Example usage
a = 1
b = -3
c = 2
roots = find_roots(a, b, c)
print(f"The roots of the quadratic equation are: {roots}")
a = 1
b = 2
c = 1
roots = find_roots(a, b, c)
print(f"The roots of the quadratic equation are: {roots}")
a = 1
b = 2
c = 5
roots = find_roots(a, b, c)
print(f"The roots of the quadratic equation are: {roots}")
def is_armstrong_number(n):
# Convert the number to a string to easily get each digit
digits = str(n)
num_digits = len(digits)
# Loop through each digit and add the digit raised to the power of
num_digits to the sum
for digit in digits:
armstrong_sum += int(digit) ** num_digits
# Example usage
number = 153
if is_armstrong_number(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
number = 9474
if is_armstrong_number(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
number = 123
if is_armstrong_number(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
return total_sum
# Example usage
lower_limit = int(input("Enter the lower limit: "))
upper_limit = int(input("Enter the upper limit: "))
# Ensure the lower limit is less than or equal to the upper limit
if lower_limit > upper_limit:
print("Invalid input: lower limit should be less than or equal to upper
limit.")
else:
result = sum_of_odd_numbers(lower_limit, upper_limit)
print(f"The sum of odd numbers between {lower_limit} and {upper_limit}
is: {result}")
import math
return series_sum
# Example usage
x = float(input("Enter the value of x: "))
n = int(input("Enter the number of terms n: "))
result = evaluate_series(x, n)
print(f"The value of the series up to {n} terms is: {result}")
8. Write a python program to find X^Y or pow(X,Y) without
using standard function.
# Example usage
x = float(input("Enter the base (X): "))
y = int(input("Enter the exponent (Y): "))
result = power(x, y)
print(f"{x} raised to the power of {y} is: {result}")
def generate_pattern(rows):
# Define a string of uppercase letters
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1. Customer Request
1. In this phase, the programmers receive a broad statement of a problem
2. Analysis
1. The programmers determine what the program will do.
3. Design
1. The programmers determine how the program will do its tasks
4. Implementation
1. The programmers write the program
5. Integration
1. Large programs have many parts. In the integration phase, these parts are broguht
together into a smoothly functioning whole. Usually not an easy task
6. Maintenance
1. Programs usually have a long life. A lifespan of 5 to 15 years is common for software,
during this time, requirements change, errors are detected and minor/major modifications
are made.
def sum_of_digits(number):
# Initialize sum to 0
digit_sum = 0
return digit_sum
The range() function in Python is used to generate a sequence of numbers. It's commonly
used in for loops to iterate over a sequence of numbers. The range() function can take one,
two, or three arguments:
Example
for i in range(10):
print(i, end=' ')
# Output: 0 1 2 3 4 5 6 7 8 9
numbers = list(range(5))
print(numbers)
# Output: [0, 1, 2, 3, 4]
def prime_factors(number):
factors = []
divisor = 2
return factors
def is_palindrome(s):
return s == s[::-1]