[Tutor] Dividing a float derived from a string

2014-11-20 Thread Stephanie Morrow
Hi there,

I have been posed with the following challenge:

Create a script that will ask for a number. Check if their input is a
legitimate number. If it is, multiply it by 12 and print out the result.

I was able to do this with the following code:

input = raw_input(Insert a number: )
if input.isdigit():
print int(input) * 12
else:
print False

*However*, a colleague of mine pointed out that a decimal will return as
False.  As such, we have tried numerous methods to allow it to divide by a
decimal, all of which have failed.  Do you have any suggestions?
Additionally, we are using 2.7, so that might change your answer.

Thank you in advance for any help you can provide!

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


Re: [Tutor] Dividing a float derived from a string

2014-11-20 Thread Danny Yoo
 I have been posed with the following challenge:

 Create a script that will ask for a number. Check if their input is a
 legitimate number. If it is, multiply it by 12 and print out the result.

 I was able to do this with the following code:

 input = raw_input(Insert a number: )
 if input.isdigit():
 print int(input) * 12
 else:
 print False

 However, a colleague of mine pointed out that a decimal will return as
 False.


Hi Stephanie,


Let me try to reproduce the problem you're reporting.  I'll use the
interactive interpreter to help me.

##
 def f():
... n = raw_input(Insert a number:)
... if n.isdigit():
... print int(n) * 12
... else:
... print False
...
 f()
Insert a number:10
120
###

This is just slightly different than the program you've given me.  I'm
replacing the variable name input with n to avoid potential
confusion, as there is a separate toplevel function called input in
the Python standard library.  I'm also defining it as a function
called f(), just to make it easy for me to call it multiple times.


From the transcript above, I don't think I can see your problem yet.
It would be helpful to present a concrete example of a failure, to
make problem reproduction easier ... oh!  Ah, I see what you're saying
now, I think.

By decimal, you probably don't just mean a number in base-10: you
may mean a number that has a _decimal point_.

##
 f()
Insert a number:3.14
False
##

Is this the problem that you're considering?


If so, you should be able to handle this additional case without too
much trouble.  You're learning how to use conditional statements, and
there's nothing that prevents you from expanding a branch that
considers one possible, to one that considers multiple possibilities:


if blah blah blah:
do some thing
elif blah blah blah:
do something else
else:
do something even more different



You might check, additionally, to see if the string has a decimal
point, and then if it does, check that the left and right hand parts,
before and after the decimal, are all digits.


The find() method on strings can be helpful:


 s = 3141.5926
 s.find(.)
4


If we know where the decimal is, we can start slicing up the string
into the left and right hand sides, using the string slicing operator:

#
 s[0:4]
'3141'
 s[4:]
'.5926'
##


So you can probably adjust your program to check for this possibility.


But to get this right in full generality is surprisingly a _lot_ more
tedious than you might initially expect.  :P  You should really check
with your instructor.  When the problem says number, what does the
problem mean?

This is not as dumb a question as it sounds at first.  As an example
of what can make this complicated: is 3/4 considered a number,
according to the problem statement?  What about scientific notation?
If you're really pedantic (or have a sense of humor), you might even
ask yourself: how about roman numerals?

So you really should touch base with your instructor.  That will
probably help in clarifying what does appear to be a under-defined
term in the problem statement.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dividing a float derived from a string

2014-11-20 Thread Danny Yoo
On Thu, Nov 20, 2014 at 3:05 PM, Stephanie Morrow svmor...@gmail.com wrote:
 What else could I do in that testing portion that would allow for a decimal
 point?  In order for a decimal to be True, it would have to accept both the
 digits and the decimal point.


Let's tackle a problem that's tangent but related, in the sense that
it'll help you practice writing functions that return useful results.

Let's say that we want to write a function on strings that returns
True if the string looks like a sentence.

For the purposes of this example, we'll say that a string looks like a
sentence if it starts with a capital letter, and it ends with a
period.


So we'd like to see:


###
 isSentence(Hello world.)
True
 isSentence(How now blue cow)
False
 isSentence(hi.)
False
 isSentence(Bye!)
False
 isSentence(Gesundheit.)
True
 isSentence()
False
##


