Getting time of day from user for silly simple app - python-3.x

I am begginer in Python and I wanted to try to make myslef a simple piece of code that would take my input of time when I came to work and tell me when I get to go home.
Problem is the input formatting and then adding those 8 hours of work into it and having an output.
I can make it work with integers but that is not good enough. I would like to see HH:MM format in I/O
I searched all around the web but what I found are mostly articles and advice about time in general (date and more importantly, the datetime.now) whereas I need it to understand I want to input time when I came to work and time when I get to leave the work, regardless of day and so on.
# When do I get to go home program
# first we need ot define a variable to use it to store the time when I came
# to work
# That is atw (arrived to work)
# gh is "go home"
from datetime import time
atw = input ("When I came to work in format of HH:MM \n")
#atw = datetime.strptime(input('enter time you arrived to work in HHMM format: '), "%H%M")
h,m = map (int, time.split(":"))
#gh = atw (hour = h, minute = m)
print (("I came to work #", atw ,"%H%M"))
gh = atw + 0800
print ("You can go home # ", gh)
All sort of error messages, from syntax to problems with format of my input and adding of those 8 hours of work to the final number (gh variable)
Is there some awesome being that could walk me trough how do I actually make python to understand that I am adding time to variable that should be formatted as time (HH:MM) input which is coming form user?

Ok, let's do this step by step, because as you said, there All sort of error messages, from syntax to...
from datetime import time
atw = input ("When I came to work in format of HH:MM \n")
These first two lines work without problem, that's fine.
h,m = map (int, time.split(":"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.time' has no attribute 'split'
Oh, an error, let's read what the error message says: type object 'datetime.time' has no attribute 'split'. Well, that's correct, because we don't want to split time, but the time that we gave to input and that has the name atw, so let's use that:
h,m = map (int, atw.split(":"))
print (("I came to work #", atw ,"%H%M"))
No error, but a weird output:
('I came to work #', '08:17', '%H%M')
You probably didn't want a tuple as output (the parentheses) and wanted to format that output, as I can see from the format string "%H%M". Fortunately python (>=3.6) has a nice solution for that called f-strings:
print (f"I came to work #{atw}")
Hmmm, wait, what about the formatting, that just outputs what we inputed... So make use of h and m:
print (f"I came to work #{h:02d}:{m:02d}")
Do a google search what that :02d means and what other options there are ;)
Next line:
gh = atw + 0800
File "<stdin>", line 1
gh = atw + 0800
^
SyntaxError: invalid token
Hmmm, you want to add 8 hours to get the endtime, but all you get is an syntax error... That's because 0800 is no valid python construct, you probably ment just 8? Let's try this...
gh = atw + 8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
Another error, but why? You are using atw, which is a string, albeit you already split that in two ints h and m, with h representing the hours:
gh = h + 8
print ("You can go home # ", gh)
Ahh, damn that print again. Look above and use f-strings:
print (f"You can go home #{gh}:{m}")
And now try to see if you get a solution using strptime as #mkrieger1 suggested in the comments.
And pleeeeease do a python tutorial :)

Related

Empty Input line raises an error in Python 3.3

I'm new at Python and trying some exercises I found on-line. The one I'm busy with requires an text input first, folowed by an ineteger input.
I get stuck on the integer input which raises an error.
I've started by modifying the code slightly to test myself when I first got the error.
Eventually changed it backed to be exactly like the example/exercise had it, but both resulted in the same error, on the same line.
The error raised was:
Traceback (most recent call last):
File ************************ line 7, in <module>
numOfGuests = int(input())
ValueError: invalid literal for int() with base 10: ''
I've checked around a bit and found it get's triggered when the input is empty, but according to what I've read the the rest of the code should handle that.
numOfGuests = int(input())
if numOfGuests:
I expected the code to ask for the input again if nothing was entered, but get the error instead.
Much appreciated.
Update:
I've managed to figure out a work-around, and even though it isn't a answer to my question, I'll take it.
For anyone that's interested, here's what I did:
I changed:
numOfGuests=int(input())
to:
numOfGuests=input()
Only once something was entered did I convert it:
numOfGuests=int(numOfGuests)
so the final block is:
numOfGuests=''
while not numOfGuests:
print('How many guests will you have?')
numOfGuests = input()
numOfGuests=int(numOfGuests)
Any ideas to improve it, or some insight, would be appreciated.
I know this question is 10 months old but I just want to share the reason why you are having an error ValueError.
Traceback (most recent call last):
File ************************ line 7, in <module>
numOfGuests = int(input())
ValueError: invalid literal for int() with base 10: ''
Is because the input() function reads any value and convert it into a string type. Even if you try to input empty or blank.
Sample code:
any_input = input("Input something: ")
print(f"Your input is: [{any_input}]")
Ouput:
Input something:
Your input is: []
Then the blank or empty string will be passed inside the int() function. The int() function will try convert string into an integer with a base of 10. As we all know, there is no blank or empty numbers. That is why it is giving you a ValueError.
To avoid this, we need to use try-except/EAFP in your code:
try:
# Try to convert input to integer
numOfGuests = int(input("How many guests will you have? "))
except:
# Handle Value Error
And put inside a While-loop to repeat until input is valid.
Sample code:
while True:
try:
# Try to convert input to integer
numOfGuests = int(input("How many guests will you have? "))
# If input is valid go to next line
break # End loop
except:
# Handle Value Error
print("Invalid input!")
print(f"The number of guest/s is: {numOfGuests}")
Ouput:
How many guest will you have? 3
The number of guest/s is: 3

