0% found this document useful (0 votes)
61 views

My Python Codes

The document contains solutions to 10 Python coding exercises. The solutions demonstrate how to: 1. Prompt a user for input and use conditionals and math operators to calculate pay based on hours worked and hourly rate. 2. Take user input, convert it to a float, and use conditionals to assign a letter grade based on a score between 0-1. 3. Define a function to calculate pay based on hours and rate, call the function with user input, and return/print the result.

Uploaded by

Esmael Uta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

My Python Codes

The document contains solutions to 10 Python coding exercises. The solutions demonstrate how to: 1. Prompt a user for input and use conditionals and math operators to calculate pay based on hours worked and hourly rate. 2. Take user input, convert it to a float, and use conditionals to assign a letter grade based on a score between 0-1. 3. Define a function to calculate pay based on hours and rate, call the function with user input, and return/print the result.

Uploaded by

Esmael Uta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

My_Python_Codes

3.1 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly
rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate
of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to
convert the string to a number. Do not worry about error checking the user input - assume the user types numbers
properly.

Solution:

hrs = input("Enter hour:")


rate = input("Enter rate:")
if int(hrs) <= 40:
pay = int(hrs) * float(rate)
print(pay)
else:
pay = (40 * float(rate)) + ((int(hrs) - 40) * (1.5 * float(rate)))
print(pay)

3.3 Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score
is between 0.0 and 1.0, print a grade using the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85.
Solution:
score = input("Enter Score: ")
x = float(score)
if x >= 0.9 and x < 1.0:
print("A")
elif x >= 0.8 and x < 0.9:
print("B")
elif x >= 0.7 and x < 0.8:
print("C")
elif x >= 0.6 and x < 0.7:
print("D")
elif x > 0.0 and x < 0.6:
print("F")
else:
print("error")

4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay should be
the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours. Put
the logic to do the computation of pay in a function called computepay() and use the function to do the computation.
The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be
498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error
checking the user input unless you want to - you can assume the user types numbers properly. Do not name your
variable sum or use the sum() function.
Solution:
def computepay(hours, rate):
if hours <= 40:
pay = hours * rate
else:
pay = 40 * rate + (hours - 40) * rate * 1.5
return pay

hours = float(input("Enter hours: "))


rate = float(input("Enter rate per hour: "))

gross_pay = computepay(hours, rate)


print("Pay", gross_pay)

5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is
entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch
it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match
the output below.
Solution:
largest = None
smallest = None
while True:
num = input("Enter an integer number (or 'done' to exit): ")
if num == 'done':
break
try:
num = int(num)
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
except ValueError:
print("Invalid input")
if largest is not None and smallest is not None:
print("Maximum is", largest)
print("Minimum is", smallest)

6.5 Write code using find() and string slicing (see section 6.10) to extract the number at the end of
the line below. Convert the extracted value to a floating point number and print it out.

text = "X-DSPAM-Confidence: 0.8475"

# Find the position of the colon in the text


colon_index = text.find(':')

# Extract the numeric portion of the text using slicing


X = text[colon_index + 1:].strip()

# Convert the extracted value to a floating-point number


Y = float(X)

# Print the result


print(Y)

7.1 Write a program that prompts for a file name, then opens that file and reads through the file, and
print the contents of the file in upper case. Use the file words.txt to produce the output below.
You can download the sample data at http://www.py4e.com/code3/words.txt
# Use words.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
for x in fh:
y = x.rstrip()
print(y.upper())

8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words
using the split() method. The program should build a list of words. For each word on each line check
to see if the word is already in the list and if not append it to the list. When the program completes,
sort and print the resulting words in python sort() order as shown in the desired output.
fname = input("Enter file name: ")
fh = open(fname)
lines = fh.readlines()
lst = []
for line in lines:
#words = line.rstrip()
word = line.split()
for W in word:
if W not in lst:
lst.append(W)
lst.sort()
print(lst)

9.4 Write a program to read through the mbox-short.txt and figure out who has sent the greatest
number of mail messages. The program looks for 'From ' lines and takes the second word of those
lines as the person who sent the mail. The program creates a Python dictionary that maps the
sender's mail address to a count of the number of times they appear in the file. After the dictionary is
produced, the program reads through the dictionary using a maximum loop to find the most prolific
committer.
"name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)""""
# Initialize an empty dictionary to store sender counts
sender_counts = {}

# Open the mbox-short.txt file for reading


try:
file_name = input("Enter the file name: ")
file_handle = open(file_name, 'r')
except:
print("File not found:", file_name)
quit()

# Loop through each line in the file


for line in file_handle:
# Check if the line starts with 'From ' (with a space)
if line.startswith('From '):
# Split the line into words
words = line.split()
# Extract the sender's email address (the second word)
sender = words[1]
# Update the sender's count in the dictionary
sender_counts[sender] = sender_counts.get(sender, 0) + 1

# Close the file


file_handle.close()

# Find the most prolific committer using a maximum loop


most_prolific_sender = None
max_count = None

for sender, count in sender_counts.items():


if max_count is None or count > max_count:
most_prolific_sender = sender
max_count = count

# Print the results


print(most_prolific_sender, max_count)

10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the
day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and
then splitting the string a second time using a colon.
From [email protected] Sat Jan 5 09:14:16 2008
Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown
below.

name = input("Enter file:")


if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)

# Create a dictionary to store the distribution by hour


hour_counts = {}

for line in handle:


if line.startswith("From "):
words = line.split()
if len(words) >= 6:
time = words[5]
hour = time.split(":")[0]
hour_counts[hour] = hour_counts.get(hour, 0) + 1

# Convert the dictionary to a list of tuples and sort it by hour


sorted_counts = sorted(hour_counts.items())

# Print the sorted counts


for hour, count in sorted_counts:
print(f"{hour} {count}")

You might also like