Think about how you'd write this.  Try it.  Read the rest below after
you've tried.

















There are a few ways to write out a function definition for
isSentence().  Let me show a few of these.

There are two things we need to check for.

  * The first part of the string has to be uppercased, and
  * The last part of the string has to be a period.

We can express the first condition on a string 's' as the following:

s[0].isupper()

For example:

##
 'fun'[0].isupper()
False
 'Fun'[0].isupper()
True
##


The second condition, that the last part of a string 's' is a period,
can be expressed as:

s[-1] == '.'


Given those two ideas, we can say that something is a sentence if it
fulfills both those expressions.  In short, we can say this with an
and, which takes two expressions and returns True if both of them
are true.


def isSentence(s):
return s[0].isupper() and s[-1] == '.'



We can try this out and see if it's reasonably close.

(Note that I haven't said that it's right.  There's a good reason I'm
not saying that yet.)

#
 isSentence(Howdy.)
True
 isSentence(Sayonara)
False
#


It turns out we can say isSentence() in a few other ways.  We can use
a case analysis:

###
def isSentence(s):
 if s[0].isupper():
if s[-1] == '.':
return True
else:
return False
else:
return False
###

This behaves the same as the one before.  I prefer the earlier because
it reads better to me, and doesn't feel as step-wise.  But this works
too.


Now, there was a caveat before about isSentence not quite being right.
That's because it _presumes_ that there's a first and last character:
that presumption's broken if the string is empty.

##
 isSentence()
Traceback (most recent call last):
  File stdin, line 1, in module
  File stdin, line 2, in isSentence
IndexError: string index out of range
##

Ooops.


So we need to make a revision to what we want to check:

There are _three_ things we need to check for.

   * The string is at least two characters long,
   * The first part of the string has to be uppercased, and
   * The last part of the string has to be a period.


And adding yet another expression to be tested isn't too bad:


##
def isSentence(s):
return len(s) = 2 and s[0].isupper() and s[-1] == '.'
###


This can also be expressed this way:

###
def isSentence(s):
if len(s)  2:
return False
return s[0].isupper() and s[-1] == '.'
###

and you might prefer this, because it's expressed in a way where the
unusual case is set aside apart from the common case.  So it might
read better for human beings.



The reason this is related to the question on recognizing numbers with
a decimal point is because the case analysis is about of equal
complexity.  You need to check for a few things when defining a
function like looksLikeNumber():

   * That the string is all digits.

   or

   * That the string has a decimal point,
   * That the left side of the string is all digits, and
   * That the right side of the string is all digits.

Defining a helper function that does these things is not too bad.  It
does involve either a few conditional statements, or a robust use of
ands and ors.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dividing a float derived from a string

2014-11-20 Thread Stephanie Morrow
What else could I do in that testing portion that would allow for a decimal
point?  In order for a decimal to be True, it would have to accept both the
digits and the decimal point.

