I need to assign a user-provided integer value to an object. My format is as follows:
object = input("Please enter an integer")
The following print tests...
print(type(object))
print(object)
...return <class 'str'> and '1'. Is there a way to set the data type of 'object' to the data type of the user's input value? IOW, such that if object=1, type(object)=int? I know I can set the data type of an input to int using the following:
object = int(input("Please enter an integer"))
In this case, if the user does not provide an int, the console throws a traceback error and the program crashes. I would prefer to test whether the object is in fact an int; if not, use my program to print an error statement and recursively throw the previous prompt.
while True:
try:
object = int(input("Please enter an integer"))
break
except ValueError:
print("Invalid input. Please try again")
print(type(object))
print(object)
You can always catch a "traceback error" and substitute your own error handling.
user_input = input("Please enter an integer")
try:
user_number = int(user_input)
except ValueError:
print("You didn't enter an integer!")
Related
import random
random.randint(1,100)
while True:
cevap = int(input("what is the number that computer chose?"))
if cevap > random:
print("you typed higher.")
if cevap < random:
print("you typed lower.")
if cevap == random:
ae = input("again?")
I wrote this code, but I get the error mentioned. Can you help me?
I was trying to create a "guess the number" type thing but I can't get over this.
I'm a beginner btw
I am trying to send data to a login textbox but when I use 'send_keys' I get an error..
def wait_for_element(selenium, selenium_locator, search_pattern, wait_seconds=10):
elem = None
wait = WebDriverWait(selenium, wait_seconds)
try:
if (selenium_locator.upper() == 'ID'):
elem = wait.until(
EC.visibility_of_element_located((By.ID, search_pattern))
)
except TimeoutException:
pass
return elem
userid=os.environ.get('userid')
wait_for_element(selenium, "ID", 'username')
assert elem is not None
elem.click()
time.sleep(3)
elem.send_keys(userid)
tests\util.py:123: in HTML5_login
elem.send_keys(userid)
..\selenium\webdriver\remote\webelement.py:478: in send_keys
{'text': "".join(keys_to_typing(value)),
value = (None,)
def keys_to_typing(value):
"""Processes the values that will be typed in the element."""
typing = []
for val in value:
if isinstance(val, Keys):
typing.append(val)
elif isinstance(val, int):
val = str(val)
for i in range(len(val)):
typing.append(val[i])
else:
for i in range(len(val)):
for i in range(len(val)):
E TypeError: object of type 'NoneType' has no len()
I have no clue why it is saying the element is of "NoneType" when I have it pass an assertion as well as click the element. I can even see it clicking the element when I run the test!
This error message...
elem.send_keys(userid) ..\selenium\webdriver\remote\webelement.py:478: in send_keys {'text': "".join(keys_to_typing(value)), value = (None,)
TypeError: object of type 'NoneType' has no len()
...implies that send_keys() method encountered an error when sending the contents of the variable userid.
Though you have tried to use the variable userid, I don't see the variable userid being declared anywhere within your code block. Hence you see the error:
TypeError: object of type 'NoneType' has no len()
Solution
Initialize the userid variable as:
userid = "Austin"
Now, execute your test.
I don't quite have an answer but I'm narrowing it down. Somehow I'm mixing/confusing types, I believe, between what is provided by commands like 'os.path' and type str().
As I've made the assignment of the logfile(s) globally, even though I can print it in the function, when the variable is used in fout = open(... it's actually a null that's being referenced, i.e. open() doesn't like/can't use the type it finds.
The error:
UnboundLocalError: local variable 'fout' referenced before assignment
I am simply writing a log of dot files (left on USB drives by OSX) for deletion, but the try/except is now falling over. First the original version.
working code:
logFile = "/Users/dee/Desktop/dotFile_names.txt"
try:
fout = open(logFile, 'w')
for line in dotFile_names:
fout.write(line)
except IOError as e:
print ("Error : %s not found." % fout)
finally:
fout.close()
Attempting better practice, I sought to put the log file specs and path as variables so they can be modified if need be - I hope to make it cross platform workable. these variables are at the head of the program, i.e. not in main(), but I pass them in and print() statements have shown me they are successfully being referenced. i.e. I get this printed:
/Users/dee/Desktop/dotFile_names.txt
Despite this the error I get is:
UnboundLocalError: local variable 'fout' referenced before assignment -
error points at the "fout.close()" line
Error producing code
logFilespec = "dotFile_names.txt"
fullLogFileSpec = []
userDesktop = os.path.join(os.path.expanduser('~'), 'Desktop')
fullLogFilespec = os.path.join(userDesktop, logFilespec)
try:
print "opening " + fullLogFilespec
fout = open(fullLogFileSpec, 'w')
for line in dotFile_names:
print "..", # are we executing this line..?
fout.write(line)
except IOError as e:
print ("Error : %s not found." % fout)
finally:
print "\nclosing " + fullLogFilespec
fout.close()
I've found that if I modify this line by converting to a string
fout = open(fullLogFileSpec, 'w')
fout = open(str(fullLogFileSpec), 'w')
the error goes away, BUT NO file is created on the Desktop!
At the very least I guess that I am passing something unrecognisable to fout = open() but it is not being caught by the except. Then when I pass something that does seem to allow fout =open() to work it seems to be a ghost?
So I figure I am lost between a String and whatever kind of reference/pointer os.path.expanduser() gives me.
I'm sure it's insanely simple. Before adding the str() code I also checked all indentation, removing them all and adding back using the editor indent hotkeys, just in case that was affecting things somehow.
OK, it looks like I was wearing my dumb glasses, I think declaring
fullLogFileSpec = []
as a list instead of a string was my error.
Similar as it is, having re-written it without that list declaration this code is working fine:
logfile_directory = os.path.join(os.path.expanduser('~'),'Desktop')
log_bf_file_spec = 'ItemsFoundByFolder_' + Deez_1.current_datetime() + '.txt'
log_by_folder = os.path.join(logfile_directory, log_bf_file_spec)
the function later calls, with no error:
fout_by_folder = open(log_by_folder, 'w')
My try:
(com-invoke fsc "Connect" "" (box +0))
exact error:
Connect: expected argument of type <(box unsigned-int)>; given: '#&0
How to pass <(box unsigned-int)> to com-invoke?
I have added the following code in sale.py but I am unable to see output of print in
server.log. I wish to fill a one2many field by returned list of this function
I am using openerp6.1 under windows xp
my code is
def model_id_change(self,cr,uid,ids,model_id,context=None):
list1=[]
if context is None:
context = {}
print "Hi"
print str(model_id)
if not model_id:
raise osv.except_osv(_('No Model Selected !'),_('You have to select Model.'))
querystr = 'SELECT microswitch FROM product_model WHERE id = ' + model_id
print querystr
try:
cr.execute(querystr)
s=cr.fetchone()
print s
list1=[]
print list1
for t in s.split(','):
if t:
list1.append(t)
except:
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
return(list1)
The print statement prints to standard output. If you want to get something in the server log, use the logging module.
import logging
logger = logging.getLogger(__name__)
logger.info('my message, with a substituted variable %s', s)