import datetime
now = datetime.datetime.now()
if now.day == Tuesday :
print ('yes it is tuesday')
else :
print ('no')
I try this but I get error in python :
Traceback (most recent call last):
File "C:/Users/Yarlagadda/Desktop/test2.py", line 4, in <module>
if now.day == Tuesday :
NameError: name 'Tuesday' is not defined
>>>
I would like to know mistake
You have two problems with your code.
The first is that the error code is telling you that Tuesday doesn't exist as a variable because you are not making it a string. So change it to 'Tuesday' with the ' around it.
Second is that now.day is going to return a number and not a string day.
Edit: Thanks to #Tomerikoo for pointing out that this returns the day of the month and not the day of the week. Change this to now.weekday() to get the day of the week.
To fix this, you can either compare the number 1 in the if statement instead of the word Tuesday or you can map the numbers to the words. Mapping the numbers to the words is the preferred method since it is easier to maintain and less messy.
Note: The days of the week in now.weekday() will be numbered 0-6 with 0 being Monday and 6 being Sunday.
I'm using a tuple here, but you could use a list, or if you really feel inclined, a dictionary. But a dict is overkill and a list comes with memory overhead that's not needed.
Mapping:
week_days = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
Final Code
import datetime
week_days = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
now = datetime.datetime.now()
day = week_days[now.weekday()] # Note the change to now.weekday()
if day == 'Tuesday' :
print ('yes it is tuesday')
else :
print ('no')
The error is just in if condition that the Tuesday is not used as string. Replace Tuesday by 'Tuesday' and your code is working fine.
For enhancement you may also use list or tuple to keep the weekdays.
import datetime
now = datetime.datetime.now()
if now.day == 'Tuesday':
print ('yes it is tuesday')
else:
print ('no')
Related
Okay so I am not exactly a rookie but a beginner in python, and I have been trying to create the following program by using functions, however, I don't really know how functions work and it just seems a little tough for the moment. Here is the question:
The length of a month varies from 28 to 31 days. In this exercise you will create
a program that reads the name of a month from the user as a string. Then your
program should display the number of days in that month. Display “28 or 29 days”
for February so that leap years are addressed.
And here is my simple solution:
name = input('What month is it? ')
thirty_days = ['April','June','September','November']
thirty_one_days = ['January','March','July','August','October','December']
feb = ['February']
if name in thirty_days:
print('Number of days: 30')
elif name in thirty_one_days:
print('Number of days: 31')
elif name in feb:
print('Number of days: 28 or 29')
Any suggestions are appreciated :) Cheers!
You can put the code in a function that returns the length instead of printing it. Then call the function and print its result.
def month_length(name):
thirty_days = ['April','June','September','November']
thirty_one_days = ['January','March','July','August','October','December']
feb = ['February']
if name in thirty_days:
return 30
elif name in thirty_one_days:
return 31
elif name in feb:
return '28 or 29'
name = input('What month is it?')
print('Number of days:', month_length(name))
You could leverage some date utils:
from datetime import datetime
from calendar import monthrange
def length(name):
d = datetime.strptime(name, "%B") # parse month by full name
l = monthrange(datetime.now().year, d.month)[1]
# may not be needed as you dynamically get the correct value for current year
# if l == 28:
# return "28 or 29"
return l
print('Number of days:', length(input()))
Some docs:
calendar.monthrange
datetime.strptime
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...
This is my first time programming in Python and I am not too sure what I am doing wrong.
I am simply trying to print what the hour (time) is in words however I get the error "SyntaxError: invalid token" when I set the if statement to check
if current_hour == 05:
and when I change the 05 to 5 the If Statement simply does nothing.
This is my code:
import time
current_hour = time.strftime("%I")
print(current_hour)
if current_hour == 05:
print("Five")
Thank you!
current_hour is a string. For this to work you need the following:
import time
current_hour = time.strftime("%I")
print(current_hour)
if current_hour == '05':
print("Five")
or this:
import time
current_hour = int(time.strftime("%I"))
print(current_hour)
if current_hour == 5:
print("Five")
time.strftime returns a string like described in doc:
Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument.
To compare in an if-statement you need to have the same datatype, so either convert the result to int or compare with a string like "05"
If you are not sure, which datatype is returned, you can check by using the type() method:
>>> print(type(current_hour))
<class 'str'>
i have problem with this script.
named_tuple = time.localtime()
time_string = time.strftime("%H:%M", named_tuple)
if time_string > "7:00" or time_string < "18:00":
print("day")
else:
print("evening")
how can I check day or evening please?
You can retrieve the hour from what time.localtime() returns:
>>> time.localtime()
time.struct_time(tm_year=2019, tm_mon=6, tm_mday=12, tm_hour=19, tm_min=..., tm_sec=..., tm_wday=2, tm_yday=163, tm_isdst=...)
>>> _.tm_hour
19
Then you just compare tm_hour with the values you want:
Time = time.localtime()
if 7 <= Time.tm_hour <= 18:
print('Yeah!')
If you need to be more precise, grab the minutes:
if (6, 45) <= (Time.tm_hour, Time.tm_min) <= (18, 5):
...
You cannot use your time_string to check if it's greater than "7:00" or smaller than "18:00", because it ranks strings according to alphanumerical order.
For example, it's now 12:32. The first character of my time_string would be "1", which is smaller than "7", so it would print "evening" even if it's noon.
Also, you want to check if it's later than 7:00 AND earlier than 18:00.
Maybe you can add more options too, because any time earlier than 7:00 would print "evening".
As for how to do it, see ForceBru's answer, which keeps it super simple.
Right now the first statement will always match.
Your time will ALWAYS be greater than 7:00 OR less than 18:00.
Change or to and and it should work.
EDIT:
I had just glanced at the if statement briefly and noticed that it was broken. Fundamentally having the or in there will prevent the else statement from ever being executed. However, looking at it again, there are more errors going on than just the or issue.
Like #ForceBru mentions, you'll want to get the hour so that you're not doing a string comparison.
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.