Re: [Tutor] Terminology question

2015-05-15 Thread Jim Mooney Py3.4.3winXP
On 14 May 2015 at 16:47, Alan Gauld  wrote:

> Rather than printing the messages you could re-raise
> the error but with the error message attached as a string.
>

I'm a little unclear how you catch the string you create in a raise, in the
caller. I tried an example from the docs but it didn't work. Could you
provide a simple example? Sometimes the docs are heavy slogging if you
don't already know what's what ;')

-- 
Jim
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Terminology question

2015-05-15 Thread Mark Lawrence

On 15/05/2015 20:02, Jim Mooney Py3.4.3winXP wrote:

On 14 May 2015 at 16:47, Alan Gauld  wrote:


Rather than printing the messages you could re-raise
the error but with the error message attached as a string.



I'm a little unclear how you catch the string you create in a raise, in the
caller. I tried an example from the docs but it didn't work. Could you
provide a simple example? Sometimes the docs are heavy slogging if you
don't already know what's what ;')



Please help us to help you, if you were to show the example from the 
docs that "didn't work" we could easily clarify the situation for you.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help!

2015-05-15 Thread Fredrick Barrett
Hi, I'm a beginner and I've reached a roadblock. I'm trying to create a
simple guessing game program just to practice creating loops, however it is
not working out as planned.

print ("Lets play a game")

import random

# Generate random number from 1-10
rand_value = random.randint(1,10)
guess = input("Guess a number from 1-10 ")

if guess == rand_value:
print ("Congratulations! You guessed it!")
while guess != rand_value:
input ("try again")
else:
print ("Sorry, you're wrong.")


input ("\n\nBetter luck next time. Press the enter key to exit.")

The goal is for the program to keep running until someone successfully
guesses the right number, however I think I've accidentally created an
infinite loop. Any help will be greatly appreciated.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Connecting Py 2.7 with visa

2015-05-15 Thread Wilson, Pete
Greetings I am trying to write a test executive program using python 2.7 on a 
windows 7 computer. I want to connect to  a Keithley 2100 voltmeter using 
National Instruments VISA. I am having trouble installing pyvisa. All the 
documentation refers to using 'pip' and a command line "$ pip install pyvisa" . 
What interface or console is this? "$" prompt looks like a Linux command line. 
How do we do this with windows?

Do I have to do this? Or can I use the native visa module in Python 2.7? Using 
the help() and dir() features I can get some basic information about visa, but 
the functions have changed, like visa.ResourceManager.open_resource is not 
working. I really liked this function... Are there any examples of how to use 
this new visa? I have some working code below that uses pyvisa, can it be 
converted?

def update_current():
import visa

rm = visa.ResourceManager()
rm.list_resources()

current_1_ma = ""
exe_check = "PASS"

try:
dut_data = open("dut_data.txt", "w")
except:
exe_check = "FAIL"

try:
ki2100 = rm.open_resource('USB0::0x05E6::0x2100::1148525::INSTR')
device_id = ki2100.query("*IDN?")
except:
exe_check = "FAIL"

try:
dut_current_amps = (float(ki2100.query("MEASure:CURRent:DC?")))
dut_current_ma = dut_current_amps * 1000.0
current_1_ma = "%6G" % dut_current_ma
except:
exe_check = "FAIL"

new_line = "Litepoint_Data_Format" + "\r\n"
dut_data.write(new_line)
new_line = "CURRENT_1_MA=" + current_1_ma + "\r\n"
dut_data.write(new_line)
new_line = "EXE_CHECK=" + exe_check + "\r\n"
dut_data.write(new_line)

dut_data.close()

return


if __name__ == "__main__":

update_current()

print "Dumping dut_data.txt"

with open('dut_data.txt') as dut_data:

for line in dut_data:
print line,
   if 'str' in line:
break

dut_data.close()

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help!

2015-05-15 Thread Steven D'Aprano
On Fri, May 15, 2015 at 07:35:30PM -0400, Fredrick Barrett wrote:


> print ("Lets play a game")
> 
> import random
> 
> # Generate random number from 1-10
> rand_value = random.randint(1,10)
> guess = input("Guess a number from 1-10 ")

Here you guess once.

> if guess == rand_value:
> print ("Congratulations! You guessed it!")

If you guessed correctly, the game ends.

> while guess != rand_value:
> input ("try again")
> else:
> print ("Sorry, you're wrong.")


You ask the user to try again, but you pay no attention to their reply. 
You just completely ignore their guesses, apart from the very first one.

Also, and by the way, although Python does have a "while...else" 
construct, it's a bit misleading and I don't think it is useful in this 
case.

Experiment with something like this instead:


rand_value = random.randint(1,10)
guess = 0  # Guaranteed not to match.
while guess != rand_value:
guess = input("Guess a number between one and ten: ")

print("Congratulations!")



Notice that each time through the loop, I set guess to a new value?



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Connecting Py 2.7 with visa

2015-05-15 Thread Mark Lawrence

On 15/05/2015 23:12, Wilson, Pete wrote:

Greetings I am trying to write a test executive program using python 2.7 on a windows 7 computer. I 
want to connect to  a Keithley 2100 voltmeter using National Instruments VISA. I am having trouble 
installing pyvisa. All the documentation refers to using 'pip' and a command line "$ pip 
install pyvisa" . What interface or console is this? "$" prompt looks like a Linux 
command line. How do we do this with windows?



It's a Windows command line prompt.  You can get this by hitting the 
Windows logo key with 'R' and then entering cmd.  However the 
simplest way for you I think is to download this 
https://sites.google.com/site/pydatalog/python/pip-for-windows



Do I have to do this? Or can I use the native visa module in Python 2.7? Using 
the help() and dir() features I can get some basic information about visa, but 
the functions have changed, like visa.ResourceManager.open_resource is not 
working. I really liked this function... Are there any examples of how to use 
this new visa? I have some working code below that uses pyvisa, can it be 
converted?



Please help us to help you.  Stating "is not working" is less than 
useless, please show us exactly what happens.  Cut and paste any output, 
don't rely on typing it as this often results in further errors that 
just confuse the issue.



def update_current():
 import visa

 rm = visa.ResourceManager()
 rm.list_resources()

 current_1_ma = ""
 exe_check = "PASS"

 try:
 dut_data = open("dut_data.txt", "w")
 except:
 exe_check = "FAIL"


Don't use bare excepts as it's asking for trouble.  Much better to leave 
out the error handling to start with and just let your programming 
errors bubble up as stack traces.  Then add in appropriate things to 
catch.  In the above FileNotFoundError amongst others seems suitable.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Terminology question

2015-05-15 Thread Steven D'Aprano
On Fri, May 15, 2015 at 12:02:44PM -0700, Jim Mooney Py3.4.3winXP wrote:
> On 14 May 2015 at 16:47, Alan Gauld  wrote:
> 
> > Rather than printing the messages you could re-raise
> > the error but with the error message attached as a string.
> >
> 
> I'm a little unclear how you catch the string you create in a raise, in the
> caller. I tried an example from the docs but it didn't work.

What does "didn't work" mean? Did your computer crash? Catch fire? A 
completely different error got printed? Something else?


> Could you
> provide a simple example? Sometimes the docs are heavy slogging if you
> don't already know what's what ;')

I'm not entirely sure what part you are having trouble with. I assume 
you know how to catch an exception:

alist = []
try:
value = alist[2]
except IndexError:
pass  # Just pretend it didn't happen...


and how to inspect its error message:



alist = []
try:
value = alist[2]
except IndexError as err:
print(err.args[0])



We can also *replace* the error message with one of our own. The args 
attribute is a tuple, normally the error message is in the zeroeth 
position as above. So we just have to replace args with a tuple of our 
own and re-raise the exception:


try:
value = alist[2]
except IndexError as err:
err.args = ("Er, wot?",) + err.args[1:]
raise