On Thu, Nov 20, 2014 at 10:36 PM, Danny Yoo d...@hashcollision.org wrote:

  I have been posed with the following challenge:
 
  Create a script that will ask for a number. Check if their input is a
  legitimate number. If it is, multiply it by 12 and print out the result.
 
  I was able to do this with the following code:
 
  input = raw_input(Insert a number: )
  if input.isdigit():
  print int(input) * 12
  else:
  print False
 
  However, a colleague of mine pointed out that a decimal will return as
  False.


 Hi Stephanie,


 Let me try to reproduce the problem you're reporting.  I'll use the
 interactive interpreter to help me.

 ##
  def f():
 ... n = raw_input(Insert a number:)
 ... if n.isdigit():
 ... print int(n) * 12
 ... else:
 ... print False
 ...
  f()
 Insert a number:10
 120
 ###

 This is just slightly different than the program you've given me.  I'm
 replacing the variable name input with n to avoid potential
 confusion, as there is a separate toplevel function called input in
 the Python standard library.  I'm also defining it as a function
 called f(), just to make it easy for me to call it multiple times.


 From the transcript above, I don't think I can see your problem yet.
 It would be helpful to present a concrete example of a failure, to
 make problem reproduction easier ... oh!  Ah, I see what you're saying
 now, I think.

 By decimal, you probably don't just mean a number in base-10: you
 may mean a number that has a _decimal point_.

 ##
  f()
 Insert a number:3.14
 False
 ##

 Is this the problem that you're considering?


 If so, you should be able to handle this additional case without too
 much trouble.  You're learning how to use conditional statements, and
 there's nothing that prevents you from expanding a branch that
 considers one possible, to one that considers multiple possibilities:

 
 if blah blah blah:
 do some thing
 elif blah blah blah:
 do something else
 else:
 do something even more different
 


 You might check, additionally, to see if the string has a decimal
 point, and then if it does, check that the left and right hand parts,
 before and after the decimal, are all digits.


 The find() method on strings can be helpful:

 
  s = 3141.5926
  s.find(.)
 4
 

 If we know where the decimal is, we can start slicing up the string
 into the left and right hand sides, using the string slicing operator:

 #
  s[0:4]
 '3141'
  s[4:]
 '.5926'
 ##


 So you can probably adjust your program to check for this possibility.


 But to get this right in full generality is surprisingly a _lot_ more
 tedious than you might initially expect.  :P  You should really check
 with your instructor.  When the problem says number, what does the
 problem mean?

 This is not as dumb a question as it sounds at first.  As an example
 of what can make this complicated: is 3/4 considered a number,
 according to the problem statement?  What about scientific notation?
 If you're really pedantic (or have a sense of humor), you might even
 ask yourself: how about roman numerals?

 So you really should touch base with your instructor.  That will
 probably help in clarifying what does appear to be a under-defined
 term in the problem statement.

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


Re: [Tutor] Dividing a float derived from a string

2014-11-20 Thread Alan Gauld

On 20/11/14 21:20, Stephanie Morrow wrote:


input = raw_input(Insert a number: )
if input.isdigit():
 print int(input) * 12
else:
 print False

/However/, a colleague of mine pointed out that a decimal will return as
False.  As such, we have tried numerous methods to allow it to divide by
a decimal, all of which have failed.  Do you have any suggestions?
Additionally, we are using 2.7, so that might change your answer.


The simplest solution is simply to convert it to a floating point number 
instead of an integer. float() can convert both integer and floating 
point(decimals) strings top a floating point number.


But how do you deal with non numbers?
In Python we can use a try/except construct to catch anything that fails 
the conversion:


try:
print float(input)*12
except:
print False

But that's considered bad practice, it's better to put the
valid errors only in the except line like this:

try:
print float(input)*12
except TypeError, ValueError:
print False

So now Python will look out for any ValueErrors and TypeErrors
during the first print operation and if it finds one will instead
print False. Any other kind of error will produce the usual Python error 
messages.


You may not have come across try/except yet, but its a powerful 
technique for dealing with these kinds of issues.



--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my phopto-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Dividing a float derived from a string

2014-11-20 Thread Adam Jensen
#!/usr/bin/env python3.4
good = False
s = input('Enter a number: ')
a = s.split('.')
n = len(a)
if n = 2:
for y in a:
if y.isdigit():
good = True
else:
good = False
exit
else:
good = False
if good:
num = float(s)
print(num * 12)
else:
print('neener neener')


On Thu, 20 Nov 2014 21:20:27 +
Stephanie Morrow svmor...@gmail.com wrote:

 Hi there,
 
 I have been posed with the following challenge:
 
 Create a script that will ask for a number. Check if their input is a
 legitimate number. If it is, multiply it by 12 and print out the result.
 
 I was able to do this with the following code:
 
 input = raw_input(Insert a number: )
 if input.isdigit():
 print int(input) * 12
 else:
 print False
 
 *However*, a colleague of mine pointed out that a decimal will return as
 False.  As such, we have tried numerous methods to allow it to divide by a
 decimal, all of which have failed.  Do you have any suggestions?
 Additionally, we are using 2.7, so that might change your answer.
 
 Thank you in advance for any help you can provide!
 
 -Stephanie
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Data chart

2014-11-20 Thread Adam Jensen
import fileinput

def parseLine(a):
x = a.split('/')
b = x[1].split(':')
c = b[0].split('.')
y = c[0]
z = int(b[2])
return x[0], y, z

