making an input into a variable in python - python

I am very new to python and need some help, I am trying to make a simple if/else script.
my previous version worked as it should and I have have to make the only change of a user entering a variable rather than a pre-determined variable. But I get a syntax error on the final line, can anybody show me where I am going wrong.
my code is
hour = input('enter an hour')
if hour >= 0 and hour < 12:
clock = hour, 'pm' # assigning the variable here as necessary
elif hour >= 12 and hour < 23:
clock = hour, 'pm' # assigning the variable here as necessary
else:
clock = 'That is not a time on the clock.'
print(clock)
thanks in advance for your help.

Multiple problems here:
In Python indentation (the spaces from a line or tabs if you wish) are important to distinguish different scopes of the code like functions, if statements etc. Your first line has such invalid indentation.
input('enter an hour') This function reads an input from the user and returns it as a string, regardless if you provide a numeric value. You need to use int() to convert it into an actual numeric value, so that you can then do range checks like "if is greater than 0 and less than 10" for example. Obviously, if you don't convert it to integer and you are working with strings you cannot do such range checks as the value is not treated as a numeric value.
Here is a working copy:
hour = int(input('Enter an hour: '))
if hour >= 0 and hour < 12:
clock = "{}am".format(hour)
elif hour >= 12 and hour < 23:
clock = "{}pm".format(hour)
else:
clock = 'That is not a time on the clock.'
print(clock)

There are 3 errors:
Your first line should not be indented.
Convert your input to numeric type, e.g. float or int.
Hours between 0 and 12 should be "am" rather than "pm".
This will work:
hour = float(input('enter an hour'))
if hour >= 0 and hour < 12:
clock = hour, 'am' # assigning the variable here as necessary
elif hour >= 12 and hour < 23:
clock = hour, 'pm' # assigning the variable here as necessary
else:
clock = 'That is not a time on the clock.'
print(clock)

The error is IndentationError: unexpected indent This means you write the line of code indented. that's incorrect. To solve it remove the spaces before first line.
You also have to specify the type of input.
hour = int(input('enter an hour'))

Related

Returning dates in different format in python

I have made a function in the format: day/month/year. I would like to make another function that asks the user for example: "When do you want to come?" and depending on what month the user say I want to print out a answer.
The problem: I don't know how to make the function that asks the user for the format: day/month/year without limit the years, I would like the user to enter any year and still be able to get the same answers as another any year (but different month).
enter code here
import datetime
def dateformat(date):
return datetime.datetime.strptime(datumet, "%d/%m/%Y")
def ask_user():
winter = dateformat('1/1/2020') <= dateformat('31/3/2020')
spring = dateformat('1/4/2020') <= dateformat('31/5/2021')
summer = dateformat('1/6/2020') <= dateformat('31/9/2021')
autumn = dateformat('1/10/2020') <= dateformat('31/12/2021')
a = dateformat(input("When do you want to come"))
if a == winter:
print("Hi")
if a == spring:
print("bye")
if a == summer:
print("ok")
if a == autumn:
print("no")
My question: How can I make this code work for any year? I would like to be able to type any year but inside the month and get the same output. If I only return %d/%m in the dateformat-function the user will not be able to type: day/month/year. Is there maybe a better way of returning the format?
I don't think your code does what you expect it to do. For one, 31/9/2021 is not an actual date so dateformat would throw an error. Second, dateformat('1/1/2020') <= dateformat('31/3/2020') checks if the first date is less than or equal to the second, so winter, spring, etc. are booleans (and all True). With a == winter, you're comparing a date to a boolean, so they'll never be equal and you won't get any output.
What you actually want to do is read in the date, and see if its month attribute is between certain limits, because the value of a.year doesn't affect the season. So:
datumet = input("When do you want to come? ")
a = datetime.datetime.strptime(datumet, "%d/%m/%Y")
if a.month <= 3:
print("Hi, you're coming in winter")
elif a.month <= 5:
print("Spring")
elif a.month <= 9:
print("Summer")
else:
print("Autumn")
The same applies when your ranges don't end at the end of the year. For example, if winter lasted the start of November through the end of February,
if a.month >= 11 or a.month <= 2:
print("Hi, you're coming in winter")
elif a.month <= 5:
print("Spring")
elif a.month <= 9:
print("Summer")
else:
print("Autumn")

Creating a sample timer and am greeted by a TypeError

