why my function is not working for except block? - python

While putting the def clockPrint() function in try-except, try block is working fine but except block is not working (printing the statement as output which is in except block)
import datetime
try:
def clockPrint(sentence):
now = datetime.datetime.now()
date_time = now.strftime("%H:%M:%S")
print(date_time + " : " + sentence)
except TypeError:
print("Error: Invalid sentence")
If I try to call clockPrint(909) then according to the logic, it should display "Error: Invalid sentence" as an output but it is displaying "TypeError: can only concatenate str (not "int") to str" as an output. Any suggestions

You try block just does nothing. Define function outside try block and just call it from this block.
import datetime
def clockPrint(sentence):
now = datetime.datetime.now()
date_time = now.strftime("%H:%M:%S")
print(date_time + " : " + sentence)
try:
...
clockPrint(sentence)
...
except TypeError:
print("Error: Invalid sentence")

import datetime
def clockPrint(sentence):
try:
now = datetime.datetime.now()
date_time = now.strftime("%H:%M:%S")
print(date_time + " : " + sentence)
except TypeError:
print("Error: Invalid sentence")

Try this:
import datetime
def clockPrint(sentence):
now = datetime.datetime.now()
date_time = now.strftime("%H:%M:%S")
try:
print(date_time + " : " + sentence)
except TypeError:
print("Error: Invalid sentence")

Related

How to fix this AttributeError

I am trying to access a variable within a function in a class and print it. Whenever I try I keep getting the error: AttributeError: 'NoneType' object has no attribute 'job_ID'.
def driver():
q = my_queue.Queue_()
for line in df:
if 'received' in line:
q.enqueue(line)
print("Adding job " + q.new_item.job_ID + " to the queue with the timestamp: " + q.new_item.time_stamp + ".")
print("The prority of the job is: " + q.new_item.job_priority)
print("The job type is: " + q.new_item.job_type)
if 'respond' in line:
q.dequeue()
print("Completed job " + q.current.job_ID + " in " + str(int(q.time_elapsed)) + " seconds.")
if 'active' in line:
q.active_jobs()
print("Total number of jobs: " + str(len(q.temp)))
print("Average priority: " + str(q.average))
if 'modify' in line:
q.modify(line)
print("Modified job " + q.current.job_ID)
The error is coming from the last print statement in this code.
This is the function within the class that is being used here:
def modify(self, x): # need to fix printing bug
self.current = self.head
while self.current != None:
if x[1] in self.current.get_data():
self.current.data[2] = x[2]
self.current.data[3] = x[3]
break
# print("Modified job " + current.job_ID)
else:
# print('The job details cannot be modified.')
pass
self.current = self.current.get_next()
The exit condition for the loop in the modify function that you have provided is self.current == None.
When you call modify() in this last conditional statement:
if 'modify' in line:
q.modify(line) // here
print("Modified job " + q.current.job_ID)
You are making q.current evaluate to None. Therefore, the reason why you are getting an AttributeError is because q.current is None, which has no such attribute called job_ID.
To fix your problem, you must ensure that q.current is not None before printing q.current.job_ID. I can't give you any help beyond this, since I don't know what the purpose of your program is.

Error - ValueError: invalid literal for int() with base 10: ' '

I am making an online game using the sockets module and pygame in python.
def read_pos(str):
if str is not None:
string = str.split(",")
return int(string[0]), int(string[1])
else:
pass
def make_pos(tup):
return str(tup[0]) + "," + str(tup[1])
def redrawWindow(win,player, player2):
win.fill((255,255,255))
player.draw(win)
player2.draw(win)
pygame.display.update()
def main():
run = True
n = Network()
startPos = read_pos(n.getPos())
p = Player(startPos[0],startPos[1],100,100,(0,255,0))
p2 = Player(0,0,100,100,(255,0,0))
clock = pygame.time.Clock()
while run:
clock.tick(60)
p2Pos = read_pos(n.send(make_pos((p.x, p.y))))
p2.x = p2Pos[0]
p2.y = p2Pos[1]
p2.update()
This is the code I'm using in my client. in my server, the code is as follows
def convertPos(str):
if str is not None:
str = str.split(",")
return int(str[0]), int(str[1])
else:
pass
def make_pos(tup):
return str(tup[0]) + "," + str(tup[1])
pos = [(0,0),(100,100)]
def threaded_client(conn,player):
conn.send(str.encode(make_pos(pos[player])))
reply = " "
while True:
try:
data = conn.recv(2048).decode()
pos[player] = data
if not data:
print("Disconnected")
break
else:
if player == 1:
reply = (pos[0])
else:
reply = (pos[1])
print("Received: ", data)
print("Sending : ", reply)
conn.sendall(str.encode(make_pos(reply)))
except:
break
print("Lost connection")
conn.close()
I am getting the error of ValueError: invalid literal for int() with base 10: ' '.
Can someone tell me why this is happening? The value of str in the function of convertPos() is coming in as a tuple which I am converting into a string and after that into an integer.
As you have converted it to string, the format you have is (x,y), you need to remove the brackets. You need to rewrite your convertPos function as:
def convertPos(str):
if str is not None:
str=str.strip("()")
str = str.split(",")
return int(str[0]), int(str[1])
EDIT You are not using the else part, so you can remove it.
And as #Azat Ibrakov says, you should not convert the tuple to an string, but if you need to do it, you can use ast.literal_eval like this:
import ast
def convertPos(str):
return ast.literal_eval(str)
or use it directly in place of the convertPos function.
Obviously - as others have pointed out, the returned error is because you're trying to convert an empty string (or spaces) to an integer.
But the real issue is that the incoming co-ordinate is malformed. The code is not catching this error. You can write lots of code to determine what the error is, and report an accurate error. Or just plough-on as if everything is fine, but also catch any exception with a reasonable error message.
def convertPos(str):
coord = None
try:
parts = str.split( ',', 2 )
x = int( parts[0] )
y = int( parts[1] )
coord = ( x, y )
except:
raise ValueError( 'Malformed co-ordinate string [' + str.strip() + ']' )
return coord
I suspect the socket code is not buffering a full packet, and maybe what's being processed is something like 122,, whereas the socket buffering needs to keep reading until a full co-ordinate has arrived.
So you could space-pad your co-ordinates to say a block of 11 characters - that way you know you must have received 11 characters to have a valid co-ordinate string. Alternatively use and end-of-coord marker, like a |, and then the socket code keeps buffing the input co-ordinate until that | arrives.