Remove unicode '\xa0' from pandas column

I was given a latin-1 .txt dataset, which I am trying to clean up to use for proper analysis using python 3 and pandas. The dataset, being scraped from html contains a number of \xa0 occurences, which I can't seem to deal with using decode, strip, -u replace, or any other method which I found on stack overflow. All of my attempts seem to be ignored by python, still printing out the same results. As I am new to data scraping, chances are that I missed out on something obvious, but right now I don't see a way forward
I have tried to decode to ascii, strip to str and then replace, or replace using a -u clause, not leading to anything
filepath = 'meow3.txt'
outF = open("myOutFile.txt", "a")
with open(filepath) as fp:
line = fp.readline()
for line in fp:
if line.strip().startswith(','):
line = line.replace(',','',1)
line = line.replace(u'\xa0', u' ')
print(line)
df = pd.read_csv('myOutFile.txt', sep=",", encoding="latin-1", header=None, names=["Company name", "Total", "Invested since-to"])
print (df)
3sun Group, £10m ,Feb 2014
,Abacus, £4.15m ,Aug 2013
,Accsys Group ,£12m, Mar 2017,
Acro ,\xa0£7.8m, Nov 2015 – Sep 2017,
ACS Clothing, £25.3m ,Jan 2014
this is how the dataset looks like, and why in my code I am removing the first comma provided it is at the start of the column. But none of the suggested answers I tried seemed to help with removing the \xa0 part of the dataset, still giving the same result (seen above). If anyone has any clue for how I could make this work, I would be very grateful,
Cheers,
Jericho
Edit: While I know this would be best dealt with by pre-processing before turning it into txt file, I have no access or control of that process, and I have to work with the data I was given.
I suddenly stuck by this problem today and finally find a quickest and neatest solution.
Say your pandas dataframe has a column with values like 'South\xa0Carolina'.
Use the following code to remove all '\xa0'. Actually I have tried .replace("\xa0"," ") and .replace(r'\xa0',r' '), but none of them worked.
data['col'].str.split().str.join(' ')
do this after reading the file.
df['col'] = df['col'].apply(lambda x: str(x).replace(u'\xa0', u''))
Maybe decoding line to UTF8 will help
line = line.decode('UTF-8')
Then do the string replacement after that, if necessary.

Finding a List Position Represented by a Variable

Basically I have a variable equal to a number and want to find the number in the position represented by the variable. This is what I
numbertocheck =1
loopcriteria = 1
while loopcriteria == 1:
if numbertocheck in ticketnumber:
entryhour.append[numbertocheck] = currenttime.hour
entryminute.append[numbertocheck] = currenttime.minute
print("Thank you. Your ticket number is", numbertocheck)
print("There are now", available_spaces, "spaces available.")
loopcriteria = 2
I get this error (in pyCharm):
Traceback (most recent call last): File
"/Users/user1/Library/Preferences/PyCharmCE2017.3/scratches/scratch_2.py",
line 32, in entryhour.append[numbertocheck] =
currenttime.hour TypeError: 'builtin_function_or_method' object does
not support item assignment
How do I do what I'm trying to do?
Though you haven't provided the complete code, I think you only have problem with using append. You cannot use [] just after an append. To insert into a particular position, you need insert
Putting the relevant lines you need to replace below...
entryhour.insert(numbertocheck,currenttime.hour)
entryminute.insert(numbertocheck,currenttime.minute)
# available_spaces-=1 # guessing you need this too here?
P.S. your loop doesn't seem to make sense, I hope you debug it yourself if it doesn't work the way you want.