print('{:4}{:10}{:8}{:8}'.format('','canofica','lnvd','msd'))

data = [0, 0, 0]
prevDate = None

for line in fileinput.input():
thisDate, name, value = parseLine(line)
if (thisDate != prevDate): 
if (prevDate != None):
print('{:4}{:10}{:8}{:8}'.format(prevDate,
  data[0],data[1],data[2]))
prevDate = thisDate
if name == canofica:
data[0] = value
elif name == lnvd:
data[1] = value
elif name == msd:
data[2] = value
print('{:4}{:10}{:8}{:8}'.format(prevDate,data[0],data[1],data[2]))
fileinput.close()

From: Tutor [mailto:tutor-bounces+hanzer=riseup@python.org] On Behalf Of 
Mamy Rivo DIANZINGA
Sent: Wednesday, November 19, 2014 11:42 AM
To: tutor@python.org
Subject: [Tutor] Data chart

Good morning Sir. Excuse me to bother you but i was wondering if you can help 
me, please Sir. 
I am looking for a script (in python or fortran...) which can turn the data 
from Iter.dat, that i joined for you, into a chart like this:

   canofica   lnvdmsd
10_2 ...  ...
 9_1 ...  ...


I hope i do not exagerate, and i will be very grateful to you if you can help 
me, for any script in python or fortran. Thank in advance.
Best regards.

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


Re: [Tutor] Dividing a float derived from a string

2014-11-20 Thread Adam Jensen
On Thu, 20 Nov 2014 21:20:27 +
Stephanie Morrow svmor...@gmail.com wrote:

 Hi there,
 
 I have been posed with the following challenge:
 
 Create a script that will ask for a number. Check if their input is a
 legitimate number. If it is, multiply it by 12 and print out the result.
 
 I was able to do this with the following code:
 
 input = raw_input(Insert a number: )
 if input.isdigit():
 print int(input) * 12
 else:
 print False
 
 *However*, a colleague of mine pointed out that a decimal will return as
 False.  As such, we have tried numerous methods to allow it to divide by a
 decimal, all of which have failed.  Do you have any suggestions?
 Additionally, we are using 2.7, so that might change your answer.
 
 Thank you in advance for any help you can provide!
 
 -Stephanie

How about using a floating point type cast to convert the string to a number 
within a try/except block? Maybe something like this:

try:
x = float(input(Enter a number: ))
print(x * 12)
except ValueError:
print(Not a valid number.)

A little enhancement might involve removing any spaces from the string so 
something like '5.6 e -3' will also be valid input. Like this:

x = float(input(Enter a number: ).replace(' ',''))
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dividing a float derived from a string

2014-11-20 Thread Steven D'Aprano
My response is interleaved with yours, below.

On Thu, Nov 20, 2014 at 09:20:27PM +, Stephanie Morrow wrote:
 Hi there,
 
 I have been posed with the following challenge:
 
 Create a script that will ask for a number. Check if their input is a
 legitimate number. If it is, multiply it by 12 and print out the result.

The challenge doesn't say what you should do if the input is not a 
number. In your code below, you print False, which is reasonable, but 
just to be different I'm going to print something else.


 I was able to do this with the following code:
 
 input = raw_input(Insert a number: )
 if input.isdigit():
 print int(input) * 12
 else:
 print False

This technique is sometimes called Look Before You Leap -- first you 
look to see whether the input looks like a number, and if it does, you 
convert the string.

But there's another technique, sometimes called Easier to Ask 
Forgiveness than Permission -- first you try converting the string, and 
if it fails, you say sorry.

Here is an attempt using EAFP:

input = raw_input(Enter a number: )
try:
x = float(input)
print 12*x
except ValueError:
print That doesn't look like a number to me.


 *However*, a colleague of mine pointed out that a decimal will return as
 False.  As such, we have tried numerous methods to allow it to divide by a
 decimal, all of which have failed.  Do you have any suggestions?

What makes a valid decimal?

- At most one leading + or - sign.

- At most one decimal point.

- At most one 'e' or 'E' exponent.

- If there is an exponent, it must not have a decimal point 
  itself, and at most one + or - sign immediately after the E.

- There can be spaces in front of the string, or at the
  end of the string, but not in the middle.

