0% found this document useful (0 votes)
34 views11 pages

Python Programs for Beginners

The document contains a series of Python programming exercises with solutions, including Armstrong numbers, series summation, multiplication through repeated addition, wage calculation for laborers, character replacement in strings, and list manipulations. Each question is followed by a detailed code solution demonstrating various programming concepts. The exercises aim to enhance programming skills and understanding of Python functions and control structures.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views11 pages

Python Programs for Beginners

The document contains a series of Python programming exercises with solutions, including Armstrong numbers, series summation, multiplication through repeated addition, wage calculation for laborers, character replacement in strings, and list manipulations. Each question is followed by a detailed code solution demonstrating various programming concepts. The exercises aim to enhance programming skills and understanding of Python functions and control structures.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

IT PROFESSIONAL COMPUTER INSTITUTE

Python Programs
_______________________________________
Questions 1. Write a program to print all Armstrong numbers in a given
range.
Note: An Armstrong number is a number whose sum of cubes of digits is
3 3 3
equal to the number itself. E.g. 370=3 +7 +0

Solution:
start_val = int(input("Enter Start Number : "))
end_val = int(input("Enter Stop Number : "))

for num in range(start_val, end_val + 1):

# length of number
power = len(str(num))

# initialize sum
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** power
temp //= 10

if num == sum:
print(num)

Created by – Raj
IT PROFESSIONAL COMPUTER INSTITUTE

Created by – Raj
IT PROFESSIONAL COMPUTER INSTITUTE

Quetions 2. Write a function to obtain sum n terms of the following series for any
positive integer value of X
X +X3 /3! +X5 /5! ! +X7 /7! + …

Solution: Output
method 1
def power(a, b):
p=1
for i in range(1, b + 1):
p=p*a
return p

def factorial(a):
fact = 1
for i in range(1, a + 1):
fact = fact * i
return fact

sum = 0
n = int(input('Enter the number of terms: '))
x = int(input('Enter the value of x: '))
for i in range(1, 2 * n + 1, 2):
sum = sum + power(x, i) / factorial(i)
print(sum)

Method 2
import math
sum = 0
n = int(input('Enter the number of terms: '))
x = int(input('Enter the value of x: '))
for i in range(1, 2 * n + 1, 2):
sum = sum + pow(x, i) / [Link](i)
print(sum)

Created by – Raj
IT PROFESSIONAL COMPUTER INSTITUTE

Question 3. Write a function to obtain sum n terms of the following series for any
positive integer value of X
1+x/1!+x2/2!+x3/3!+…

Solution:
import math
sum = 1
n = int(input('Enter the number of terms: '))
x = int(input('Enter the value of x: '))
for i in range(1,n):
sum = sum + pow(x, i) / [Link](i)
print(sum)

Output

Created by – Raj
IT PROFESSIONAL COMPUTER INSTITUTE

Question 4. Write a program to multiply two numbers by repeated


addition
e.g. 6*7 = 6+6+6+6+6+6+6

Solution:
a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
sum = 0
for i in range(b):
sum = sum + a

print("The multiply in repeated form is: ",sum)

Output

Created by – Raj
IT PROFESSIONAL COMPUTER INSTITUTE

Question 5. Write a program to compute the wages of a daily laborer as per the
following rules: -
Hours Worked Rate Applicable Upto first 8 hrs Rs100/-
a) For next 4 hrs Rs30/- per hr extra
b) For next 4 hrs Rs40/- per hr extra
c) For next 4 hrs Rs50/- per hr extra
d) For rest Rs60/- per hr extra

Solution
worked_h = int(input("Enter Total Worked hours: "))
if worked_h <= 8:
wages = worked_h*100
elif worked_h > 8 and worked_h <= 12:
wages = (worked_h-8)*30+worked_h*100
elif worked_h > 12 and worked_h <= 16:
wages = (worked_h-8)*40+worked_h*100
elif worked_h > 16 and worked_h <= 20:
wages = (worked_h-8)*50+worked_h*100
else:
wages = (worked_h-8)*60+worked_h*100
print("Total Wages:", wages)

Output

Created by – Raj
IT PROFESSIONAL COMPUTER INSTITUTE

Question 6. Accept the name of the labourer and no. of hours worked.
Calculate and display the wages. The program should run for N number of
labourers as specified by the user.

Solution:
N = int(input("Enter Numbers of Laborers: "))
wages = int(input("Enter Wages per hour:"))
for i in range(N):
name = input("Enter name of laborer :")
hours = int(input("Enter Worked Hours:"))
Total_wages = wages*hours
print("labor name is",name, "and wages",Total_wages)

Output

Created by – Raj
IT PROFESSIONAL COMPUTER INSTITUTE

Question 7. Write a function that takes a string as parameter and returns a


string with every successive repetitive character replaced by? e.g. school may
become scho?l.

