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
Related
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!
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: ")
I am trying to create a function that accepts a users input and tries to figure out whether the year is a leap year and later also accept the users day of year (i.e. 355) and turns it into which day of the year it is (and output December, 10 2018). But for now I am not sure why it will not output whether the year is True or False. I tried to use the int parameter to change the user input from a string to a number but I am not sure if that is where I went wrong.
user_year = input('Enter year: ')
val = int(user_year)
def leap_year(val):
if val % 400 == 0:
print ("True")
if val % 100 == 0:
print ("False")
if val % 4 == 0:
print ("True")
else:
print ("False")
You're only defining the function leap_year but you're never calling it, below is an example where it actually gets called:
user_year = input('Enter year: ')
val = int(user_year)
def leap_year(val):
if val % 400 == 0:
print ("True")
if val % 100 == 0:
print ("False")
if val % 4 == 0:
print ("True")
else:
print ("False")
leap_year(val)
Also your indentation is a bit off, which causes it to not compile in the first place, but that could also be an error while copying to Stackoverflow.
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?
How do I pass the return statement from calculateTuitionIncrease into an array and then use that array when calculating the total cost?
Here's my code:
import math
def calculateTuitionIncrease(cost, increase, years):
#This function calculates the projected tuition increase for each year.
counter = 0
while counter <= years:
increasedCost = (cost)+(cost*increase)
return increasedCost
def calculateTotalCost(terms,tuition,creditHours,books,roomAndBoard,scholarships):
#This function will calculate the total cost of all your expenses.
totalBookCost = (books*terms)
totalTuitionCost = (tuition*creditHours)*(terms)
totalRoomAndBoard =(roomAndBoard*terms)
totalCost = (totalBookCost+totalTuitionCost+totalRoomAndBoard)-(scholarships)
return totalCost
def main():
#Variable declaration/initialization
years = 0
terms = 0
numberOfSchools = 0
tuitionCost1 = 0
tuitionCost2 = 0
tuitionCost3 = 0
tuitionCost = 0
bookCost = 0
roomAndBoard = 0
scholarships = 0
tuitionIncrease = 0
increasedCost = 0
creditHours = 0
overallCost = 0
#User inputs
years = int(input("Will you be going to school for 2, 4 or 6 years?"))
#If-statements for if user will be going to multiple schools.
if years == 4 or years == 6:
numberOfSchools = int(input("How many schools do you plan on attending during this time?"))
if numberOfSchools == 2:
tuitionCost1 = int(input("How much will you be paying per credit hour at the first school you'll be attending?"))
tuitionCost2 = int(input("How much will you be paying per credit hour at the second school you'll be attending?"))
tuitionCost = (tuitionCost1+tuitionCost2)/(2) #Finds average tuition between schools & assigns it to a variable
elif numberOfSchools == 3:
tuitionCost1 = int(input("How much will you be paying per credit hour at the first school you'll be attending?"))
tuitionCost2 = int(input("How much will you be paying per credit hour at the second school you'll be attending?"))
tuitionCost3 = int(input("How much will you be paying per credit hour at the third school you'll be attending?"))
tuitionCost = (tuitionCost1+tuitionCost2+tuitionCost3)/(3) #Finds average tuition cost between schools & assigns it to a variable
else:
tuitionCost = int(input("Please enter how much you will be paying per credit hour."))
terms = (years*2)
tuitionIncrease = float(input("Please enter the projected tuition increase per year in percentage form (ex. if increase is 7% enter .07)."))
creditHours = int(input("On average, how many credit hours will you be receiving per term?"))
roomAndBoard = int(input("Please enter what your price of room and board will be per term."))
bookCost = int(input("Please enter what your average book cost will be per term."))
scholarships = int(input("Please enter the total amount you will be recieving from grants and scholarships."))
#Calls function that calculates tuition increase per year
increasedCost = calculateTuitionIncrease(tuitionCost,tuitionIncrease,years)
#Calls function that calculates the total cost.
overallCost = calculateTotalCost(terms,tuitionCost,creditHours,bookCost,roomAndBoard,scholarships)
print ("Your total estimated college cost is", overallCost)
main()
For starters, it looks like calculateTuitionIncrease should be returning a list, because currently it's returning a single value and the loop is wrong (it's not advancing at all):
def calculateTuitionIncrease(cost, increase, years):
# This function calculates the projected tuition increase for each year.
counter = 0
answer = []
while counter <= years:
increasedCost = (cost)+(cost*increase)
answer.append(increasedCost)
counter += 1
return answer
As for the second part of the question, it's not clear how you're supposed to "use that array when calculating the total cost", but surely you must iterate over the list returned by calculateTuitionIncrease and do something with each element, for each year - you should know how to do this, it must be part of the problem description you received.
It looks like you're trying to return multiple values from the calculateTotalCost function. You could try using a tuple, which is like a mini-array that you can create by listing some values inside parentheses.
For instance, in your code you could replace
return totalCost
with
return (totalCost, totalBookCost, totalTuitionCost, totalRoomAndBoard)
The short answer is that you would make an empty list before the loop, and then append new items to it inside of your loop. After the loop you can either return the list or do something else with the list.
def calculateTuitionIncrease(cost, increase, years):
#This function calculates the projected tuition increase for each year.
counter = 0
# make an empty list
# before you start the loop
costsPerYear = []
# you should use 'less than' here (or start the counter at 1)
while counter < years:
increasedCost = (cost)+(cost*increase)
# append this cost to the end of the list
costPerYear.append(increasedCost)
# add one to the counter
counter = counter + 1
# once the loop is over, return the list
return costsPerYear
Then you could sum this quantity:
adjustedTuitions = calculateTuitionIncrease(cost, increase, years)
totalTuitionCost = sum(adjustedTuitions)
Alternatively, you can return the sum of those estimates
and use a for loop in place of the while loop.
def calculateTuitionIncrease(cost, increase, years):
#This function calculates the projected tuition increase for each year.
# make an empty list
# before you start the loop
costsPerYear = []
for year in range(years):
increasedCost = (cost)+(cost*increase)
# append this cost to the end of the list
costPerYear.append(increasedCost)
# return the sum of those costs
return sum(costsPerYear)
and use it like this:
totalTuitionCost = calculateTuitionIncrease(cost, increase, years)
Here's a tutorial on for loops and lists.
Also, you don't need to import the math module, because you're not using any of its special math functions.
You can use yield instead of return and use that function as iterator. So that's the example:
def calculateTuitionIncrease(cost, increase, years):
#This function calculates the projected tuition increase for each year.
counter = 0
while counter <= years:
counter += 1
yield (cost)+(cost*increase)
print(sum(calculateTuitionIncrease(1000, 10, 5))) # -> 66000
# the same but long way
sum = 0
for i in calculateTuitionIncrease(1000, 10, 5):
sum += i
print(sum) # -> 66000