I am trying to get into coding and this is kinda part of the assignments that i need to do to get into the classes.
In this task, you will implement a check using the if… else structure you learned earlier.You are required to create a program that uses this conditional.
At your school, the front gate is locked at night for safety. You often need to study late on campus. There is sometimes a night guard on duty who can let you in. You want to be able to check if you can access the school campus at a particular time.
The current hour of the day is given in the range 0, 1, 2 … 23 and the guard’s presence is indicated by with a True/False boolean.
If the hour is from 7 to 17, you do not need the guard to be there as the gate is open
If the hour is before 7 or after 17, the guard must be there to let you in
Using predefined variables for the hour of the day and whether the guard is present or not, write an if statement to print out whether you can get in.
Example start:
hour = 4
guard = True
Example output:
'You're in!'
Make use of the if statement structure to implement the program.
One of my ideas was:
Time = int(input("Time of getting in: "))
open = 7
closed = 17
if Time > open and Time < closed:
print("You can not enter")
cap O will solve
Time = int(input("Time of getting in: "))
Open = 7
closed = 17
if Time > Open and Time < closed:
print("You can not enter")
It's not too difficult, you can do a simple function like that :
def go_to_study(hour, start_day = 7, end_day = 17):
if (hour >= start_day and hour <= end_day):
return True
else:
return False
// on one line, uncomment if you want.
// return (hour >= start_day and hour <= end_day)
hour=int(input("Enter the Hour"))
if hour>=7 and hour<=17:
print("You can Go")
else:
print("You need Guard to let you in")
Related
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 1 year ago.
I am going to try to explain this the best I can. I have a task to make a pay phone price calculator based on day, duration, and time call started. I did two of the if statements and realized whenever I put in my answers all it does is print the result off the most recent if statement and does not really listen to what I want it to do. It is a bit hard to explain so I will just put my code, my input, and my result.
Code:
day = str(input('Enter the day the call started at: '))
start_time = float(input('Enter the time the call started at (hhmm): '))
duration = float(input('Enter the duration of the call (in minutes):'))
cost = duration
if (start_time >= 08.00 and start_time <= 18.00 and day == "Mon" or "Tue" or "Wed" or "Thr" or "Fri"):
cost = duration * 0.40
if (start_time < 08.00 and start_time > 18.00 and day == "Mon" or "Tue" or "Wed" or "Thr" or "Fri"):
cost = duration * 0.25
print('$' + str(cost))
My inputs:
1: Fri, 2350, 22. 2: Sund, 2350, 22.
My results:
1: $5.5. 2: $5.5.
As you can see it did not even do what is inside the print statement. It just gave me the result of the outcome of the previous if statement. I also tried removing the "and day ==" and what is after and all that did is make the first print statement work fine while the second does not work it just prints my original duration so I think I messed up bad.
When you're trying to connect multiple conditions using logical operators you have to compare each string separately.
I mean it needs to be like this
day == "Mon" or day == "Tue" or day == "Wed"
And so on...
I am still in the beginning stages of learning and obviously trying to shorten instances like this, where I have many if conditionals to go through. Just wondering how someone more experienced tackles this? I have tried with 'or' and 'and' operators, and I try to nest my statements where I see I can, but generally it still feels quite clumsy.
This bit of code was part of a date-validator using regex for How To Automate The Boring Stuff, I don't have a else statement as there is more conditionals in the full code. Is there a better way or am I over complicating it?
if month == 4 and day == 31:
print("Invalid date found in text")
return False
elif month == 6 and day == 31:
print("Invalid date found in text")
return False
elif month == 9 and day == 31:
print("Invalid date found in text")
return False
elif month == 11 and day == 31:
print("Invalid date found in text")
return False
As others said, you want to use a library to deal with dates. But for a case like yours, you could do this:
illegal_dates = [(4,31), (6,31), (9,31), (11,31)]
if (month, day) in illegal_dates:
print("Invalid date found in text")
return False
When you find yourself being repetitive, you can sometimes make an ad-hoc list of values and loop through them. In your case, we don't even need a for loop, we can just check if the tuple is in the list.
What about this?
import datetime
try :
datetime.datetime(int(year),int(month),int(day))
except ValueError :
print("Invalid date found in text")
return False
As others said, the DateTime library is the best way to check the correctness of date (as it handles various edge scenarios like Feb has 28 days, etc.), but if it is just about writing above piece with brevity, one can try following:
month_invalid = True if (month in [4,6,9,11]) else False
day_invalid = True if day==31 else False
if month_invalid or day_invalid:
return false
When you have a common expression in a sequence of if statements, you can often factor them out so it can be an outer expression controlling a block, for example:
if (day == 31) and (month in (4,6,9,11)):
print("Invalid date found in text")
return False
But for checking for ranges with obvious indexes, you would probably use (ignoring leapyear):
maxdays = [31,28,31,30,31,30,31,31,30,31,30,31]
if day > maxdays[month-1]:
print("Invalid date found in text")
return False
I am making a basic date converter and I need to update the the date every time the user enters an invalid date and is asked to input again. From this function below, I need both the object day and year returned.
def day_valid (month, dates, feb_day, month_days):
day = int(dates[2:4])
while month_days == 31 and day > 31:
print ("Invalid day input.")
print()
dates = input_date()
day = int(dates[2:4])
if month_days == 31 and day < 32:
break
while month_days == 30 and day > 30:
print ("Invalid day input.")
print()
dates = input_date()
day = int(dates[2:4])
if month_days == 30 and day < 31:
break
while month_days == feb_day and day > feb_day:
print ("Invalid day input.")
print()
dates = input_date()
day = int(dates[2:4])
if month_days == feb_day and day <= feb_day:
break
return day
When a user types in 00102002 in MMDDYYYY format, there is no month. So the user is prompted to enter again, entering 01102005. The code still displays the date as 10 January 2002 and not 2005 .
If any one needs clarification on the code, please ask!
My main function:
def main():
loop = "Y"
print()
print("Welcome to Date Converter!")
print()
while loop.upper () == "Y" :
dates = input_date()
year = int(dates[4:])
month = month_valid(dates)
feb_day = feb_days(year)
month_days = month_Days(month, feb_day)
day = day_valid(month, dates, feb_day, month_days)
month_str = month_names(month)
print()
print("The date is " + str(day) + " " + month_str + " " + str(year))
loop = str(input ("Do you want to re-run this program? Y/N: "))
main()
This sounds first of all like an XY Problem: someone wants to do X, and comes up with a solution requiring doing Y. They need help with Y, so request help to do Y. However, it turns out that Y is not an appropriate solution. By recognizing the XY Problem and asking how to do X instead, the person gets better help and more insight into X.
XY Problems also often look suspiciously like homework problems, since those are often of the form "write a program that does X, by doing Y".
It's OK to pose a question that you want to do X and tried to solve it using Y.
Anyway, that's why you're probably going to get low-effort answers. I'll make the effort :)
Anyway, going with the Y question :)
There is a readability practice that considers tuples harmful because you don't know what the purpose of the items in the tuple are. Consider instead creating an object that holds the things, each with its own attribute, and then return that.
Since you stated that you needed day and year returned:
class DayAndYear(object):
def __init__(self, day, year):
self.day = day
self.year = year
And that's how you do it without making a tuple, and it increases the readability of your program, such as it is.
Now, going with the unstated X question:
without knowing what month_valid does,
assuming feb_days returns the number of days in February of the given year,
assuming month_Days returns the number of days in the given month when it isn't February,
it seems that you want a function that will check if a string is a valid MMDDYYYY string.
def is_valid_date(s):
"""Checks if the given date is a valid MMDDYYYY string.
Args:
s (str): A date to check.
Returns:
bool: True if the date is valid, False otherwise.
"""
if len(s) != 8:
return False
try:
date = int(s[:2])
month = int(s[2:4])
year = int(s[4:])
except ValueError:
return False
if month < 1 and month > 12:
return False
if month == 2:
days_in_month = days_in_february(year)
else:
days_in_month = days_in_month(month)
return date >= 1 and date <= days_in_month
def print_date(s):
"""Prints the given MMDDYYYY date, assuming it has already been checked for validity.
Args:
s (str): A date to print.
"""
print("The date is {:d} {:s} {:d}.".format(
int(s[2:4]), month_name(int(s[:2])), int(s[4:])))
I'd like to highlight a few general techniques to make your programs read better:
We don't know X. A well-posed question is one with specifications for the input and output of the program.
I've used verbose, readable function names.
I've used function comments, complete with args, arg types, and return values so there's no guessing about what things do.
I've chosen a split between checking validity and printing an already valid string. You can combine them. You can also return a string rather than print the date, and return instead the sentinel value None if the date was not valid.
Don't compute any more than you have to. Note the early returns.
No doubt there are library functions that will do this, but I've assumed you don't want to use any library functions.
The short key concepts:
Readability: Programs should be almost as easy to read as prose in your native language.
Readability: Function names should be descriptive.
Readability: Comment your code.
Readability: Choose a consistent format for functions and stick with it ("month_Days" vs "feb_days")
Efficiency: Return early.
Testability: Specify well what your program does in terms of inputs and outputs, give examples of good and bad inputs.
Effectiveness: Use library functions.
Stackoverflowness: Consider if your problem is an XY problem.
I'm trying to create a program that asks if there was school that day and if so, subtracts that from the total, (86 days left as of 1-22-18). It works, but the program ends after one subtraction, so my question is, is there any way for it to continue running and update itself, or maybe ask the user again in 24 hours (no clue how)?
Python 3.4.4
Windows 10
import time
localtime = time.asctime(time.localtime(time.time()))
day = localtime[0:3]
check = 0
daysLeft = 87 #As of 1-22-18
daysOfTheWeek = ["Mon", "Tue", "Wed", "Thu", "Fri"]
yesPossibilities = ["yes", "y", "yeah"]
print ("Did you have school today?")
schoolToday = input().lower()
if schoolToday in yesPossibilities:
if day in daysOfTheWeek:
daysLeft -= 1
print ("There are", daysLeft, "days of school left!")
I think what you're really trying to do is save the results each time you run your script (Ex: If you run it today, it tells you there are 86 days left, if you run it tomorrow, it tells you there are 85 days left, etc). You probably don't want to run the script forever because if you turn your computer off, the script is terminated, which means you'll lose all of your results. I would save the output to a text file in the following manner:
print("There are" daysLeft, "days of school left!")
with open("EnterNameOfFileHere.txt",'w') as f:
print(daysLeft,file=f)
This will save the daysLeft variable in a text file, which you can access at the start of your program in the following manner:
check = 0
with open("EnterNameOfFileHere.txt") as f:
daysLeft = int(f.readline().strip())
daysOfTheWeek = ....
In summary, implementing this will allow you to save your results each time you run your script so that you can start from that value the next time you run the script.
You need an infinite loop and a sleep timer
import time
time.sleep(86400) #this will make the code sleep for 1 day = 86400 seconds
Next, put the sleep into the infinite loop
while True:
#get input
if input meets condition:
reduce day count by 1
print number of days left
time.sleep(86400)
if days left meets some threshold:
print "school over"
break
I'm learning on codeacademy and I was trying to print the following:
def trip_cost(p, d, m):
return rental_car_cost(d) + hotel_cost(d) + plane_ride_cost(p) + m
print "%s to %s for %s days with an extra %s dollars of spending mone" (trip_cost(p, d, m), p, d, m)
The program was telling me nothing was printing on the console, so I proceeded to delete the return line and it worked, so I was wondering if every time a function reaches a return it finishes, in that case in the following code I could've save the "and days < 7" ??
def rental_car_cost(days):
cost = days*40
if days >= 7:
cost -= 50
return cost
elif days >= 3 and days < 7:
cost -= 20
return cost
print cost
so I was wondering if every time a function reaches a return it finishes
Yes, it returns to what called it, hence the name.
in that case in the following code I could've save the and days < 7
Yes. Also you could have left it out because elif means "else if" so even if you didn't return that case would only have been considered if the previous if had been false so that it is considered else.
Generally we call the code and days < 7 here redundant. It's a good idea to remove redundant code. If redundancy makes something clearer then there's little harm leaving it in, but as a rule redundancy is more likely to confuse someone than to assist them, especially when you get more familiar with the language.
Yes, you can leave out and days < 7
Yes, return finishes the function and nothing else after that line is executed. Your example will work fine for the if-elif-else statements, as the appropriate condition will be checked and executed, returning the corresponding cost.
As a tip, you can use elif 3 <= days < 7 instead of elif days >= 3 and days < 7. Python is nice like that! In the way your conditions are structured, you can just have elif days >=3.