Solution
def char_replace(str):
result = ""
for i in str:
if i in result:
result = result + "?"
else:
result = result + i
return result
string = input("Enter a String : ")
print(char_replace(string))

Output

Created by – Raj
IT PROFESSIONAL COMPUTER INSTITUTE

Question 8. Write a program that takes in a sentence as input and displays


the number of words, number of capital letters, no. of small letters and
number of special symbols.

Solution
str = input("Enter a String:")
str = [Link]()
upper = lower = symbols = 0
word = [Link](" ")+1
for c in str:
if [Link]():
upper += 1
elif [Link]():
lower += 1
elif (not [Link]() and not [Link]()):
symbols += 1
print("Number of Word is ",word)
print("Number of Uppercase letter is ",upper)
print("Number of lowercase letter is ",lower)
print("Number of Special Symbols is ",symbols)

Output

Created by – Raj
IT PROFESSIONAL COMPUTER INSTITUTE

Question 9. Write a Python program that takes list of numbers as input


from the user and produces a cumulative list where each element in the list at
any position n is sum of all elements at positions upto n-1.

Solution
list1 = eval(input("Enter Your List :"))
sum = 0
result = []
for i in list1:
sum = sum + i
[Link](sum)
print("Cumulative list",result)

Output

Created by – Raj
IT PROFESSIONAL COMPUTER INSTITUTE

Question 10. Write a program which takes list of numbers as input and finds:
a) The largest number in the list
b) The smallest number in the list
c) Product of all the items in the list

Solution
list1 = eval(input("Enter Your List:"))
large = max(list1)
small = min(list1)
product = 1
for i in list1:
product = product*i
print("Largest Number in list is ",large)
print("Smallest Number in list is ",small)
print("Product of all Number in list is ",product)

Output

Created by – Raj

Common questions

Powered by AI

Yes, the logic used in the Python program for computing the exponential series can be adapted to calculate values of more complex series. The program employs loops and functions to dynamically compute terms involving powers and factorial, which are common operations in many mathematical series. By modifying the power or the terms in the loop, similar logic can handle more intricate series that may involve alternating signs or coefficients .

Using `math.factorial()` and `pow()` is preferred because they are optimized, tested for efficiency and correctness, and reduce the potential for human error associated with writing custom functions. These built-in functions are highly optimized at the C level, making them computationally superior. They also enhance code readability and one can leverage extended mathematical capabilities of Python's standard library .

The algorithm effectively uses Python's string methods to count occurrences of different character types with clear separation via conditional checks. Its effectiveness stems from relying on built-in functions that optimize performance and readability. However, its reliance on `strip()` may overlook necessary spaces, and mixing counting logic makes it less modular. Optimizing for edge cases like contractions or numbers might need additional handling .

The program determines if a number is an Armstrong number by calculating the sum of each of its digits raised to the power of the total number of digits. It uses a loop to iterate over each digit, computes its power, and accumulates the result. If this accumulated sum equals the original number, it confirms the number as an Armstrong number .

The program successfully executes cumulative summation by iterating through the list, maintaining a running total, and appending this total to a new list. This demonstrates effective list operations by utilizing append dynamically. One improvement could include directly altering the initial list rather than creating a new list, reducing memory usage. Additionally, utilizing list comprehensions or in-built functions like `itertools.accumulate()` could further optimize and condense the code .

Adapting the cumulative list method for operations beyond summation involves modifying the accumulator logic: instead of addition, apply a multiplication operation within the loop. For each element in the list, the running product would replace the running total, appending the cumulative product to the result list. This alteration follows the same principle, demonstrating adaptability to a range of aggregation operations, provided the elements align with the chosen operation .

Errors might arise when the current method incorrectly replaces non-consecutive repeats since it checks if a character is anywhere in the result string instead of consecutive repeats. This could lead to premature and incorrect replacement. To address this, the algorithm should use a stateful iteration keeping track of the last character without accumulating past results, or use a regular expression designed for consecutive duplicates .

Adapting the program to handle non-numeric data entails adding checks to separate numeric processing from string comparisons. Using Python’s type checking allows for operations on particular data types: numeric aggregation functions for numbers and lexicographical comparisons or concatenations for strings. Additionally, error handling can prevent operation mishaps when non-comparable types are encountered, ensuring robustness in diverse data environments .

The strength of using repeated addition for multiplication lies in its simplicity and minimal programming essentials, suitable for learning purposes. However, its limitations include inefficiency for large numbers due to its computational intensity, as it employs O(b) time complexity where b is the second operand. This method lacks the computational efficiency inherent in direct multiplication operations provided by most programming languages .

The method calculates wages by applying different rates for distinct hourly categories using conditional statements. It iterates through each tier of hours worked, incrementally adding the applicable rate. Potential optimization could involve precomputing constants for each range to avoid repeated calculations or using arrays to dynamically adjust wages as conditions change, reducing redundancy and improving clarity .

You might also like