try/except issue in Python

2024/11/15 13:46:06

I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input i.e., rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there i.e., (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below: enter image description here

Following is the code:

sh = input("Enter hours:")
sr = input("Enter Rate:")
try:fh = float(sh)fr = float(sr)
except:print('Error, please enter numeric input')quit()
print(fh, fr)
if fh > 40:reg = fr  * fhotp = (fh - 40.0) * (fr * 0.5)xp = reg + otp
else:xp = fh * fr
print("Pay:",xp)
Answer

Ideally, you put as less code as possible into a try-block and try to not repeat code, this makes it easier to debug/find errors in programs.
A more pythonic version of the 'questioning' would look like this:

# define a dictionary to save the user input
userInput = {'hours': None,'rate': None
}# The input lines are identical so you can just 'exchange' the question.
# Dynamically ask for user input and quit immedialy in case of non-float
for question in userInput.keys():try:userInput[question] = float(input(f"Enter {question}:"))except:print('Error, please enter numeric input')quit()# continue with the original code
fh, fr = userInput['hours'], userInput['rate']
if fh > 40:reg = fr  * fhotp = (fh - 40.0) * (fr * 0.5)xp = reg + otp
else:xp = fh * fr
print("Pay:", xp)
https://en.xdnf.cn/q/119308.html

Related Q&A

Counting the number of vowels in a string using for loops in Python

Python Code:sentence = input(Enter a string:) vowel = A,a,E,e,I,i,O,o,U,u Count = 0 for vowel in sentence:Count += 1 print(There are {} vowels in the string: \{}\.format(Count,sentence))I am trying to …

Sum the values of specific rows if the rows have same values in specific column

I have a data frame like this:a b c 12456 11 123.1 12678 19 345.67 13278 19 1235.345or in another format <table><tr><td>12456</td><td>11</td><td>1…

Plotting Interpolated 3D Data As A 2D Image using Matplotlib

The data set is made of a list dfList containing pandas DataFrames, each DataFrame consisting of the column Y and an identical index column. I am trying to plot all the DataFrames as a 2D plot with pix…

Plotting a flow duration curve for a range of several timeseries in Python

Flow duration curves are a common way in hydrology (and other fields) to visualize timeseries. They allow an easy assessment of the high and low values in a timeseries and how often certain values are …

HTML variable value is not changing in Flask

I have written this code in Flaskans = 999 @app.route(/, methods=[POST, GET]) def home():flag = 0global anssession["ans"] = 0if (request.method == "POST"):jsdata = request.form[data…

How to add two lists with the same amount of indexs in python

I am still new to coding so i apologize for the basic question. How do I add to elements of two seperate lists? listOne = [0, 1 , 7, 8] listTwo = [3, 4, 5, 6] listThree = []for i in listOne:listAdd = …

How to crawl thousands of pages using scrapy?

Im looking at crawling thousands of pages and need a solution. Every site has its own html code - they are all unique sites. No clean datafeed or API is available. Im hoping to load the captured data i…

Object Transmission in Python using Pickle [duplicate]

This question already has answers here:Send and receive objects through sockets in Python(3 answers)Closed last year.I have the following class, a Point objectclass Point:def __init__(self):passdef __i…

Google App Engine: Modifying 1000 entities

I have about 1000 user account entities like this:class UserAccount(ndb.Model):email = ndb.StringProperty()Some of these email values contain uppercase letters like [email protected]. I want to select …

more efficient method of dealing with large numbers in Python? [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…