hrs = int(input("How many hours do you want? "))
if hrs >= 24:
day = hrs/24
hrs = hrs
if day == 1:
print(hrs, "hours is equal to", day, "day")
else:
if day >= 7:
wks = day / 7
if wks == 1:
print(day, "days is equal to", wks, "week")
else:
if wks >= 4:
mon = wks / 4
if mon == 1:
print(wks, "weeks is equal to", mon, "month")
else:
if hrs == 1:
print("You have 1 hour")
else:
print("You have", hrs, "hours")
For some reason when I try and use a number greater than 24 in hrs = int(input("How many hours would you like? ")) it stops completely not giving me what the problem is.
Here is what is shown in the console
I am using VisualStudio Code to make this
try using Floor division // instaed of normal devision /
hrs = int(input("How many hours do you want? "))
if hrs >= 24:
day = hrs//24
hrs = hrs
if day == 1:
print(hrs, "hours is equal to", day, "day")
else:
if day >= 7:
wks = day // 7
if wks == 1:
print(day, "days is equal to", wks, "week")
else:
if wks >= 4:
mon = wks // 4
if mon == 1:
print(wks, "weeks is equal to", mon, "month")
else:
if hrs == 1:
print("You have 1 hour")
else:
print("You have", hrs, "hours")
There's nothing wrong with Visual Studio Code based on the information that you've provided in your post.
The first mistake that I could see was this:
day = hrs/24
#...
if day == 1:
Here, day will be exactly equal to 1 only when hrs == 24. For hrs > 24, day will always be a floating point number unless hrs is storing a multiple of 24. Hence, the condition day == 1 will never be True.
This also applies to the else block underneath, where you've written wks = day / 7 and then if wks == 1:.
To resolve this, use the floor-division operator, //, which returns an integer value if both operands are integers.
The second thing that I noticed was that in line #4, you've written hrs = hrs. I believe you wanted to write hrs = hrs % 24, which assigns the remainder of hrs and 24 to hrs itself. So for hrs = 25, number of days = hrs // 24 = 1. And, number of hours = hrs % 24 = 25 % 24 = 1 (remainder when 25 is divided by 24).
Now, on to the main question: Why did the console show no output, and why did the code terminate without doing anything?
Well, notice that all the print statements in the code are under if or else conditions. If the conditions are never true, the print statements will not be executed at all!
Consider the case where hrs = 25. The first if block becomes True (if hrs >= 24) and hence gets executed. Note that the two print statements in the corresponding else block at lines 19 and 21 will not be executed now.
Since hrs / 24 is a floating point number (not an integer, and definitely not equal to 1), the statement day == 1 is never True and hence its if statement never gets executed. So, the print statement in the if day == 1: block, printf(hrs, "hours is equal to", day, "day"), also does not get executed.
Now, the control goes to the else block below. day >= 7 evaluates to False, since hrs/24 is actually 1.08333....
Corresponding to this if (if day >= 7:), there is no else! So, when this if condition turns out to be False, the program terminates without doing anything!
Related
I am attempting to define a function that asks the user which days of the week they are available. I need their input to be saved into a list for future use. I want to ensure they are entering the day of the week properly and that it is in the correct format. I have tried various ways but cannot seem to get it to work correctly.
Here is what I have so far:
daysWeek = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
def daysInput(message):
print(daysWeek)
z = False
while z == False:
i = list(input(message).strip().title().replace(",", " ").split(" "))
print(i)
varify = 0
for day in i:
for dow in daysWeek:
if day == dow:
varify += 1
else:
varify = 0
if varify == 0:
print("Invalid entry")
else:
z = True
return i
When varify += 1 is executed, and a next iteration executes, varify is set back to 0 even though the input day had matched with a correct day in the previous iteration. That means that unless you enter only the last day (Sun), the input will be rejected.
Secondly, if a day is found, and the next day from the input is checked, you'll destroy the previous result, by clearing varify again, even though a match will be found in a next iteration.
You need to implement the logic that for all inputs, some day of the week should match with it. You can do this a lot easier with the all function and the in operator:
daysWeek = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
def daysInput(message):
print(daysWeek)
while True:
inp = list(input(message).strip().title().replace(",", " ").split(" "))
print(inp)
if all(day in daysWeek for day in inp):
return inp
print("Invalid entry")
daysInput("Enter some days of the week: ")
On every even birthday a girl, named Lily, receives as a present $10.00. Every next even birthday she receives $10 more than the previous one (so on her 2nd birthday she gets 10, on her 4th she gets 20, 6th she gets 30 and etc.) This is the for loop:
age = int(input())
saved_birthday_money = 0
for i in range(1, age + 1):
if i % 2 == 0:
How would you code the rest of this problem (adding 10, then 20, then 30?)
The idea is to have a variable that starts at ten then has ten added to it each cycle. This ever-increasing amount is what gets added to her savings. The following pseudo-code should hopefully illustrate this:
set savings to zero
set gift to zero
for each alternate birthday:
add ten to gift
add gift to savings
You can change the number of iterations but:
Money = 0
Gift = 0
for X in range(100):
#She starts getting money at 2
X += 2
if X % 2 == 0:
Gift += 10
Money += Gift
print(Money)
This will plus 10 at the age of two, 20 at the age of 4 and so on
This program starts with 1 cent and doubles each day. However, I'm stuck on trying to find a way to convert the number of pennies into a dollar and cent amount. For example, converting 1020 pennies to $10.20.
I'm also attempting to make it so if user input is not a positive number, the user will be continously prompted until they enter a positive number. This isn't working, however.
I also feel I've messed up by using range, as I want to enter a set number of days, say 16 days, and when I enter 16, I receive the days 1-17, as range should be doing, and I'm not sure how to go about fixing that.
b = int(input("Input number of days "))
if b > 0:
print(b)
else:
b = int(input("Days must be positive "))
print("Day 1:","1")
days = 1
aIncrement = 2
penny = 1
for i in range(b):
pAmount = int(penny*2)
addAmount = int(2**aIncrement -1)
aIncrement +=1
days +=1
penny *= 2
print("Day " + str(days) + ":",pAmount)
Your question has multiple parts, which is not ideal for stackoverflow, but I will try to hit them all.
Fixing the numeric values to show dollars and cents.
As noted in comments to other answers, division can often run into snags due to floating point notation. But in this case, since all we really care about is the number of times 100 will go into the penny count and the remainder, we can probably safely get away with using divmod() which is included with Python and calculates the number of times a number is divisible in another number and the remainder in whole numbers.
For clarity, divmod() returns a tuple and in the sample below, I unpack the two values stored in the tuple and assign each individual value to one of two variables: dollars and cents.
dollars, cents = divmod(pAmount, 100) # unpack values (ints)
# from divmod() function
output = '$' + str(dollars) + '.' + str(cents) # create a string from
# each int
Fixing the range issue
The range() function produces a number and you can set it to start and end where you want, keeping in mind that the ending number must be set at one value higher than you want to go to... i.e. to get the numbers from one to ten, you must use a range of 1 to 11. In your code, you use i as a placeholder and you separately use days to keep track of the value of the current day. Since your user will tell you that they want b days, you would need to increment that value immediately. I suggest combining these to simplify things and potentially using slightly more self-documenting variable names. An additional note since this starts off on day one, we can remove some of the setup code that we were using to manually process day one before the loop started (more on that in a later section).
days = int(input("Input number of days "))
for day in range(1, days + 1):
# anywhere in your code, you can now refer to day
# and it will be able to tell you the current day
Continuous input
If we ask the user for an initial input, they can put in:
a negative number
a zero
a positive number
So our while loop should check for any condition that is not positive (i.e. days <= 0). If the first request is a positive number, then the while loop is effectively skipped entirely and the script continues, otherwise it keeps asking for additional inputs. Notice... I edited the string in the second input() function to show the user both the problem and to tell them what to do next.
days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input positive number of days: "))
Putting all this together, the code might look something like this:
I put the items above together AND cleaned up a few additional things.
days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input number of days: "))
# aIncrement = 2 # this line not needed
penny = 1
for day in range(1, days + 1):
pAmount = int(penny) # this line was cleaned up
# because we don't need to manually
# handle day one
dollars, cents = divmod(pAmount, 100)
output = '$' + str(dollars) + '.' + str(cents)
# addAmount = int(2**aIncrement -1) # this line not needed
# aIncrement +=1 # this line not needed
penny *= 2
print("Day " + str(day) + ":", output)
For the continuous prompting, you can use a while loop.
while True:
user_input = int(input("Enter the number"))
if user_input > 0:
break
else:
continue
Or alternatively:
user_input = int(input("Enter the number"))
while user_input <= 0:
user_input = int(input("Enter the number"))
For the range issue, you can add -1 to the parameter you're passing range.
for i in range(b - 1):
I am trying to use Python coding to create a paycheck when a user enters a said amount of hours. For under 40 hours a week of work, the standard pay is $9.25 an hour. Anything over 40 hours is rewarded a 150% of bonus(150% of 9.25 that is). I should also be able to take in hours entered in fractions and be able to print the paycheck as the output(which states the number of hours worked, pay per hour, bonus received, if any and the total salary)
So far, I have been able to successfully use the if else statement to get the final result but I do not know how to take in fractions and print the entire paycheck in the output. I am fairly new to Python and really like it a lot. Can someone please help me improvise my code and help me with fractions and printing the entire paycheck?
Here is my code so far.
hours = int(input('Please enter the number of hours...'))
if hours <= 40:
hourlyWage = hours*(9.25)
elif hours > 40:
hourlyWage = hours*(9.25*1.5)
print('Your salary is ${0}'.format(hourlyWage))
Thank you and help is much appreciated!
hours = int(input('Please enter the number of hours...'))
hourlyWage = 9.25
bonus = 0.5
bonusThreshold = 40
bonusHours = max(0, hours - bonusThreshold)
regularSalary = hourlyWage * hours
bonusSalary = bonusHours * hourlyWage * bonus
totalSalary = regularSalary + bonusSalary
print('Worked: {0} hours.'.format(hours))
print('Pay per hour: ${0}.'.format(hourlyWage))
print('Bonus received: ${0}'.format(bonusSalary))
print('Total salary: ${0}'.format(totalSalary))
hours = float(input('Please enter the number of hours...'))
hourlyWage = hours*(9.25)
hours = hours - 40
if hours > 0:
hourlyWage = hourlyWage + (hours*(9.25*1.5))
print('Your salary is ${0}'.format(hourlyWage))
hours = float(input('Please enter the number of hours...'))
pay = hours * 9.25 + max(hours-40,0)* (9.25*1.5-9.25)
print('Your salary is ${0}'.format(pay))
Your need to format your print statement. Here are some examples.
hours = 50
hourly_wage = 9.25
>>> print('Your salary is ${0:,.2f}'.format(hourly_wage * hours
+ max(0, hours - 40) * hourly_wage * 1.5))
Your salary is $601.25
Ask the user to enter payroll information for the company. Set up a loop that continues to ask for information until they enter “DONE”. For each employee ask three questions:
name (first & last)
hours worked this week (only allow 1 through 60)
hourly wage (only allow 6.00 through 20.00)
VALIDATE the hours worked and the hourly wage, and make sure a name is entered.
Calculate each employee’s pay, and write it out to a sequential file. Be sure to include file I/O error handling logic.
Include only the weekly pay
Weekly pay is calculated:
For (1-40 hours) it is hourly rate * hours worked
For (41-60 hours) it is (hours worked – 40) * (hourly rate * 1.5)
+ hourly rate * 40
After all the employees are entered, read in the sequential file into a list named PAY for the weekly pay of each employee. Sort the list. Now print the lowest, highest, and average weekly pay for the week.
I am having obvious problem with this code
while len(eName)>0:
eName=raw_input("\nPlease enter the employees' first and last name. ")
hWork=raw_input("How many hours did they work this week? ")
hoursWork=int(hWork)
if hoursWork < 1 or hoursWork > 60:
print "Employees' can't work less than 1 hour or more than 60 hours!"
else:
pRate=raw_input("What is their hourly rate? ")
payRate=int(pRate)
if payRate < 6 or payRate > 20:
print "Employees' wages can't be lower than $6.00 or greater than $20.00!"
if hoursWork <=40:
grossPay=hoursWork*payRate
else:
grossPay=((hoursWork-40)*(payRate*1.5))+(40*payRate)
lsthours.append(grossPay)
print grossPay
print lsthours
ePass=raw_input("Type DONE when finished with employees' information. ")
ePass.upper() == "DONE"
if ePass == "DONE":
break
else:
continue
There's several problems with this code:
The indentation is all over the place. For example, the while loop ends at that first if statement
The test for the while loop is almost certainly false (since eName isn't initialised), so the loop never enters
the code at ePass.upper() == "DONE" is trying to set the ePass variable, which means that test won't work. You need:
if ePass.upper() == "DONE":
break
try this:
lsthours = list()
eName = "start" # initialize to something to start the loop
while eName:
eName = raw_input("\nPlease enter the employees' first and last name. ")
if not eName:
break #loop will exit also when blank name is inserted
hWork = raw_input("How many hours did they work this week? ")
hoursWork = int(hWork)
if hoursWork < 1 or hoursWork > 60:
print "Employees' can't work less than 1 hour or more than 60 hours!"
continue #skip
pRate = raw_input("What is their hourly rate? ")
payRate = int(pRate)
if payRate < 6 or payRate > 20:
print "Employees' wages can't be lower than $6.00 or greater than $20.00!"
continue #skip
if hoursWork <= 40:
grossPay = hoursWork * payRate
else:
grossPay = ((hoursWork - 40) * (payRate * 1.5)) + (40 * payRate)
lsthours.append(grossPay)
print grossPay
print lsthours
ePass = raw_input("Type DONE when finished with employees' information. ")
if ePass.upper() == "DONE":
break
It still lacks exception checking but should work.
The "data error" checks should just short-circuit the main loop, it's simpler, but you can have a more involved code and put them into their own loop.
A few errors as has been pointed out:
In python, indentation decides the code blocks
while loop:
while logic_test:
# this is inside while loop
....
# this is outside while loop
Certain functions on string does not replace the string in place, they return another string via return value
upper:
>>> a = "done"
>>> a.upper()
'DONE'
>>> a
'done'
>>>
Always initialize your variables.
If you are using sequence methods, the variable should have been defined as sequence earlier.
>>> t.append('ll')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 't' is not defined
>>> t = []
>>> t.append('ll')
>>>
Make your scope explicit
lsthours = []
while len(eName)>0:
........
lsthours.append(grossPay)
Yu can do something as this:
grossPay = 0.0
lsthours = []
eName=raw_input("\nPlease enter the employees' first and last name (type 'PASS' to exit): ")
while eName.upper() != "PASS":
hWork=raw_input("How many hours did they work this week? ")
hoursWork=int(hWork)
if hoursWork < 1 or hoursWork > 60:
print "Employees' can't work less than 1 hour or more than 60 hours!"
else:
pRate=raw_input("What is their hourly rate? ")
payRate=int(pRate)
if payRate < 6 or payRate > 20:
print "Employees' wages can't be lower than $6.00 or greater than $20.00!"
if hoursWork <=40:
grossPay=hoursWork*payRate
else:
grossPay=((hoursWork-40)*(payRate*1.5))+(40*payRate)
lsthours.append(grossPay)
print grossPay
print lsthours
eName=raw_input("\nPlease enter the employees' first and last name. (type 'PASS' to exit): ")