python check user input is day of the week - python

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: ")

Related

Doubling amount per day, need to convert number of pennies to dollars + cents

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):

Code not checking values in list?

This program I am trying to build needs to check if the user's input corresponds to values in a list. Here is the code I have:
def find_val(val, seq):
for ele in seq:
if val == ele:
return True
return False
def get_input(possible_vals, day_or_time_string):
if day_or_time_string == "day":
answer = input("What day would you like your appointment? ")
else:
answer = input("What time would you like your appointment? ")
answer = answer.strip()
valid_entry = find_val(answer, possible_vals)
if valid_entry == True:
count = 0
while False:
second_answer = input("Invalid entry. Please enter a valid day: ")
count = count + 1
if count == 3:
print("This is getting silly - still not a valid entry")
if second_answer in possible_vals:
return second_answer
else:
return answer
day_list = ["Monday", "Tuesday", "Wednesday"]
res = get_input( day_list, "day" )
print("The funtion returned", res)
This is the type of output I should be getting:
What day would you like your appointment? saturday
Invaild entry. Please enter a valid day: Monday
The funtion returned Monday
However, it seems that no matter what I input, the function returns it, and doesn't check if the input matches a string in the list:
What day would you like your appointment? akw
The function returned akw
What is wrong with my code that isn't allowing the user's input to be checked whether or not it is in the list day_list?
First
valid_entry = find_val(answer, possible_vals)
if valid_entry == True:
can be simplified to
if answer in possible_vals:
(your find_val function is totally unnecessary)
Then your problem is that
while False:
...
simply never executes... Did you mean while True? If so You'll need to somehow break out this (now) infinite loop using a break statement for example.
And finally as A.G. suggests, you explicitly tell your program to return answer when it's not "valid" so why do you expect otherwise?

Creating a List from User input {with Unlimited User Input}

I'm trying to create a function definition that asks the user to enter a int or float value to be added to an empty list, but continues to ask the user for input until the user types in -1 or so (<0).
This is what I have so far, but all it does is take the user's input and replicates it 5 times [range(5)] in the new list, and doesn't allow the user to enter anymore values....
I'm very stuck even though I feel it should be pretty easy:
def main():
salesList = []
salesValue = float(input('Please enter total sales in your department: '))
while salesValue < 0:
salesValue = float(input('Please enter a value greater than or equal to zero: '))
if salesValue == -1:
break
else:
for values in range(5):
salesList.append(salesValue)
print(salesList)
main()
Any guidance will be greatly appreciated, as I am new to programming.
:::The easy solution:::
def makeList():
salesList = []
while True:
salesValue = float(input('Please enter total sales in your department: '))
if salesValue == -1:
break
salesList.append(salesValue)
return salesList
You want
while salesValue > 0:
instead of
while salesValue < 0:
As you have it written now, the user inputs a value greater than 0, which automatically kicks it into the else block. You will be able to remove the
if salesValue == -1:
break
as well.
# here you are saying, for 5 iterations do the following
for values in range(5):
# append the single float value salesValue to salesList
# naturally this will happen 5 times
salesList.append(salesValue)
So it makes total sense that you end up with a list containing
the salesValue five times over.
Think about this:
while True: # will loop until a break
salesValue = float(input('Please enter a value greater than or equal to zero (-1 to end): '))
if salesValue < 0:
break
else:
salesList.append(salesValue)
Your current code has a mistake. Basically, when the flow finally reaches the for statement, the value of salesValue does not change, so the program appends the same value 5 times. Try this instead:
def main():
salesList = []
salesValue = float(input())
while salesValue < 0:
salesvalue = float(input())
if salesValue == -1:
break
for values in range (5):
salesList.append(salesValue)
salesValue = float(input("yourmessage"))
print salesList
main()

NameErrors and functions in python

I'm constantly getting a NameError Although I already defined a term, The problem is with "day" on line 28.
def today():
day = input("What day is it?")
if "sunday" in day:
day = 0
elif "monday" in day:
day = 1
elif "tuesday" in day:
day = 2
elif "wednesday" in day:
day = 3
elif "thursday" in day:
day = 4
elif "friday" in day:
day = 5
elif "saturday" in day:
day = 6
else:
today()
today()
days_on_vacation = int(input("How many days will you be on vacation? "))
days_to_add_to_day = days_on_vacation % 7
day += days_to_add_to_day
I already gave day a value in the function today() right? Why am I being told it is not defined?
Names you assign to in a function are locals; they are not visible outside of the function.
The best way to share that result is to return the value from the function, so that you can assign it to a variable as a result of the call:
def today():
# ...
return day
and
result = today()
The result variable then holds the value the function returned. You are free to use the name day there too but that's then a separate variable from the one inside the function.
You did complicate matters here by using a recursive function call; you then also need to make sure you pass on the result of the recursive calls back along the chain:
def today():
# ...
else:
return today()
return day
However, it is better not to rely on recursion here; a simple enless loop would do a better; returning from the function would automatically end the loop:
def today():
while True:
day = input('...')
# ...
else:
# not valid input, restart the loop
continue
# input was valid, return the result
return day

Python error calculating program

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): ")

Categories

Resources