Number split from a string is not numeric

duration = inputScriptLine.split(' ', 1)[1]
if type(duration) == str:
print ' Error: Sleep duration "' + duration + '" is not numeric'
given SLEEP 50, I get Error: Sleep duration "50" is not numeric
I am not too concerned as to why, I just want to know how I can code so that SLEEP 50 is valid and SLEEP APNOEA is not.
Use isdigit():
if not duration.isdigit():
print 'Error: Sleep duration "' + duration + '" is not numeric'
It would check whether all characters in duration are digits or not.
If you want to accept more than just ints you should cast to float:
def is_numeric(s):
try:
float(s)
return True
except ValueError:
return False
duration = inputScriptLine.split(' ', 1)[1]
if not is_numeric(duration):
print(' Error: Sleep duration {} is not numeric'.format())
float("1.0"), float("1"), float("1.5") etc.. would all return True but int("1.0"), int("1.5") etc..would also return False which if you are actually looking for numeric input would be wrong.
If you want to make sure you also get a positive number, store the result after you cast and return f > 0:
def is_positive_numeric(s):
try:
f = float(s)
return f > 0
except ValueError:
return False
try:
duration = int(duration)
except:
pass
This will attempt to convert it to an int, if it's not numeric it will fail and stay a string.
DeveloperXY's solution is cleaner, but if you want to use the value as an int later on, my solution is useful.
duration = inputScriptLine.split(' ', 1)[1]
try:
duration = int(duration)
except ValueError:
print ' Error: Sleep duration "' + duration + '" is not numeric'
You are checking if the input is a string. It will be - you've just used the split command on a string.
You need to check if the string contains only numeric characters, with .isdigit().
Note that this won't accept negative inputs, but you don't want those as this is a time.
So your new code is:
duration = inputScriptLine.split(' ', 1)[1]
if not duration.isdigit():
print 'Error: Sleep duration "' + duration + '" is not numeric'

python - datetime output time only

The function below takes in HH:MM:SS but returns the date. I just want to enter the time and get out the time.
desired:
enter 23:23:23 > returns 23:23:23
currently:
enter 23:23:23 > returns 1900-01-01 23:23:23
question:
How do i get it to return only 23:23:23 time.
import datetime
def ObtainTime():
while True: #Infinite loop
userInDate = raw_input("Type Time HH:MM:SS ")
try:
d = datetime.datetime.strptime(userInDate, "%H:%M:%S")
break #this will stop the loop
except ValueError:
print "Invalid Input. Please try again.\n"
return d
print ObtainTime()
Completed Code:
import datetime
def ObtainTime():
while True: #Infinite loop
userInDate = raw_input("Type Time HH:MM:SS ")
try:
d = datetime.datetime.strptime(userInDate, "%H:%M:%S")
d = d.time()
break #this will stop the loop
except ValueError:
print "Invalid Input. Please try again.\n"
return d
print ObtainTime()
Use datetime.time() to get the time.
Example -
>>> d = datetime.datetime.strptime("23:23:23","%H:%M:%S")
>>> d.time()
datetime.time(23, 23, 23)

How can I validate a date in Python 3.x?

I would like to have the user input a date, something like:
date = input('Date (m/dd/yyyy): ')
and then make sure that the input is a valid date. I don't really care that much about the date format.
Thanks for any input.
You can use the time module's strptime() function:
import time
date = input('Date (mm/dd/yyyy): ')
try:
valid_date = time.strptime(date, '%m/%d/%Y')
except ValueError:
print('Invalid date!')
Note that in Python 2.x you'll need to use raw_input instead of input.
def validDate(y, m, d):
Result = True
try:
d = datetime.date(int(y), int(m), int(d))
except ValueError, e:
Result = False
return Result
and in the program use the function defined previously:
if not validDate(year_file, month_file, day_file):
return 0
Max S.,
Thanks for the code. Here is how I implemented it:
while True:
date = input('Date (m/dd/yyyy): ')
try:
date = time.strptime(date, '%m/%d/%Y')
break
except ValueError:
print('Invalid date!')
continue

Categories