Can't print an integer that has been converted to a string

I am trying to do something that should be very simple. I am a bit frustrated for why my code won't work, so any help is appreciated :).
My program reads in data, and then makes a dictionary that records the number of times a particular item occurs (I am using Twitter data and counting hashtag occurrences). I want to output the top tweets, and have found a nice easy way to do that using the following:
def main():
tweet_file = open(sys.argv[1])
tweet_dic = lines(tweet_file) #function that makes my dictionary
for i in range(0,10):
big_key = max(tweet_dic, key = lambda i: tweet_dic[i])
big_value = tweet_dic[big_key]
sys.stdout = big_key + " " + str(big_value)
del tweet_dic["big_key"]
tweet_file.close()
The error I get on using this is AttributeError: 'str' object has no attribute 'write'
Now I have outputted the two different values into terminal using print just fine, they can be put in two different print statements with no problems since I don't have to concatenate or anything. I have checked the two variables types, and as expected they are always str & int.
My understanding of the str(integer to convert) function is that you should be able to pass in an integer and get a string representation back! After it has been converted, I have been able to print out things like this in the past with no issues.
Things to consider that may be throwing it out - the big_key can sometimes be a string that was converted from Unicode by .encode('utf-8'). Otherwise the output from my file (printing on separate lines) looks like:
MTVHottest 60
KCAMexico 38
EXO 26
CD9 24
Unicode 19
Coders 18
AlonsoVillapandoTrendy 17
Unicode 14
Unicode 14
Any ideas? Thanks in advance!
The error you're getting is because of this: https://docs.python.org/2/library/sys.html#sys.stdout
stdout and stderr needn’t be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument.
stdout and stderr are the locations where the data is written, you aren't supposed to assign data itself to stdout, which is what it looks like you're doing.
As others have mentioned you would assign stdout to where you want and then use the print command to actually get the data to go there. But if all you're trying to do is print a line of text to a file then why not just open the file and write to it normally?
with open(tweet_file, 'w') as f:
f.write(big_key + " " + str(big_value))
The specific error you're getting is from the line:
sys.stdout = big_key + " " + str(big_value)
This is not how things are output to stdout.
Using a print would be the appropriate way to do that:
print(big_key + " " + str(big_value))
There are some other strange things in your code example, like for example using big_key and then "big_key" in quotes. So probably that's not the end of your bugs and errors.

Compare a user inputted value to an iterated value in a list

I am trying to compare values in a list of files (named as a date) to a user inputted start and end date, but I'm having some trouble when iterating the through the list in comparing the values.
Here is the code:
import os
import datetime
from tkinter.filedialog import askdirectory
x = askdirectory()
start = input('Enter start date (ddmmyyyy): ')
end = input('Enter end date (ddmmyyyy): ')
start = datetime.datetime.strptime(start, "%d%m%Y").strftime("%Y%m%d")
end = datetime.datetime.strptime(end, "%d%m%Y").strftime("%Y%m%d")
start = int(start)
end = int(end)
for files in os.walk(x):
file = files[2]
if '2' in file[1]:
file = [int(i) for i in file]
print(len(file))
for i in file:
if start >= file >= end:
fr.file_reader(time,rdata,intensity,files[i])
print(files[i])
When I run this, I get the following error:
TypeError: '>=' not supported between instances of 'int' and 'list'
I have tried converting the input to an integer, tried converting the list itself to integers but that didn't help. I know that at the moment it is reading the file as the whole list in the if loop, I just want it to read the ith file and iterate through, in order to read that file using my working file reader program. I can't work out how to achieve this.
Here is an what the first 10 files in my file list looks like. It's full length is 312 items so I won't copy it all here.
['20151123000103', '20151123220540', '20151124000043', '20151124003712', '20151125000055', '20151125070850', '20151126000101', '20151126000204', '20151126000330', '20151126000513']
If I could get any help with this I'd be most grateful :)
So I fixed it, the error itself was fixed by replacing "file" with "i". Knew it would be something small and simple.

Resources