An alternative is to replace the exception with a completely different 
exception:



try:
value = alist[2]
except IndexError:
raise RuntimeError("er, wot?")



In Python 2, this suppresses the IndexError and raises RuntimeError 
instead. However, this hides bugs in the case that the second exception 
isn't deliberate, but a bug. So starting with Python 3, exceptions are 
chained, which means that if an exception occurs inside an "except" 
block, Python will display both exceptions and not just the most recent:


Traceback (most recent call last):
  File "", line 2, in 
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "", line 4, in 
RuntimeError: er, wot?



This is a great boon for debugging accidental bugs, but doesn't help 
much if you actually do intend to replace one exception with another. So 
starting from Python 3.3 you can suppress the chaining:

try:
value = alist[2]
except IndexError:
raise RuntimeError("er, wot?") from None



which gives just a single exception:

Traceback (most recent call last):
  File "", line 4, in 
RuntimeError: er, wot?



Does this help?




-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Terminology question

2015-05-15 Thread Steven D'Aprano
On Thu, May 14, 2015 at 03:43:30PM -0700, Jim Mooney Py3.4.3winXP wrote:
> I noticed that if I call a function that throws an error, I can catch it
> from the caller, instead of catching it in the function. Is this is what is
> known as "errors bubbling up?" Also, is this how you're supposed to do it?

Consider a chain of functions:

main() calls setup();
setup() calls process_arguments();
process_arguments() calls read_config();
read_config() calls open("somefile");

and open("somefile") raises an exception (perhaps the file cannot be 
found, or you don't have permission to read it).


Each function in the chain gets a chance to catch the exception:

open <- read_config <- process_arguments <- setup <- main


If open doesn't catch the exception, we say that the exception "bubbles 
up" the chain until it is caught, or if none of them catch it, then it 
bubbles all the way up and finally reaches the Python interpreter, which 
prints a stack trace and exits.


[...]
> def get_input():
> inp = input("Enter minimum, maximum, rows, and columns, separated by
> commas: ")
> inps = inp.split(',')
> try:
> minimum = int(inps[0])
> maximum = int(inps[1])
> rows = int(inps[2])
> columns = int(inps[3])
> return minimum, maximum, rows, columns

This is not best practice. There are too many things which might cause 
an exception. Ideally, a try block should only contain *one* thing which 
might go wrong. Here you have at least four. By treating them all the 
same, you lose the opportunity to give the user information about 
*which* one they screwed up.


> except ValueError as err:
> print("non-integer entered", err)
> return None

This is bad practice, for two reasons.

You might not think so yet, but Python tracebacks give you a lot of 
useful debugging information. Here, you flush that useful information 
down the toilet and replace it with a not-very helpful message 
"non-integer entered" (plus a bit more stuff). In a trivial script that 
might not matter, but in a big script, you may have *no idea* where this 
non-integer was entered. There could be thirty places where it might 
happen. How do you know which one it is?

The second reason is that you really should only catch exceptions that 
you can do something about. If you can't fix the problem, there's no 
point in catching the exception[1]. In this case, if the user doesn't 
enter a valid set of values, there's no way you can proceed. So why 
bother delaying the inevitable? Just let the exception exit the program.

This will also look after all the little things which distinguish a 
professional quality application from a jerry-built beginner's toy. For 
example: error messages should print to stderr, not stdout; the 
application should exit with a non-zero result code. If this means 
nothing to you, don't be too concerned about it, just understand that 
Python will do the right thing provided you don't get in its way, as you 
just did by catching the exception.





[1] Well, there is one other reason: in an application aimed at 
non-programmers, you might choose to catch the exception, log the 
traceback somewhere where you can get to it for debugging, and display a 
"friendly" (i.e. non-technical, non-threatening, useless) message to the 
user. But as a beginner yourself, you shouldn't do this until you have 
become an expert in reading tracebacks. Otherwise you're just hiding 
debugging info that you need.


-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor