[Go to site: main page, start]

0% found this document useful (0 votes)
80 views2 pages

Python Programs for Common Tasks

Uploaded by

ehtsalman
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)
80 views2 pages

Python Programs for Common Tasks

Uploaded by

ehtsalman
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

1.

Student List Sorter


# Program to input a list of student names and display them sorted names = input("Enter student
names separated by commas: ").split(',') names = [[Link]() for name in names]
[Link](key=lambda x: [Link]()) print("Sorted Names:", names)
Sample Run: Input: John, Alice, bob Output: Sorted Names: ['Alice', 'bob', 'John']

2. Find Word in Sentence


# Program to find a word in a given sentence sentence = input("Enter a sentence: ") word =
input("Enter word to search: ") if [Link]() in [Link]().split(): print(f"'{word}' found in the
sentence") else: print(f"'{word}' not found")
Sample Run: Input: sentence='I like robotics', word='robotics' Output: 'robotics' found in the
sentence

3. City-Data Dictionary
# Program to store and query city temperature data city_data = {"Delhi": 30, "Mumbai": 28,
"Kolkata": 29} city = input("Enter city name: ") if city in city_data: print("Average temperature:",
city_data[city], "°C") else: print("City not found")
Sample Run: Input: city='Delhi' Output: Average temperature: 30 °C

4. Electricity Bill Calculator


# Program to calculate electricity bill prev = int(input("Enter previous meter reading: ")) curr =
int(input("Enter current meter reading: ")) units = curr - prev bill = 0 if units <= 100: bill = units * 5 elif
units <= 300: bill = 100*5 + (units-100)*7 else: bill = 100*5 + 200*7 + (units-300)*10 print("Total Bill:
Rs.", bill)
Sample Run: Input: prev=1200, curr=1350 Output: Total Bill: Rs. 850

5. Bonus Calculator
# Program to calculate bonus based on years of service salary = float(input("Enter salary: ")) years
= int(input("Enter years of service: ")) if years > 5: bonus = salary * 0.05 else: bonus = 0
print("Bonus Amount: Rs.", bonus)
Sample Run: Input: salary=50000, years=6 Output: Bonus Amount: Rs. 2500.0

6. NumPy Array Operations


import numpy as np arr = [Link]([1,2,3,4,5]) print("Array:", arr) print("Mean:", [Link](arr))
print("Reshaped (5x1):", [Link](5,1))
Sample Run: Output: Array: [1 2 3 4 5] Mean: 3.0 Reshaped: [[1],[2],[3],[4],[5]]

7. Plot Data using Matplotlib


import [Link] as plt x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] [Link](x, y, marker='o')
[Link]('X values') [Link]('Y values') [Link]('Simple Line Graph') [Link]()
Sample Run: Displays a line graph of x vs y.
8. Predict Temperature Trend
from sklearn.linear_model import LinearRegression import numpy as np # Example data: year vs
temperature X = [Link]([[2000],[2005],[2010],[2015],[2020]]) y = [Link]([30, 31, 32, 33, 34])
model = LinearRegression().fit(X, y) next_year = [Link]([[2025]]) pred = [Link](next_year)
print("Predicted temperature in 2025:", pred[0])
Sample Run: Output: Predicted temperature in 2025: 35.0 (approx)

9. Text Processing
# Count words and check palindrome text = input("Enter text: ") print("Word Count:", len([Link]()))
if [Link]() == [Link]()[::-1]: print("It is a palindrome") else: print("Not a palindrome")
Sample Run: Input: 'madam' Output: Word Count: 1, It is a palindrome

10. Dice Roll Simulation


import random print("Rolling dice...") print("You got:", [Link](1,6))
Sample Run: Output: You got: 4

Common questions

Powered by AI

The electricity bill calculator differentiates unit cost based on usage: Rs. 5 for the first 100 units, Rs. 7 for the next 200 units, and Rs. 10 for any units beyond 300. This tiered pricing structure likely mimics real-world billing systems, aiming to incentivize lower energy consumption by charging higher rates for more extensive use. It incrementally impacts the final bill, making it proportionate to the consumer's usage and discouraging wastage .

The bonus calculator assesses eligibility by checking if the years of service exceed five (if years > 5). If eligible, the program calculates the bonus as 5% of the salary (bonus = salary * 0.05). This approach allows the program to reward long-term employees while utilizing a simple conditional statement for determination and calculation .

The student list sorter uses the method names.sort(key=lambda x: x.lower()), which converts each name to lowercase before sorting. This approach ensures that the sorting is case-insensitive, treating names like 'Alice' and 'alice' equally despite the difference in case. This is effective because it maintains a logical alphabetical order for human-readable data, irrespective of variations in capitalization .

Graphical data representation using Matplotlib is often preferred because it provides an immediate visual summary of trends or patterns, which can be more intuitive and quicker to interpret than textual data descriptions. Features like markers ('o'), labeled axes ('xlabel', 'ylabel'), and titles ('title') enhance the effectiveness by providing clear, context-rich plots that communicate the data's story effectively, aiding in decision-making processes .

The program compares the lowercase version of the text with its reverse to determine if it is a palindrome (i.e., text.lower() == text.lower()[::-1]). This approach is significant as it allows checking palindromicity in a case-insensitive manner, ensuring that variations in letter case do not affect the result. It effectively handles simple palindrome checks by focusing on the sequence of characters .

The word search program identifies if a specified word appears in a given sentence by converting both the word and sentence to lowercase before searching (if word.lower() in sentence.lower().split()). The case-insensitive search improves usability by ensuring that users can find words without worrying about the original capitalization, providing a more intuitive and error-tolerant search experience .

NumPy array operations facilitate efficient data manipulation through vectorized operations like calculating the mean and reshaping. The reshaping operation (arr.reshape(5,1)) is important as it changes the array's dimensions without altering its data, allowing it to fit into various mathematical contexts or model requirements more effectively. This flexibility is crucial for aligning data with specific algorithmic needs or addressing formatting constraints .

The City-Data Dictionary program checks for the presence of a city by querying whether the city name exists as a key in the city_data dictionary using an if statement (if city in city_data). If the city is found, it prints the city's average temperature in degrees Celsius. This mechanism provides a straightforward way to retrieve predefined city climate information .

The dice roll simulation program uses the random.randint(1,6) function to simulate a roll by generating a pseudo-random integer between 1 and 6, inclusive. This randomness is crucial in programming as it underlies many applications, from gaming to cryptographic protocols, providing unpredictability and variation in outcomes that mirror real-world processes .

The temperature trend prediction program uses LinearRegression from sklearn to fit a line to a dataset of historical temperatures over time (year vs temperature). This method captures the linear relationship between time and temperature, enabling the prediction of future temperatures by extending the observed trend. Linear regression is appropriate here due to its simplicity and effectiveness in modeling linear trends, providing a foundation for more complex prediction models .

You might also like