- There has to be at least one digit.

- If there is an exponent, there must be at least one
  digit before AND after the exponent.

Have I missed any rules?


E.g. these are valid:

123
123.
+123.4
.5
.5e-7
-1234.567e89

but these are not:

1.2e3.4
123 456
56-78
-.
.e
.e3
123.456.789
1,234,567
1.1f6
abc


That makes it quite hard to check whether a string looks like a valid 
number first. It would be easy to miss some cases which should be 
allowed, or allow some cases which should not be.

Or... we can allow Python to check for us. After all, when you call the 
float() function, Python has to check anyway. So why bother checking 
first? That's doing twice as much work: first you check, then Python 
checks.

Hence the Easier to Ask Forgiveness than Permission approach above.


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


[Tutor] break and exit

2014-11-20 Thread James Rieve
I accidently used 'exit' in a loop where I meant to use 'break' and, in that
case, the program seemed to work as expected but in some cases 'exit' seems
to behave differently from 'break'. For example, in this code snippet using
'exit' or 'break' produces the same result:

for i in range(10):
if i  3:
exit
else:
print(i)
print('out of loop')

But in this case they behave differently:

for i in range(10):
if i  3:
break   # try using exit here.
else:
print(i)
else:
print('for loop else statement')

print('out of loop')

Does anyone have any pointers to descriptions of 'exit', what it is, what it
means, how It's used, etc.?


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


[Tutor] Empty GraphicsWindow

2014-11-20 Thread niyanaxx95
I need help figuring why my GraphicsWindow empty, I cannot figure out why it is 
empty. 

Here is my code :


# Import graphics from module
from graphics import GraphicsWindow


tileSize = 0


def main() :

# Define global variables
tilesInRow = 0
tilesInCol = 0
gapX = 0
gapY = 0

# Input room width
roomWidth = getNumber(100, 500, Enter a room width between 100 and 500: , 
)
roomLength = getNumber(100, 450, Enter a room length between 100 and 450: 
, )
tileSize = getNumber(20, 50, Enter a tile size between 20 and 50: , )

numCols = tilesForSize(roomWidth, tileSize)
print(The total number of Columns:, numCols)
numRows = tilesForSize(roomLength, tileSize)
print(The total number of Rows:, numRows)

# Print the total number of tiles
print(The total number or Tiles: %d %(numCols * numRows))

# Calculate the gap
# the gap = (the total width - the number of tiles * tile width / 2

gapX = calculateGap(roomWidth, numCols)
gapY = calculateGap(roomLength, numRows)

# Print the gaps
print(The gap at each end of a row is: %.1f % (gapX))
print(The gap at each end of a column is: %.1f % (gapY))

# Draw graphics window
win = GraphicsWindow(roomWidth, roomLength)
canvas = win.canvas()

# Draw the checkered surface
for row in range(numRows) :
# If the row is even
if row % 2 == 0 :
# If the column is even set color to black, if odd yellow
drawRow(canvas, row, gapX, numCols, gapY, black, yellow)


# If the row is odd
else:
# If the column is even set color to yellow, if odd black
drawRow(canvas, row, gapX, numCols, gapY, yellow, black)  
  
win.wait()

def getNumber(minBound, maxBound, msg, err_msg) :
num = minBound - 1
while num  minBound or num  maxBound :
if(msg == ) :
num = float(input(Enter a number between %f and %f:  % (minBound, 
maxBound)))
else :
num = float(input(msg))
if num  minBound or num  maxBound :
if err_msg ==  :
print(Invalid input.)   
else:
print(err_msg)
return num


def tilesForSize(size, tileSize) : 
pairs = int(size - tileSize) // int(2 * tileSize)
num = int(1 + (2 * pairs))
return num


def calculateGap(size, num) :
return (size - num * tileSize) / 2


def drawRow(canvas, row, gapX, numCols, gapY, color1, color2) :
for col in range(numCols) :
if col % 2 == 0 :
canvas.setColor(black)
else:
canvas.setColor(yellow)
# Draw the actual rectangle
canvas.drawRect(row * tileSize + gapX, col * tileSize + gapY, tileSize, 
tileSize)
 
 
main ()



























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