I've been working on a project for around five minutes, and I just got an error:
TypeError: 'str' object is not callable.
Can anyone help me see my error?
from win10toast import ToastNotifier as tst
import time
#timer with notifications
toaster = tst()
#the below input shows how long the timer will last
span_seconds = input('How many seconds will your timer span through? ')
#loops the time until the seconds are up
i = 0
while i < span_seconds():
time.sleep(1)
span_seconds-1
#determines whether the timer is done
if i == span_seconds:
toaster.show_toast('Timer is up!')
span_seconds is a string, as returned from input. You cannot call a string. Nor can you call an int. You don't want to be calling it anyway. You want simply to reference the variable. You can omit the () to do that.
Also, your line span_seconds - 1 doesn't do anything. I'm guessing you're going for something along the lines of span_seconds = span_seconds - 1 (also written as span_seconds -= 1). That line wouldn't accomplish what you're aiming to do, even if written properly, because span_seconds is a string, not an int.
If you change
while i < span_seconds():
span_seconds-1
to
while i < span_seconds:
span_seconds -= 1
as I mention above, and also change
span_seconds = input('How many seconds will your timer span through? ')
to
span_seconds = int(input('How many seconds will your timer span through? '))
converting span_seconds into an int, your code might behave in the way you want it to.

Variable not defined error, and if statement doesn't execute

I'm trying to code horoscope that comes after the user input the birth month and day.
print("To figure out your horoscope, enter the following questions")
month = int(input("what month were you born(january,december,august: "))
days = int(input("what day were you born(2,4,12: "))
if month == 'december':
astro_sign = 'Sagittarius are nice people' if (day < 22) else 'Capricon are adventurous'
print(astro_sign)
However, every time I execute the code, it gives me an error:
print(astro_sign)
NameError: name 'astro_sign' is not defined
Currently, I only put one month which is 12 and day is below 22, later on when one piece of this code works, I'm going to add more months. Can anyone please help me?
That is because you are introducing/creating your astro_sign variable inside your conditional if month == '12':. So, every time you enter something that is not in fact '12', you will end up getting this error.
Simply, create your astro_sign before the conditional, so it is at least available in the event you don't enter your condition:
astro_sign = ''
if month == '12':
# rest of code here
Furthermore, you will never actually enter that condition with your current code, because you are casting your input for month as an int here:
month = int(input("month: "))
However, your condition is explicitly checking for a string per your single quotes: '12'.
So, instead of:
if month == '12':
You in fact should do:
if month == 12:
Remove the single quotes, so you are comparing int to int.
print("Please enter your birthday")
month = int(input("month: "))
day = int(input("day: "))
if month == '12':
print('Sagittarius are nice people')
if day < 22:
print('Capricon are adventurous')
see if this actually works for you (Tell me if I got it all wrong please)

Knowing if time has already passed or not python

Im using this code right now to get the difference of two different times
from time import strftime
from datetime import datetime
fmt = '%H:%M'
currentTimeString = strftime(fmt) #get the current time
gameTimeObject = datetime.strptime(time , fmt)
currentTimeObject = datetime.strptime(currentTimeString, fmt)
diff = currentTimeObject-gameTimeObject
diff_minutes = diff.seconds/60
I have a for loop that loops through different time values, 11:00, 12:00, 13:00, 14:00.
For the purpose of this example lets say the currentTime is 13:23
Im getting the result that i want when the time has passed meaning, 11:00, 12:00, 13:00 but when it comes to 14:00 the diff_minutes shows the value 1403
Why this is a problem is because I'm doing this after that code is executed
if diff_minutes >= 0 and diff_minutes <= 47:
time = str(diff_minutes)
elif diff_minutes >= 48 and diff_minutes <= 58:
time = "HT"
elif diff_minutes >= 59 and diff_minutes <= 103:
time = str(diff_minutes)
elif diff_minutes >= 104 and diff_minutes <= 107:
time = "90'"
elif diff_minutes >= 108: # HERE IS THE PROBLEM <<<<<<-------
time = "FT"
As you can see the times that has not yet been passed will change to "FT" since I'm using that if statement to know if the time of a games is over. How can i fix this?
--- EDIT more information of what I'm trying to do as asked
So what I'm trying to do here is to set the time variable to a soccer game. The different times as mentioned above 13:00 etc are the times of which when the game starts. So what i want to do is if the currentTime is 13:23, then i would change the time label of that soccer game to 23' since 23minutes has passed. If the total time that has passed is over 108 minutes then it means the game is over that is why i set the time variable to "FT" in the last if statement.
As i said before this is where the problem occurs since the diff_minutes gives me a value of higher than 108 minutes when the games has not yet been started it will change the time variable to "FT" which is wrong
So what we really should do is work only with datetime objects here. When you do math on them, the produce timedelta objects. These timedelta objects are comparable. This makes writing your code secretarial. Also - since an if/elif/else tree is short circuiting, you need not check if a time is between two times, just less than the upper bound. I admit my domain knowledge of soccer is limited to knowing it is a 90 minute game, so you may need to adjust this, but it should give you the idea.
import datetime
def gametime(hour, minute):
now = datetime.datetime.now()
starttime = datetime.datetime.combine(datetime.date.today(), datetime.time(hour, minute))
dif = now - starttime
if dif < datetime.timedelta(seconds=48*60):
return dif.seconds / 60
elif dif < datetime.timedelta(seconds=58*60):
return "Half Time"
elif dif < datetime.timedelta(seconds=104*60):
return dif.seconds / 60
elif dif < datetime.timedelta(seconds=108*60):
return "90'"
else:
return "Final"
PS: Seriously, Guido?
PPS: I should have tested this before posting it. I am sorry that I did not.

24-Hour Time Conversion to 12-Hour Clock (ProblemSetQuestion) on Python

I am a beginner programmer in Python and I have no idea how to proceed with the following question. There are a ton of similar questions out there, however there are none having to do with Python code.
I have tried to compare the strings but I am uncertain how to make the comparison. I'm pretty sure I need to take the first two numbers (hours) and divide by 12 if it is greater than 12 ... but that presents problems.
Question:
Time Conversion (24hrs to 12hr)
Write a function that will allow the
user to convert the 24 hour time format to the 12 hour format (with
'am','pm' attached). Example: from '1400' to '2:00pm'. All strings
passed in as a parameter will have the length of 4 and will only
contain numbers.
Examples (tests/calls):
>>> convertTime('0000')
'12:00am'
>>> convertTime('1337')
'1:37pm'
>>> convertTime('0429')
'4:29am'
>>> convertTime('2359')
'11:59pm'
>>> convertTime('1111')
'11:11am'
Any input or different methods would be awesome!
You could use the datetime module, but then you would have to deal with dates as well (you can insert wathever you want there). Probably easier to simply parse it.
Update: As #JonClements pointed out in the comments to the original question, it can be done with a one liner:
from datetime import datetime
def convertTime(s):
print datetime.strptime(s, '%H%M').strftime('%I:%M%p').lower()
You can split the input string in the hours and minutes parts in the following way:
hours = input[0:2]
minutes = input[2:4]
And then parse the values to obtain an integer:
hours = int(hours)
minutes = int(minutes)
Or, to do it in a more pythonic way:
hours, minutes = int(input[0:2]), int(input[2:4])
Then you have to decide if the time is in the morning (hours between 0 and 11) or in the afternoon (hours between 12 and 23). Also remember to treat the special case for hours==0:
if hours > 12:
afternoon = True
hours -= 12
else:
afternoon = False
if hours == 0:
# Special case
hours = 12
Now you got everything you need and what's left is to format and print the result:
print '{hours}:{minutes:02d}{postfix}'.format(
hours=hours,
minutes=minutes,
postfix='pm' if afternoon else 'am'
)
Wrap it up in a function, take some shortcuts, and you're left with the following result:
def convertTime(input):
h, m = int(input[0:2]), int(input[2:4])
postfix = 'am'
if h > 12:
postfix = 'pm'
h -= 12
print '{}:{:02d}{}'.format(h or 12, m, postfix)
convertTime('0000')
convertTime('1337')
convertTime('0429')
convertTime('2359')
convertTime('1111')
Results in:
12:00am
1:37pm
4:29am
11:59pm
11:11am
Some tips
int("2300") returns an integer 2300
2300 is PM.
time >= 1200 is PM
time between 0000 and 1200 is AM.
You could make a function that takes a string, evaluates it as integer, then checks if it is greater or less than the above conditions and returns a print.
import datetime
hour = datetime.datetime.now().strftime("%H")
minute = datetime.datetime.now().strftime("%M")
if int(hour) > 12:
hour = int(hour) - 12
amPm = 'PM'
else:
amPm = 'AM'
if int(hour) == 12:
amPm = 'PM'
if int(hour) == 0:
hour = 12
amPm = 'AM'
strTime = str(hour) + ":" + minute + " " + amPm
print(strTime)
Take hour and minute from datetime. Convert hour to an int. Check if int(hour) > 12. If so, change from AM to PM. Assign hour with int(hour) - 12. Check if hour is 0 for 12 AM exception. Check if hour is 12 for 12 PM exception. Convert hour back into a string. Print time.

Categories