[Tutor] While loop homework: was Re: Tutor Digest, Vol 161, Issue 33

2017-07-30 Thread Alan Gauld via Tutor
On 30/07/17 23:36, Borisco Bizaro wrote:

> a=1
> b=2
> while a   input ("enter another price :")

Do 'a' or 'b' ever change?
Does 'a print"\n\n press 0 key to stop"

Does the user ever get the chance to enter a value?
If they were, Where is the value stored and is the
value ever used?

>> When replying, please edit your Subject line so it is more specific
>> than "Re: Contents of Tutor digest..."

Please follow the instructions as requested.
It helps find answers in the archives.


-- 
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 photo-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] While Loop Question

2017-05-11 Thread George Fischhof
2017-05-11 3:53 GMT+02:00 Rafael Skovron :

> Sorry I left out the indents in my previous email. It seems like j is
> always reset to zero. Why does j vary?
>
> Are there two different instances of j going on?
>
>
> for i in range(1, 5):
>
> j=0
>
>while j < i:
>
>  print(j, end = " ")
>
>  j += 1
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



Hi,

As there is a j = 0 statement in the for cycle, it will be set to 0 every
time the while cycle finishes. (The while cycle will then increment j, then
if j == i j will be set to 0 again).

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


Re: [Tutor] While Loop Question

2017-05-11 Thread Steven D'Aprano
On Wed, May 10, 2017 at 06:53:21PM -0700, Rafael Skovron wrote:
> Sorry I left out the indents in my previous email. It seems like j is
> always reset to zero. Why does j vary?

Because you run code that adds 1 to j.


> Are there two different instances of j going on?

No. Try to run the code in your head and see what happens. See below:

> for i in range(1, 5):
> j=0
> while j < i:
>  print(j, end = " ")
>  j += 1

We start by setting i = 1, then the body of the for-loop begins. That 
sets j = 0, and since 0 < 1, we enter the while-loop.

Inside the while-loop, we print j (0), then add 1 to j which makes it 1. 
Then we return to the top of the while-loop. Since 1 is NOT less than 1, 
we exit the while-loop and return to the top of the for-loop.

Now we set i = 2, and continue into the body of the for-loop. That sets 
j = 0 (again!) and since 0 < 2, we enter the while-loop.

Inside the while-loop, we print j (0), then add 1 to j which makes it 1. 
Then we return to the top of the while-loop. Since 1 < 2, we continue 
inside the body, print j (1), then add 1 to j which makes it 2. Since 2 
is not LESS than 2, we exit the while-loop and return to the top of the 
for-loop.

Now we set i = 3, and continue into the body of the for-loop. That sets 
j = 0 (again!) and since 0 < 3, we enter the while-loop.

Inside the while-loop, we follow the same steps and print 0, then 1, 
then 2, then exit the while-loop and return to the top of the for-loop.

Now we set i = 4, and again continue into the while-loop to print 0, 1, 
2 and finally 3, then exit the while-loop and return to the top of the 
for-loop, which is now complete.



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


[Tutor] While Loop Question

2017-05-11 Thread Rafael Skovron
Sorry I left out the indents in my previous email. It seems like j is
always reset to zero. Why does j vary?

Are there two different instances of j going on?


for i in range(1, 5):

j=0

   while j < i:

 print(j, end = " ")

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


Re: [Tutor] While Loop Help

2014-12-11 Thread James Chapman
While Alan has given you a far better solution, I feel someone should
mention the break statement as you will likely come across it a lot, and it
is quite an important flow control statement.

You could add a break statement to the else which would break out of the
while loop.
https://docs.python.org/3.4/reference/simple_stmts.html#break

Refactored to include a break

--

...

the_number = random.randint(1, 100)
win = false
tries = 0
guess = int(input("Take a guess: "))

while tries < 10:
guess = int(input("Take a guess: "))
tries += 1
if guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
else:
win = true
break

if win:
print("You win")
else:
print("You fail! The number was {0}".format(the_number))

input("\n\nPress the enter key to exit.")
--
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loop Help

2014-12-11 Thread Steven D'Aprano
On Wed, Dec 10, 2014 at 11:20:12PM -0500, Matthew Nappi wrote:

> I am working on the challenges from “Python Programming for the Absolute
> Beginner” Chapter 3.  I am asked to modify the original code pasted below
> to limit the number of guesses a player has to guess the number.  I did so
> (code pasted below); however if a player guesses the right number they
> still receive an ending message indicating that they failed.  How can I
> modify the code without using any advanced techniques to have a different
> message in the event of a successful guess?  Thanks in advance!

[...]
> *My Modified Code:*

> import random
> print("\tWelcome to 'Guess My Number'!")
> print("\nI'm thinking of a number between 1 and 100.")
> print("Try to guess it in as few attempts as possible.\n")
> 
> # set the initial values
> the_number = random.randint(1, 100)
> guess = int(input("Take a guess: "))
> tries = 1
> 
> # guessing loop
> while guess != the_number and tries < 10:
> if guess > the_number:
> print("Lower...")
> elif guess < the_number:
> print("Higher...")
> else:
> print("You win.")
> guess = int(input("Take a guess: "))
> tries += 1


Follow the code: start at the top of the while loop. The next thing that 
happens is that the computer checks whether guess > the number, 
otherwise whether guess < the number, otherwise they must be equal. 
Whichever one happens, a message is printed. What happens next?

The next line executes, which says "take a guess". That isn't right, 
since that forces the player to guess even after they've won.

There are a few ways to deal with that. One way would be to change the 
while loop to something like this:


the_number = random.randint(1, 100)
guess = -99   # Guaranteed to not equal the_number.
tries = 0  # Haven't guessed yet.
while guess != the_number and and tries < 10:
tries += 1
guess = int(input("Take a guess: "))
if guess < the_number:
print("too low")
elif guess > the_number:
print("too high")
else:
print("you win!")


Notice how this differs from the earlier version? Instead of asking the 
player to guess at the *end* of the loop, after checking whether the 
guess was right, you ask the player to guess at the *start* of the loop. 
That means you don't need an extra guess at the beginning, and it means 
you don't get an extra, unneeded guess even after you win.

Now let's move on to the next line:

> print("You fail!  The number was", the_number)

This line *always prints*, regardless of whether you have won or not. 
The easiest way to fix that is to just check whether or not the player 
guessed correctly:

if guess != the_number:
print("You fail!  The number was", the_number)


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


Re: [Tutor] While Loop Help

2014-12-11 Thread Alan Gauld

On 11/12/14 04:20, Matthew Nappi wrote:


(code pasted below); however if a player guesses the right number they
still receive an ending message indicating that they failed.  How can I
modify the code without using any advanced techniques to have a different
message in the event of a successful guess?  Thanks in advance!



import random

print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")

the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1

while guess != the_number and tries < 10:
 if guess > the_number:
 print("Lower...")
 elif guess < the_number:
 print("Higher...")
 else:
 print("You win.")
 guess = int(input("Take a guess: "))
 tries += 1


So far so good, except that you probably don;t want
the winner to have to input another number after
being told he already won.

You can avoid that by making the initial value for
guess be something invalid, then move the input
line to the top of the while loop:

guess = 0

while guess != the_number and tries < 10:
guess = int(input("Take a guess: "))
tries += 1
... the if/else code here.


print("You fail!  The number was", the_number)


But you always print this regardless of the result.
You need to put a test around it to check whether
the guess equals the number and only print this
if it is not.


--
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 photo-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


[Tutor] While Loop Help

2014-12-11 Thread Matthew Nappi
Hello All:



I am working on the challenges from “Python Programming for the Absolute
Beginner” Chapter 3.  I am asked to modify the original code pasted below
to limit the number of guesses a player has to guess the number.  I did so
(code pasted below); however if a player guesses the right number they
still receive an ending message indicating that they failed.  How can I
modify the code without using any advanced techniques to have a different
message in the event of a successful guess?  Thanks in advance!



*Original Code:*



# Guess My Number

#

# The computer picks a random number between 1 and 100

# The player tries to guess it and the computer lets

# the player know if the guess is too high, too low

# or right on the money



import random



print("\tWelcome to 'Guess My Number'!")

print("\nI'm thinking of a number between 1 and 100.")

print("Try to guess it in as few attempts as possible.\n")



# set the initial values

the_number = random.randint(1, 100)

guess = int(input("Take a guess: "))

tries = 1



# guessing loop

while guess != the_number:

if guess > the_number:

print("Lower...")

else:

print("Higher...")



guess = int(input("Take a guess: "))

tries += 1



print("You guessed it!  The number was", the_number)

print("And it only took you", tries, "tries!\n")



input("\n\nPress the enter key to exit.")



*My Modified Code:*



# Guess My Number

#

# The computer picks a random number between 1 and 100

# The player tries to guess it and the computer lets

# the player know if the guess is too high, too low

# or right on the money



import random



print("\tWelcome to 'Guess My Number'!")

print("\nI'm thinking of a number between 1 and 100.")

print("Try to guess it in as few attempts as possible.\n")



# set the initial values

the_number = random.randint(1, 100)

guess = int(input("Take a guess: "))

tries = 1



# guessing loop

while guess != the_number and tries < 10:

if guess > the_number:

print("Lower...")

elif guess < the_number:

print("Higher...")

else:

print("You win.")



guess = int(input("Take a guess: "))

tries += 1



print("You fail!  The number was", the_number)



input("\n\nPress the enter key to exit.")
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loop and Threads

2014-07-15 Thread Japhy Bartlett
this construct:


On Tue, Jul 15, 2014 at 5:09 AM, Oğuzhan Öğreden 
wrote:
>
>
> while time_now  < time_finish: # counter and count_until defined
> somewhere above and
> if g_threadStop.is_set() == False:
> # return something or raise an exception to signal
> iteration was interrupted
>
>
 might work better as something like


while (time_now < time_finish) and (not g_threadStop.is_set()):

to avoid the 'interrupt iteration' dilemma
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loop and Threads

2014-07-15 Thread James Chapman
Apologies, I didn't answer your question.

while time_now  < time_finish: # counter and count_until defined
somewhere above and
if g_threadStop.is_set() == False:
# return something

Thread methods are typically void, meaning they return nothing. At least
this is the case in other languages, so I would expect the return to fail.
Also, what would you be returning it to?
Perhaps just a return without a value to indicate exit. (Probably some
reading required here)

Exceptions should be raised when something occurs that you were not
expecting and not used as an exit mechanism for normal operation.

Where to place the timer is up to you. Another thread is an option, but is
it necessary? Overhead needs to be considered.


--
James


On 15 July 2014 14:14, James Chapman  wrote:

> So if I understand this correctly, you want to start a thread and then
> stop it after a certain time period?
>
> Here's an adapted example that includes a timer. (I believe in learning by
> example where possible)
> With that said, if it were my code going into production I'd move the
> timer logic out of the thread and only signal the thread when it should
> exit. Keep the logic within the thread simple and try and make each
> method/function do one thing only. It makes for testable, reusable code.
>
> In my new example
> * The first thread should exit because the time limit is met.
> * The second thread should exit because the Event is set.
>
> Hope this helps...
>
> James
>
>
>
> import time
> import threading
>
> class ThreadExample(object):
>
> def __init__(self):
> self.thread1Stop = threading.Event()
> self.thread2Stop = threading.Event()
> self.timeFinish = time.time() + 12
>
> def threadWorkerOne(self, _arg1, _arg2):
> print("THREAD1 - started with args: %s, %s" % (_arg1, _arg2))
> while(not self.thread1Stop.is_set()):
> while(time.time() < self.timeFinish):
> print("THREAD1 - Running")
> if (self.thread1Stop.is_set()):
> break # Break out of the time while loop
> time.sleep(1)
> if time.time() > self.timeFinish:
> print("THREAD1 - Time limit exceeded")
> self.thread1Stop.set()
> print("THREAD1 - Exiting because thread1Stop is TRUE")
>
> def threadWorkerTwo(self, _arg1, _arg2):
> print("THREAD2 - started with args: %s, %s" % (_arg1, _arg2))
> while(not self.thread2Stop.is_set()):
> while(time.time() < self.timeFinish):
> print("THREAD2 - Running")
> if (self.thread2Stop.is_set()):
> break # Break out of the time while loop
> time.sleep(1)
> if time.time() > self.timeFinish:
> print("THREAD2 - Time limit exceeded")
> self.thread2Stop.set()
> print("THREAD2 - Exiting because thread2Stop is TRUE")
>
> def main(self):
> t1 = threading.Thread(target=self.threadWorkerOne, args = ("arg1",
> "arg2"))
> t1.start()
> t2 = threading.Thread(target=self.threadWorkerTwo, args = ("arg1",
> "arg2"))
> t2.start()
> print("MAIN - sleep(5)")
> time.sleep(5)
> print("MAIN - setting thread1Stop")
> self.thread1Stop.set()
> print("MAIN - sleep(10)")
> time.sleep(10)
> print("MAIN - exiting...")
>
> if __name__ == '__main__':
> runExample = ThreadExample()
> runExample.main()
>
>
>
>
>
>
>
> --
> James
>
>
> On 15 July 2014 11:09, Oğuzhan Öğreden  wrote:
>
>> Thanks!
>>
>> I'll have a side question. If I implement this idea to my case,
>> threadWorker() would look like this:
>>
>>
>> def threadWorker(_arg1, _arg2):
>> print("Starting worker thread with args: %s, %s" % (_arg1, _arg2))
>> while g_threadStop.is_set() == False:
>> ## here comes a for loop:
>> while time_now < time_finish: # time_finish and counter
>> defined somewhere above and
>> print("Thread running.")  # and expression of the
>> condition is intentionally (and necessarily, I believe)
>> counter += 1 # left out of for
>> expression.
>> print(counter)
>> time.sleep(1)
>> print("Thread exiting...")
>>
>> Of course in this case value of g_threadStop.is_set() is not checked
>> until for loop finishes its iteration. Would the suggestion below be a good
>> way to handle the event signal?
>>
>>
>> def threadWorker(_arg1, _arg2):
>> print("Starting worker thread with args: %s, %s" % (_arg1, _arg2))
>> ## here comes a for loop:
>> while time_now  < time_finish: # counter and count_until defined
>> somewhere above and
>> if g_threadStop.is_set() == False:
>> # return something or raise an exception to signal
>> iteration was interrupted
>> print("Thread running.

Re: [Tutor] While Loop and Threads

2014-07-15 Thread James Chapman
So if I understand this correctly, you want to start a thread and then stop
it after a certain time period?

Here's an adapted example that includes a timer. (I believe in learning by
example where possible)
With that said, if it were my code going into production I'd move the timer
logic out of the thread and only signal the thread when it should exit.
Keep the logic within the thread simple and try and make each
method/function do one thing only. It makes for testable, reusable code.

In my new example
* The first thread should exit because the time limit is met.
* The second thread should exit because the Event is set.

Hope this helps...

James



import time
import threading

class ThreadExample(object):

def __init__(self):
self.thread1Stop = threading.Event()
self.thread2Stop = threading.Event()
self.timeFinish = time.time() + 12

def threadWorkerOne(self, _arg1, _arg2):
print("THREAD1 - started with args: %s, %s" % (_arg1, _arg2))
while(not self.thread1Stop.is_set()):
while(time.time() < self.timeFinish):
print("THREAD1 - Running")
if (self.thread1Stop.is_set()):
break # Break out of the time while loop
time.sleep(1)
if time.time() > self.timeFinish:
print("THREAD1 - Time limit exceeded")
self.thread1Stop.set()
print("THREAD1 - Exiting because thread1Stop is TRUE")

def threadWorkerTwo(self, _arg1, _arg2):
print("THREAD2 - started with args: %s, %s" % (_arg1, _arg2))
while(not self.thread2Stop.is_set()):
while(time.time() < self.timeFinish):
print("THREAD2 - Running")
if (self.thread2Stop.is_set()):
break # Break out of the time while loop
time.sleep(1)
if time.time() > self.timeFinish:
print("THREAD2 - Time limit exceeded")
self.thread2Stop.set()
print("THREAD2 - Exiting because thread2Stop is TRUE")

def main(self):
t1 = threading.Thread(target=self.threadWorkerOne, args = ("arg1",
"arg2"))
t1.start()
t2 = threading.Thread(target=self.threadWorkerTwo, args = ("arg1",
"arg2"))
t2.start()
print("MAIN - sleep(5)")
time.sleep(5)
print("MAIN - setting thread1Stop")
self.thread1Stop.set()
print("MAIN - sleep(10)")
time.sleep(10)
print("MAIN - exiting...")

if __name__ == '__main__':
runExample = ThreadExample()
runExample.main()







--
James


On 15 July 2014 11:09, Oğuzhan Öğreden  wrote:

> Thanks!
>
> I'll have a side question. If I implement this idea to my case,
> threadWorker() would look like this:
>
>
> def threadWorker(_arg1, _arg2):
> print("Starting worker thread with args: %s, %s" % (_arg1, _arg2))
> while g_threadStop.is_set() == False:
> ## here comes a for loop:
> while time_now < time_finish: # time_finish and counter
> defined somewhere above and
> print("Thread running.")  # and expression of the
> condition is intentionally (and necessarily, I believe)
> counter += 1 # left out of for
> expression.
> print(counter)
> time.sleep(1)
> print("Thread exiting...")
>
> Of course in this case value of g_threadStop.is_set() is not checked until
> for loop finishes its iteration. Would the suggestion below be a good way
> to handle the event signal?
>
>
> def threadWorker(_arg1, _arg2):
> print("Starting worker thread with args: %s, %s" % (_arg1, _arg2))
> ## here comes a for loop:
> while time_now  < time_finish: # counter and count_until defined
> somewhere above and
> if g_threadStop.is_set() == False:
> # return something or raise an exception to signal
> iteration was interrupted
> print("Thread running.")   # and expression of the condition
> is intentionally (and necessarily, I believe)
> counter += 1  # left out of for expression.
> time.sleep(1)
> print("Iteration done.")
>
> This comes with a problem, due to time.sleep(1), signal is handled with a
> delay. I can think of a work around through GTK:
>
>1. changing (1) to something like while time_now < time_finish -
>actually that is the way it is in original code.
>2. dealing with the counter in the GTK main loop since it's main use
>is for GTK display of the timer.
>
> But let's now follow your advice and leave GTK out for a while and keep
> imagining I want:
>
>1. Command line output for the timer.
>2. Event signal handling without a delay.
>
> I have a felling that 'thread-way of thinking' would come up with another
> thread for counter. Is that correct? If yes, would there be an obvious
> advantage to either using GTK main loop or dealing with another thread?
>
> 

Re: [Tutor] While Loop and Threads

2014-07-15 Thread Oğuzhan Öğreden
Thanks!

I'll have a side question. If I implement this idea to my case,
threadWorker() would look like this:

def threadWorker(_arg1, _arg2):
print("Starting worker thread with args: %s, %s" % (_arg1, _arg2))
while g_threadStop.is_set() == False:
## here comes a for loop:
while time_now < time_finish: # time_finish and counter defined
somewhere above and
print("Thread running.")  # and expression of the
condition is intentionally (and necessarily, I believe)
counter += 1 # left out of for
expression.
print(counter)
time.sleep(1)
print("Thread exiting...")

Of course in this case value of g_threadStop.is_set() is not checked until
for loop finishes its iteration. Would the suggestion below be a good way
to handle the event signal?

def threadWorker(_arg1, _arg2):
print("Starting worker thread with args: %s, %s" % (_arg1, _arg2))
## here comes a for loop:
while time_now  < time_finish: # counter and count_until defined
somewhere above and
if g_threadStop.is_set() == False:
# return something or raise an exception to signal
iteration was interrupted
print("Thread running.")   # and expression of the condition is
intentionally (and necessarily, I believe)
counter += 1  # left out of for expression.
time.sleep(1)
print("Iteration done.")

This comes with a problem, due to time.sleep(1), signal is handled with a
delay. I can think of a work around through GTK:

   1. changing (1) to something like while time_now < time_finish -
   actually that is the way it is in original code.
   2. dealing with the counter in the GTK main loop since it's main use is
   for GTK display of the timer.

But let's now follow your advice and leave GTK out for a while and keep
imagining I want:

   1. Command line output for the timer.
   2. Event signal handling without a delay.

I have a felling that 'thread-way of thinking' would come up with another
thread for counter. Is that correct? If yes, would there be an obvious
advantage to either using GTK main loop or dealing with another thread?

2014-07-14 20:24 GMT+02:00 James Chapman :

> OK, so I mocked up an example now...
>
>
>
> import time
> import threading
>
> g_threadStop = threading.Event()
>
> def threadWorker(_arg1, _arg2):
> print("Starting worker thread with args: %s, %s" % (_arg1, _arg2))
> while(not g_threadStop.is_set()):
> print("Thread running.")
> time.sleep(1)
> print("Thread exiting...")
>
> def main():
> t = threading.Thread(target=threadWorker, args = ("arg1", "arg2"))
> t.start()
> print("Main thread sleeping for 10 seconds...")
> time.sleep(5)
> print("Main thread setting g_threadStop")
> g_threadStop.set()
> time.sleep(3)
> print("Main thread exiting...")
>
> if __name__ == '__main__':
> main()
>
>
>
>
>
> --
> James
>
>
> On 14 July 2014 19:03, James Chapman  wrote:
>
>> Multi-threading takes practice!
>>
>> Are you using an event object to signal the thread should exit? I'm
>> guessing you're just using a bool which is why it does not work.
>>
>> See: https://docs.python.org/3.4/library/threading.html#event-objects
>>
>> I'm very short on time and the moment and therefore can't mock up a
>> working example. If I have time later/tomorrow and you haven't solved it or
>> no one else has commented I'll try and put something together.
>>
>> IMO, move away from GTK until you get threading working as expected, then
>> add the additional layer. Solve one problem at a time.
>>
>> James
>>
>> --
>> James
>>
>>
>> On 13 July 2014 12:23, Oğuzhan Öğreden  wrote:
>>
>>> Hi,
>>>
>>> I've been practicing with multithreading and gtk for a while and
>>> recently have observed something I can't quite grasp.
>>>
>>> This is basically a timer with a settings window and a countdown window
>>> which is produced after setting_window passes necessary arguments to thread.
>>>
>>> I have a while loop which counts time, inside the thread, while variable
>>> "runner" is True, which looks like this:
>>>
>>> def run(self):
>>> cycle = ['work', 'break', 'long_break']
>>> cycle = cycle[:2]*self.workn+cycle[3]
>>> self.runner = True
>>> sec_count = timedelta(seconds=1)
>>>
>>> while self.runner == True:
>>> for i in cycle:
>>> self.setState(i)
>>> print('Start:', i, datetime.now())
>>>
>>> while self.end_time > datetime.now():
>>> time.sleep(1)
>>> self.duration -= sec_count
>>>
>>> self.count[self.state] += 1
>>>
>>> And I want countdown to stop when countdown_window receives delete
>>> event, thus I have a countdown_window.stop() function which is defined as
>>> follows:
>>>
>>> def stop(self, *args):
>>> pom.count[pom.state] -= 1
>>>   

Re: [Tutor] While Loop and Threads

2014-07-14 Thread James Chapman
OK, so I mocked up an example now...



import time
import threading

g_threadStop = threading.Event()

def threadWorker(_arg1, _arg2):
print("Starting worker thread with args: %s, %s" % (_arg1, _arg2))
while(not g_threadStop.is_set()):
print("Thread running.")
time.sleep(1)
print("Thread exiting...")

def main():
t = threading.Thread(target=threadWorker, args = ("arg1", "arg2"))
t.start()
print("Main thread sleeping for 10 seconds...")
time.sleep(5)
print("Main thread setting g_threadStop")
g_threadStop.set()
time.sleep(3)
print("Main thread exiting...")

if __name__ == '__main__':
main()





--
James


On 14 July 2014 19:03, James Chapman  wrote:

> Multi-threading takes practice!
>
> Are you using an event object to signal the thread should exit? I'm
> guessing you're just using a bool which is why it does not work.
>
> See: https://docs.python.org/3.4/library/threading.html#event-objects
>
> I'm very short on time and the moment and therefore can't mock up a
> working example. If I have time later/tomorrow and you haven't solved it or
> no one else has commented I'll try and put something together.
>
> IMO, move away from GTK until you get threading working as expected, then
> add the additional layer. Solve one problem at a time.
>
> James
>
> --
> James
>
>
> On 13 July 2014 12:23, Oğuzhan Öğreden  wrote:
>
>> Hi,
>>
>> I've been practicing with multithreading and gtk for a while and recently
>> have observed something I can't quite grasp.
>>
>> This is basically a timer with a settings window and a countdown window
>> which is produced after setting_window passes necessary arguments to thread.
>>
>> I have a while loop which counts time, inside the thread, while variable
>> "runner" is True, which looks like this:
>>
>> def run(self):
>> cycle = ['work', 'break', 'long_break']
>> cycle = cycle[:2]*self.workn+cycle[3]
>> self.runner = True
>> sec_count = timedelta(seconds=1)
>>
>> while self.runner == True:
>> for i in cycle:
>> self.setState(i)
>> print('Start:', i, datetime.now())
>>
>> while self.end_time > datetime.now():
>> time.sleep(1)
>> self.duration -= sec_count
>>
>> self.count[self.state] += 1
>>
>> And I want countdown to stop when countdown_window receives delete event,
>> thus I have a countdown_window.stop() function which is defined as follows:
>>
>> def stop(self, *args):
>> pom.count[pom.state] -= 1
>> pom.runner = False # refers to the runner of the thread.
>> print(pom.runner) # prints False,
>> Gtk.main_quit()
>>
>> What I expect to happen is that while loop to break, but it does not.
>>
>> Any suggestions?
>>
>> Best,
>> Oğuzhan
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loop and Threads

2014-07-14 Thread James Chapman
Multi-threading takes practice!

Are you using an event object to signal the thread should exit? I'm
guessing you're just using a bool which is why it does not work.

See: https://docs.python.org/3.4/library/threading.html#event-objects

I'm very short on time and the moment and therefore can't mock up a working
example. If I have time later/tomorrow and you haven't solved it or no one
else has commented I'll try and put something together.

IMO, move away from GTK until you get threading working as expected, then
add the additional layer. Solve one problem at a time.

James

--
James


On 13 July 2014 12:23, Oğuzhan Öğreden  wrote:

> Hi,
>
> I've been practicing with multithreading and gtk for a while and recently
> have observed something I can't quite grasp.
>
> This is basically a timer with a settings window and a countdown window
> which is produced after setting_window passes necessary arguments to thread.
>
> I have a while loop which counts time, inside the thread, while variable
> "runner" is True, which looks like this:
>
> def run(self):
> cycle = ['work', 'break', 'long_break']
> cycle = cycle[:2]*self.workn+cycle[3]
> self.runner = True
> sec_count = timedelta(seconds=1)
>
> while self.runner == True:
> for i in cycle:
> self.setState(i)
> print('Start:', i, datetime.now())
>
> while self.end_time > datetime.now():
> time.sleep(1)
> self.duration -= sec_count
>
> self.count[self.state] += 1
>
> And I want countdown to stop when countdown_window receives delete event,
> thus I have a countdown_window.stop() function which is defined as follows:
>
> def stop(self, *args):
> pom.count[pom.state] -= 1
> pom.runner = False # refers to the runner of the thread.
> print(pom.runner) # prints False,
> Gtk.main_quit()
>
> What I expect to happen is that while loop to break, but it does not.
>
> Any suggestions?
>
> Best,
> Oğuzhan
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] While Loop and Threads

2014-07-13 Thread Oğuzhan Öğreden
Hi,

I've been practicing with multithreading and gtk for a while and recently
have observed something I can't quite grasp.

This is basically a timer with a settings window and a countdown window
which is produced after setting_window passes necessary arguments to thread.

I have a while loop which counts time, inside the thread, while variable
"runner" is True, which looks like this:

def run(self):
cycle = ['work', 'break', 'long_break']
cycle = cycle[:2]*self.workn+cycle[3]
self.runner = True
sec_count = timedelta(seconds=1)

while self.runner == True:
for i in cycle:
self.setState(i)
print('Start:', i, datetime.now())

while self.end_time > datetime.now():
time.sleep(1)
self.duration -= sec_count

self.count[self.state] += 1

And I want countdown to stop when countdown_window receives delete event,
thus I have a countdown_window.stop() function which is defined as follows:

def stop(self, *args):
pom.count[pom.state] -= 1
pom.runner = False # refers to the runner of the thread.
print(pom.runner) # prints False,
Gtk.main_quit()

What I expect to happen is that while loop to break, but it does not.

Any suggestions?

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


Re: [Tutor] While loop issue, variable not equal to var or var

2014-07-12 Thread Steven D'Aprano
On Sat, Jul 12, 2014 at 02:39:12PM +0200, Wolfgang Maier wrote:
[...]
> Very interesting advice. Wasn't aware at all of this feature of casefold.
> As a native German speaker, I have to say that your last two examples 
> involving the capital ß are pretty contrived: although the capital ß is 
> part of unicode, it is not an official part of the German alphabet and 
> nobody is using it (in fact, I had to look it up in Wikipedia now to 
> learn what that letter is).

Interestingly, although capital ß is not official, it used to be a lot 
more common than it is now, and never quite disappeared:

http://opentype.info/blog/2011/01/24/capital-sharp-s/


Now that the common fonts provided on Windows support the capital sharp 
s, I wouldn't be surprised if it starts to come back into vogue. 
Typesetters will be at the forefront, since they care about the look of 
things:

http://www.glyphsapp.com/tutorials/localize-your-font-german-capital-sharp-s



> An even better example than the rest of yours would be Kuß (German for 
> the noun kiss), which only people above 30 (like me) still spell this 
> way, but younger people spell Kuss since the official rules have changed 
> over the last 10 years.
> In this particular case, you should definitely be prepared to handle 
> "Kuss" and "Kuß" as legal input.

Good example! Thank you!


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


Re: [Tutor] While loop issue, variable not equal to var or var

2014-07-12 Thread Alan Gauld

On 12/07/14 13:19, Steven D'Aprano wrote:


Because the person might have typed any of:

grosse
große



etc., and you want to accept them all, just like in English


The bit I was missing was that a German user might use the ss version 
instead the ß so testing for either of them alone is insufficient.
lower() or casefold() would deal with the mixed case variations, but 
lower() would not fix the ss v ß issues.


Thanks,

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] While loop issue, variable not equal to var or var

2014-07-12 Thread Wolfgang Maier

On 12.07.2014 14:20, Dave Angel wrote:


I don't remember my high school German enough to remember if the  ß

character is an example,  but in various languages there are
  characters that exist only in uppercase,  and whose lowercase
  equivalent is multiple letters. Or vice versa. And characters
  that have multiple valid spellings in uppercase,  but only one in
  lowercase.

If the latter is true for German,  perhaps GROSSE and GROßE are
  valid uppercase,  but only grosse for lowercase.



No, that's not the case.
Only große is valid lowercase, but many people got so used to computers 
not dealing with ß correctly that they'd type grosse automatically.
Conversely, since there is no official capital form of ß (see my reply 
to Steven), GROSSE is standard uppercase although you might encounter 
GROßE occasionally.


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


Re: [Tutor] While loop issue, variable not equal to var or var

2014-07-12 Thread Wolfgang Maier

On 12.07.2014 14:19, Steven D'Aprano wrote:

On Sat, Jul 12, 2014 at 11:27:17AM +0100, Alan Gauld wrote:

On 12/07/14 10:28, Steven D'Aprano wrote:


If you're using Python 3.3 or higher, it is better to use
message.casefold rather than lower. For English, there's no real
difference:
...
but it can make a difference for non-English languages:

py> "Große".lower()  # German for "great" or "large"
'große'
py> "Große".casefold()
'grosse'


You learn something new etc...

But I'm trying to figure out what difference this makes in
practice?

If you were targeting a German audience wouldn't you just test
against the German alphabet? After all you still have to expect 'grosse'
which isn't English, so if you know to expect grosse
why not just test against große instead?


Because the person might have typed any of:

grosse
GROSSE
gROSSE
große
Große
GROßE
GROẞE

etc., and you want to accept them all, just like in English you'd want
to accept any of GREAT great gREAT Great gReAt etc. Hence you want to
fold everything to a single, known, canonical version. Case-fold will do
that, while lowercasing won't.

(The last example includes a character which might not be visible to
many people, since it is quite unusual and not supported by many fonts
yet. If it looks like a box or empty space for you, it is supposed
to be capital sharp-s, matching the small sharp-s ß.)



Very interesting advice. Wasn't aware at all of this feature of casefold.
As a native German speaker, I have to say that your last two examples 
involving the capital ß are pretty contrived: although the capital ß is 
part of unicode, it is not an official part of the German alphabet and 
nobody is using it (in fact, I had to look it up in Wikipedia now to 
learn what that letter is).
An even better example than the rest of yours would be Kuß (German for 
the noun kiss), which only people above 30 (like me) still spell this 
way, but younger people spell Kuss since the official rules have changed 
over the last 10 years.
In this particular case, you should definitely be prepared to handle 
"Kuss" and "Kuß" as legal input.


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


Re: [Tutor] While loop issue, variable not equal to var or var

2014-07-12 Thread Steve Rodriguez
Thank you guys! Works perfectly! :D

Regards,
Steve Rodriguez


On Sat, Jul 12, 2014 at 1:21 AM, Peter Otten <__pete...@web.de> wrote:

> Peter Otten wrote:
>
> > PS: You sometimes see
> >
> > message in "qQ"
> >
> > but this is buggy as it is true when the message is either
> > "q", "Q", or "qQ".
>
> Oops, I forgot "".
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While loop issue, variable not equal to var or var

2014-07-12 Thread Joseph Lee
Hi Steve,

In your conditionals:

…

while message != 'q' or 'Q'/message != “q” or message != “Q”:
…

Python will only match the first variable. A better approach (which might be a 
good solution) would be capturing the exit commands in a list like this:

JL’s code:

while message not in [“q”, “Q”]:

   # blah, blah, your code…

# code end

Effectively, we’re testing if the command is a member of our exit commands 
list, and if it is, we’ll fall off the loop. Try this solution and see if it 
works for you.

Cheers,

Joseph

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


Re: [Tutor] While loop issue, variable not equal to var or var

2014-07-12 Thread Dave Angel
Steven D'Aprano  Wrote in message:
> On Sat, Jul 12, 2014 at 09:33:20AM +0100, Alan Gauld wrote:
> 
>> 2) Better (IMHO) is to convert message to lower case (or upper if
>> you prefer) and only do one comparison:
>> 
>> while message.lower() != 'q':
> 
> I second this advice, but with a slight modification.
> 
> If you're using Python 3.3 or higher, it is better to use 
> message.casefold rather than lower. For English, there's no real 
> difference:
> 
> py> "Hello World!".casefold()
> 'hello world!'
> 
> 
> but it can make a difference for non-English languages:
> 
> py> "Große".lower()  # German for "great" or "large"
> 'große'
> py> "Große".casefold()
> 'grosse'
> 

I don't remember my high school German enough to remember if the  ß

character is an example,  but in various languages there are
 characters that exist only in uppercase,  and whose lowercase
 equivalent is multiple letters. Or vice versa. And characters
 that have multiple valid spellings in uppercase,  but only one in
 lowercase. 

If the latter is true for German,  perhaps GROSSE and GROßE are
 valid uppercase,  but only grosse for lowercase.
 

-- 
DaveA

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


Re: [Tutor] While loop issue, variable not equal to var or var

2014-07-12 Thread Steven D'Aprano
On Sat, Jul 12, 2014 at 11:27:17AM +0100, Alan Gauld wrote:
> On 12/07/14 10:28, Steven D'Aprano wrote:
> 
> >If you're using Python 3.3 or higher, it is better to use
> >message.casefold rather than lower. For English, there's no real
> >difference:
> >...
> >but it can make a difference for non-English languages:
> >
> >py> "Große".lower()  # German for "great" or "large"
> >'große'
> >py> "Große".casefold()
> >'grosse'
> 
> You learn something new etc...
> 
> But I'm trying to figure out what difference this makes in
> practice?
> 
> If you were targeting a German audience wouldn't you just test
> against the German alphabet? After all you still have to expect 'grosse' 
> which isn't English, so if you know to expect grosse
> why not just test against große instead?

Because the person might have typed any of:

grosse
GROSSE
gROSSE
große
Große
GROßE
GROẞE

etc., and you want to accept them all, just like in English you'd want 
to accept any of GREAT great gREAT Great gReAt etc. Hence you want to 
fold everything to a single, known, canonical version. Case-fold will do 
that, while lowercasing won't.

(The last example includes a character which might not be visible to 
many people, since it is quite unusual and not supported by many fonts 
yet. If it looks like a box or empty space for you, it is supposed 
to be capital sharp-s, matching the small sharp-s ß.)


Oh, here's another example of the difference, this one from Greek:

py> 'Σσς'.lower()  # three versions of sigma
'σσς'
py> 'Σσς'.upper()
'ΣΣΣ'
py> 'Σσς'.casefold()
'σσσ'


I suspect that there probably aren't a large number of languages where 
casefold and lower do something different, since most languages don't 
have distinguish between upper and lower case at all. But there's no 
harm in using it, since at worst it returns the same as lower().


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


Re: [Tutor] While loop issue, variable not equal to var or var

2014-07-12 Thread Alan Gauld

On 12/07/14 10:28, Steven D'Aprano wrote:


If you're using Python 3.3 or higher, it is better to use
message.casefold rather than lower. For English, there's no real
difference:
...
but it can make a difference for non-English languages:

py> "Große".lower()  # German for "great" or "large"
'große'
py> "Große".casefold()
'grosse'


You learn something new etc...

But I'm trying to figure out what difference this makes in
practice?

If you were targeting a German audience wouldn't you just test
against the German alphabet? After all you still have to expect 'grosse' 
which isn't English, so if you know to expect grosse

why not just test against große instead?

I think I'm missing something.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] While loop issue, variable not equal to var or var

2014-07-12 Thread Steven D'Aprano
On Sat, Jul 12, 2014 at 09:33:20AM +0100, Alan Gauld wrote:

> 2) Better (IMHO) is to convert message to lower case (or upper if
> you prefer) and only do one comparison:
> 
> while message.lower() != 'q':

I second this advice, but with a slight modification.

If you're using Python 3.3 or higher, it is better to use 
message.casefold rather than lower. For English, there's no real 
difference:

py> "Hello World!".casefold()
'hello world!'


but it can make a difference for non-English languages:

py> "Große".lower()  # German for "great" or "large"
'große'
py> "Große".casefold()
'grosse'




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


Re: [Tutor] While loop issue, variable not equal to var or var

2014-07-12 Thread Alan Gauld

On 11/07/14 22:16, Steve Rodriguez wrote:

Hey guys n gals,

New to python, having some problems with while loops, I would like to
make a program quick once q or Q is typed, but thus far I can only get
the first variable to be recognized.


> My code looks like:
>
>  message = raw_input("-> ")
>  while message != 'q':

Peter has given a comprehensive reply.

There are two other options he didn't mention.

1) Use 'and' instead of 'or':

while message != 'q' and message != 'Q':

2) Better (IMHO) is to convert message to lower case (or upper if
you prefer) and only do one comparison:

while message.lower() != 'q':


HTH,

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] While loop issue, variable not equal to var or var

2014-07-12 Thread Peter Otten
Peter Otten wrote:

> PS: You sometimes see
> 
> message in "qQ"
> 
> but this is buggy as it is true when the message is either
> "q", "Q", or "qQ".

Oops, I forgot "".

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


Re: [Tutor] While loop issue, variable not equal to var or var

2014-07-12 Thread Peter Otten
Steve Rodriguez wrote:

> Hey guys n gals,
> 
> New to python, having some problems with while loops, I would like to make
> a program quick once q or Q is typed, but thus far I can only get the
> first variable to be recognized. My code looks like:
> 
> message = raw_input("-> ")
> while message != 'q':
> s.send(message)
> data = s.recv(2048)
> print str(data)
> message = raw_input("-> ")
> s.close()
> print("Shutting Down")
> 
> I've tried:
> 
> while message != 'q' or 'Q':

This evaluates 

(message != "q") or "Q"

and "Q" is always True in a boolean context:

>>> bool("Q")
True

> while message != 'q' or message != 'Q':

This is true when at least one of the subexpressions

message != "q"
message != "Q"

is True. When the value of message is "q" it must be unequal to "Q" and vice 
versa, so there is always at least one true subexpression.

> while message != ('q' or 'Q'):

When you try the right side in the interactive interpreter you get

>>> "q" or "Q"
'q'

so this is the same as just 

message != "q" 

> Any ideas would be much appreciated! Thanks! :D

while message.lower() != "q":
while message not in ("q", "Q"):
while message != "q" and message != "Q":

There's another one that chains boolean expressions

while "q" != message != "Q":

that I don't recommend here but that is very readable for checking number 
intervals:

if 0 <= some_number < 1:
   print some_number, "is in the half-open interval [0,1)"


You also may consider an infinite loop:

while True:
message = raw_input("-> ")
if message in ("q", "Q"):
break
s.send(message)
...

This avoids the duplicate raw_input().

PS: You sometimes see

message in "qQ"

but this is buggy as it is true when the message is either
"q", "Q", or "qQ".

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


[Tutor] While loop issue, variable not equal to var or var

2014-07-11 Thread Steve Rodriguez
Hey guys n gals,

New to python, having some problems with while loops, I would like to make
a program quick once q or Q is typed, but thus far I can only get the first
variable to be recognized. My code looks like:

message = raw_input("-> ")
while message != 'q':
s.send(message)
data = s.recv(2048)
print str(data)
message = raw_input("-> ")
s.close()
print("Shutting Down")

I've tried:

while message != 'q' or 'Q':
while message != 'q' or message != 'Q':
while message != ('q' or 'Q'):

Any ideas would be much appreciated! Thanks! :D

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


Re: [Tutor] While Loop?

2014-05-19 Thread Alan Gauld

On 18/05/14 23:44, Sam Ball wrote:


I however would like to add in another line that tells the user their account 
is invalid
before looping around and asking them to re enter their account.


OK, Time to introdusce another Pyhon idioM, the break clause.

while True:   # loop forever
get input from user
check/convert input
if no errors:
   break   # exits the loop
print error message here

"Please Input Your Account Number:")

userAccountNumber = int(userAccount)



As for users typing in a name like "Charlie" or a float I would like that to 
spit out
an error also, but I haven't learned how to accomplish that yet.


The code you have will detect the error and throw an exception.
To stay in the loop you need to catch those exceptions in a try/except 
clause.


while True:
   try:
  get input
  check/convert input
  break
   except error1, error2,:
  print error messages here

If you haven't covered try/except yet then you should read up on it
as it has several variations and subtleties.

HTH

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] While Loop?

2014-05-18 Thread Sam Ball
> Firstly thanks everyone for the help, I definitely learned something. 

> The current version of Python I'm using is actually version 3, sorry for not 
> specifying that earlier. 


> I ended up going with Alan's suggestion and created the below code which 
> works perfectly fine.

> I however would like to add in another line that tells the user their account 
> is invalid

> before looping around and asking them to re enter their account.

>

> userAccount = ''
> while len (userAccount) !=8:
>userAccount = input ("Please Input Your Account Number:")
>userAccountNumber = int(userAccount)

>

>

> As for users typing in a name like "Charlie" or a float I would like that to 
> spit out

> an error also, but I haven't learned how to accomplish that yet.

>

> Thanks again.


----
> Date: Wed, 14 May 2014 16:16:45 -0400
> From: d...@davea.name
> To: tutor@python.org
> Subject: Re: [Tutor] While Loop?
>
> On 05/14/2014 05:45 AM, Sam Ball wrote:
>> I'm attempting to create a program where the user inputs their account 
>> number (which must be 8 digits) and if what the user enters is not 8 digits 
>> in length I want python to tell the user this is invalid and then keep 
>> asking for the account number until a suitable number has been entered.
>> I'm guessing it's a sort of while loop but I'm not 100% sure as I'm quite 
>> new to Python.
>>
>
> Welcome to Python, and to the Tutor mailing list. Please post in text
> form, as the html you're now using is quite error prone, especially
> since this is a text list. There's no errors I can see with your
> present message, but it's a good habit to learn early - tell your email
> program to use "plain text".
>
> Next, it's very important to specify what version of Python you're
> using. In particular there are differences between Python version 2.x
> and version 3.x And those differences affect the input statement.
>
> From your print syntax, it appears you're aiming at Python 2.x But
> it's not valid there either, so it's better if you be explicit in your
> question.
>
>
>> So far I have...
>>
>>
>>
>>
>> userAccountNumber = eval(input("Please Input Your Account Number:"))
>
> Since I'm asssuming Python 2.x, you want int(raw_input( instead.
> input() in 2.x is a security mistake, and eval() is for either version
> of Python.
>
>
>> while userAccountNumber> 1 or <=999:
>
> Syntax error, as you've discovered. Alan has told you how to fix it.
> But it would be much better to get in the habit of quoting the entire
> error message (it's called a traceback) instead of paraphrasing it.
>
>> print userAccountNumber ("Invalid Account Number! Account Must Be Eight 
>> Digits")
>
> Once you've fixed the above, you'll get an error on this line. But how
> to fix it depends on what Python version you're using.
> userAccountNumber isn't a function, so why are you trying to call it?
>
> Next problem is that your loop doesn't ask the user again, it just loops
> around trying to print its error message.
>>
>>
>>
>> When I run this however it gives me an invalid syntax and highlights the = 
>> in <=999:
>>
>> Would appreciate any help with sorting this out.
>>
>
> Once you've gone as far as you can get with these suggestions from Alan,
> Danny, and me, be sure and use reply-list to post your next revision and
> query. (Or, if your email program doesn't support that, use Reply-All,
> and remove from the header everyone you don't want to get the response).
> And of course, you'll tell us what version of Python you're
> taqrgeting. In particular, keep the tutor@python.org recipient.
>
> Once your program works, you need to consider other things, possible
> bugs. For example, what happends if a user types "charlie" instead of
> a number? Or if they type a floating point value? What would you like
> to happen?
>
> --
> DaveA
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loop?

2014-05-14 Thread Dave Angel

On 05/14/2014 05:45 AM, Sam Ball wrote:

I'm attempting to create a program where the user inputs their account number 
(which must be 8 digits) and if what the user enters is not 8 digits in length 
I want python to tell the user this is invalid and then keep asking for the 
account number until a suitable number has been entered.
  I'm guessing it's a sort of while loop but I'm not 100% sure as I'm quite new 
to Python.



Welcome to Python, and to the Tutor mailing list.  Please post in text 
form, as the html you're now using is quite error prone, especially 
since this is a text list.  There's no errors I can see with your 
present message, but it's a good habit to learn early - tell your email 
program to use "plain text".


Next, it's very important to specify what version of Python you're 
using.  In particular there are differences between Python version 2.x 
and version 3.x   And those differences affect the input statement.


From your print syntax, it appears you're aiming at Python 2.x  But 
it's not valid there either, so it's better if you be explicit in your 
question.




So far I have...




userAccountNumber = eval(input("Please Input Your Account Number:"))


Since I'm asssuming Python 2.x, you want   int(raw_input(   instead. 
input() in 2.x is a security mistake, and eval() is for either version 
of Python.




while userAccountNumber > 1 or <=999:


Syntax error, as you've discovered.  Alan has told you how to fix it. 
But it would be much better to get in the habit of quoting the entire 
error message (it's called a traceback) instead of paraphrasing it.



 print userAccountNumber ("Invalid Account Number! Account Must Be Eight 
Digits")


Once you've fixed the above, you'll get an error on this line.  But how 
to fix it depends on what Python version you're using. 
userAccountNumber isn't a function, so why are you trying to call it?


Next problem is that your loop doesn't ask the user again, it just loops 
around trying to print its error message.




When I run this however it gives me an invalid syntax and highlights the = in 
<=999:

Would appreciate any help with sorting this out.



Once you've gone as far as you can get with these suggestions from Alan, 
Danny, and me, be sure and use reply-list to post your next revision and 
query.  (Or, if your email program doesn't support that, use Reply-All, 
and remove from the header everyone you don't want to get the response). 
 And of course, you'll tell us what version of Python you're 
taqrgeting.  In particular, keep the tutor@python.org recipient.


Once your program works, you need to consider other things, possible 
bugs.  For example, what happends if a user types  "charlie" instead of 
a number?  Or if they type a floating point value?  What would you like 
to happen?


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


Re: [Tutor] While Loop?

2014-05-14 Thread Danny Yoo
On Wed, May 14, 2014 at 2:45 AM, Sam Ball  wrote:
> I'm attempting to create a program where the user inputs their account
> number (which must be 8 digits) and if what the user enters is not 8 digits
> in length I want python to tell the user this is invalid and then keep
> asking for the account number until a suitable number has been entered.
>  I'm guessing it's a sort of while loop but I'm not 100% sure as I'm quite
> new to Python.
>
> So far I have...
>
>
>
> userAccountNumber = eval(input("Please Input Your Account Number:"))


Don't use eval here.  If you want to turn a string that's full of
digits into a number, use int()

https://docs.python.org/3/library/functions.html#int

eval() is dangerous.  Don't use it.



> while userAccountNumber > 1 or <=999:
> print userAccountNumber ("Invalid Account Number! Account Must Be Eight
> Digits")
>
> When I run this however it gives me an invalid syntax and highlights the =
> in <=999:
>
> Would appreciate any help with sorting this out.



The compiler is technically correct: it's invalid syntax.

You've written something that scans as English.  But it does not scan
as a Python program.  "or" does not have the English meaning in
Python.

To put it another way: what are you comparing to be less than or equal
to ?  You've left that implicit.  Many programming languages
do not allow implicit statements because it's too easy to
misunderstand or misinterpret.

Make what you're comparing explicit.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loop?

2014-05-14 Thread Alan Gauld

On 14/05/14 10:45, Sam Ball wrote:

I'm attempting to create a program where the user inputs their account
number (which must be 8 digits) and if what the user enters is not 8
digits in length I want python to tell the user this is invalid and then
keep asking for the account number until a suitable number has been entered.
  I'm guessing it's a sort of while loop


You guess correct


userAccountNumber = eval(input("Please Input Your Account Number:"))


But please don;t do this. it is a huge security hole since whatever your 
user enters will be executed as Python code - thats what eval() does. 
Your user can ytype anything in there.


The correct approach is to use raw_input (since you seem to be using 
Pthon v2) and a conversion function such as int() to get the data

type that you want.



while userAccountNumber > 1 or <=999:


Python sees this as:

   while (userAccountNumber > 1) or <=999:

Which makes no sense.

In most programming languages you test this like this:

(userAccountNumber > 1) or (userAccountNumber <= 999):

But in Python you can do these compound checks more
succinctly like this:

> while not (999 < userAccountNumber < 1):

And the other way is to check the length of the input at source:

userAccount = ''
while len(userAccount) != 8:
   userAccount = raw_input("Please Input Your Account Number:")
userAccountNumber = int(userAccount)


HTH

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

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


[Tutor] While Loop?

2014-05-14 Thread Sam Ball
I'm attempting to create a program where the user inputs their account number 
(which must be 8 digits) and if what the user enters is not 8 digits in length 
I want python to tell the user this is invalid and then keep asking for the 
account number until a suitable number has been entered.
 I'm guessing it's a sort of while loop but I'm not 100% sure as I'm quite new 
to Python.
 
So far I have...



 
userAccountNumber = eval(input("Please Input Your Account Number:"))
while userAccountNumber > 1 or <=999:
print userAccountNumber ("Invalid Account Number! Account Must Be Eight 
Digits")
 
 
 
When I run this however it gives me an invalid syntax and highlights the = in 
<=999:
 
Would appreciate any help with sorting this out.
 
Thank you.
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loop

2014-04-01 Thread Alan Gauld

On 01/04/14 00:22, Scott Dunning wrote:


def print_n(s,n):
 i = 0
 while i < n:
 print s,
 i += 1

print_n('a',3)

Also, with this exercise it’s using a doctest so I don’t actually call the 
function


I have no idea what you mean buy this?
There is no doctest above and you do call the function...


so I can’t figure out a way to make the string’s print on

> separate lines without changing the doctest code?

You don't have any doctest code and the printing on one line
is a result of the comma in the print statement.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] while loop

2014-04-01 Thread Dave Angel
 Scott Dunning  Wrote in message:
> 
> On Mar 31, 2014, at 5:15 AM, Dave Angel  wrote:
>> 
>> Do you know how to define and initialize a second local variable? 
>> Create one called i,  with a value zero.
>> 
>> You test expression will not have a literal,  but compare the two
>> locals. And the statement that increments will change i,  not
>> n.
> 
> So like this?  
> def print_n(s,n):
> i = 0
> while i < n:
> print s,
> i += 1
> 
> print_n('a',3)
> 
> So this is basically making i bigger by +1 every time the while loop passes 
> until it passes n, then it becomes false right?  
> 
> Also, with this exercise it’s using a doctest so I don’t actually call 
> the function so I can’t figure out a way to make the string’s print on 
> separate lines without changing the doctest code?  
> 

The trailing comma on the print statement is suppressing the
 newline that's printed by default. If you want them on separate
 lines, get rid of the comma.



-- 
DaveA

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


Re: [Tutor] while loop

2014-04-01 Thread Scott Dunning

On Mar 31, 2014, at 5:15 AM, Dave Angel  wrote:
> 
> Do you know how to define and initialize a second local variable? 
> Create one called i,  with a value zero.
> 
> You test expression will not have a literal,  but compare the two
> locals. And the statement that increments will change i,  not
> n.

So like this?  
def print_n(s,n):
i = 0
while i < n:
print s,
i += 1

print_n('a',3)

So this is basically making i bigger by +1 every time the while loop passes 
until it passes n, then it becomes false right?  

Also, with this exercise it’s using a doctest so I don’t actually call the 
function so I can’t figure out a way to make the string’s print on separate 
lines without changing the doctest code?  

Thanks for all of the help!


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


Re: [Tutor] while loop

2014-03-31 Thread Scott Dunning

On Mar 31, 2014, at 1:39 AM, Mark Lawrence  wrote:
> 
> They say that the truth hurts, so if that's the best you can come up with, I 
> suggest you give up programming :(
You’re in the TUTOR section.  People in here are new to programming.  I’ve only 
been doing this for a couple months and I just learned about while loops two 
days ago.  If my questions are annoying you I suggest you not read them.  : (
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loop

2014-03-31 Thread Scott Dunning

On Mar 31, 2014, at 2:01 AM, Alan Gauld  wrote:

> 
> Incidentally, your assignment does not appear to require
> a while loop, just iteration? If thats the case you could
> use a for loop instead and it would actually be more
> suitable. Have you covered for loops yet?
> 

No, we haven’t got to for loops yet, that’s why it needs to be done with a 
while for now.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loop

2014-03-31 Thread David Rock
* Scott Dunning  [2014-03-30 18:37]:
> Without out a break or placing that 10 in there I can’t think of a way
> to have the while loop stop once it reaches (n).  Any hints?  

As discussed already, you can't use fixed values (ie, you don't know
that 10 is always going to be there).

> def print_n(s, n):
>  
> while n <= 10:
>  
> print s   
>  
> n = n + 1 
>  
>  

So, instead of 

while n <= 10:  
   

Think about:

while something <= n:

and changing something and retesting.

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


Re: [Tutor] while loop

2014-03-31 Thread Dave Angel
 Scott Dunning  Wrote in message:
> 
> On Mar 30, 2014, at 4:29 AM, Dave Angel  wrote:
>> 
>> You're getting closer.   Remember that the assignment shows your
>> function being called with 10, not zero.  So you should have a
>> separate local variable,  probably called I, which starts at
>> zero, and gets incremented each time. 
>> 
>> The test in the while should be comparing them.
>> 
> So, this is what I have now and it ‘works’ but, instead of printing (s) 
> on seperate lines they’re all on the same line?
> 
> def print_n(s,n):
> while n < 10:
> print s * n
> break
> assert isinstance(s, str)
> assert isinstance(n, int)
> 
> 

So much for getting closer.  Go back to the version I replied to. 

Do you know how to define and initialize a second local variable? 
 Create one called i,  with a value zero.

You test expression will not have a literal,  but compare the two
 locals. And the statement that increments will change i,  not
 n.


-- 
DaveA

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


Re: [Tutor] while loop

2014-03-31 Thread Alan Gauld

On 31/03/14 03:13, Scott Dunning wrote:


separate local variable,  probably called I, which starts at
zero, and gets incremented each time.

The test in the while should be comparing them.


So, this is what I have now and it ‘works’


It doesn't work because they are all on the same line.
But also because it does NOT use iteration.
Your while loop is completely redundant. You could
remove the while and break lines and it would do
exactly the same.


def print_n(s,n):
 while n < 10:
 print s * n
 break


You're other attempt where you increment n is much
closer to what is being asked for. The only difference
is you need to modify the while test to not use a hard coded
10 but use the parameter instead. Then use a separate
value to do the counting.

Incidentally, your assignment does not appear to require
a while loop, just iteration? If thats the case you could
use a for loop instead and it would actually be more
suitable. Have you covered for loops yet?


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] while loop

2014-03-31 Thread Alan Gauld

On 31/03/14 02:37, Scott Dunning wrote:


You're getting closer.   Remember that the assignment shows your
function being called with 10, not zero.  So you should have a
separate local variable,  probably called I, which starts at
zero, and gets incremented each time.



Without out a break or placing that 10 in there I can’t think

> of a way to have the while loop stop once it reaches (n).

Dave has explained in his first paragraph(above) how to do it.
n is a parameter in your function so the value is passed in
by the caller. You should not be using a literal 10 you should
be using n, since that's the required number of repeats.

Then you need to create a new local variable in your function
and let that variable count up until it equals whatever n is.
That's where the iteration comes in. And as you count
up, towards n, print s.

hth
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] while loop

2014-03-31 Thread Mark Lawrence

On 31/03/2014 03:13, Scott Dunning wrote:


On Mar 30, 2014, at 4:29 AM, Dave Angel  wrote:


You're getting closer.   Remember that the assignment shows your
function being called with 10, not zero.  So you should have a
separate local variable,  probably called I, which starts at
zero, and gets incremented each time.

The test in the while should be comparing them.


So, this is what I have now and it ‘works’ but, instead of printing (s) on 
seperate lines they’re all on the same line?

def print_n(s,n):
 while n < 10:
 print s * n
 break
 assert isinstance(s, str)
 assert isinstance(n, int)



They say that the truth hurts, so if that's the best you can come up 
with, I suggest you give up programming :(


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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: [Tutor] while loop

2014-03-31 Thread Scott Dunning

On Mar 30, 2014, at 4:29 AM, Dave Angel  wrote:
> 
> You're getting closer.   Remember that the assignment shows your
> function being called with 10, not zero.  So you should have a
> separate local variable,  probably called I, which starts at
> zero, and gets incremented each time. 
> 
> The test in the while should be comparing them.
> 
So, this is what I have now and it ‘works’ but, instead of printing (s) on 
seperate lines they’re all on the same line?

def print_n(s,n):
while n < 10:
print s * n
break
assert isinstance(s, str)
assert isinstance(n, int)


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


Re: [Tutor] while loop

2014-03-31 Thread Scott Dunning

On Mar 30, 2014, at 4:29 AM, Dave Angel  wrote:
> 
> 
> You're getting closer.   Remember that the assignment shows your
> function being called with 10, not zero.  So you should have a
> separate local variable,  probably called I, which starts at
> zero, and gets incremented each time. 
The exercise just asks to print (s), (n) times using iteration.  The exersise 
is in a doctest which I didn’t really understand at first.  So, I guess while I 
was doing it “correctly” it wasn’t what the exercise is asking for.  This I 
guess is what the doctest is looking for.

"""Print the string `s`, `n` times.

Parameters
--
s -- A string
n -- an integer, the number of times to
 print `s'

Examples


>>> print_n("hello", 3)
hello
hello
hello

>>> print_n("bye", 0)

>>> print_n("a", 6)
a
a
a
a
a
a

"""
> 
> The test in the while should be comparing them.
> 
> Note that the number of times is specified in top level code, and
> implemented in the function.  You should not have a literal 10 in
> the function. 
Without out a break or placing that 10 in there I can’t think of a way to have 
the while loop stop once it reaches (n).  Any hints?  

SCott 








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


Re: [Tutor] while loop

2014-03-30 Thread Dave Angel
 Scott Dunning  Wrote in message:
> 
> On Mar 29, 2014, at 12:47 AM, Dave Angel  wrote:
>> 
>> So did your code print the string 10 times?  When asking for help,
>> it's useful to show what you tried,  and what was expected,  and
>> what actually resulted. 
>> 
>> You use * to replicate the string,  but that wasn't what the
>> assignment asked for. So take out the *n part. You're supposed to
>> use iteration,  specifically the while loop. 
>> 
>> Your while loop doesn't quit after 10 times, it keeps going.  Can
>> you figure out why?
> 
> This works without a break.  Is this more a long the line of what the 
> excercise was looking for you think?
>> 
> def print_n(s, n):
> while n <= 10:
> print s
> n = n + 1
> 
> print_n("hello\n", 0)
>
> 
> 


You're getting closer.   Remember that the assignment shows your
 function being called with 10, not zero.  So you should have a
 separate local variable,  probably called I, which starts at
 zero, and gets incremented each time. 

The test in the while should be comparing them.

Note that the number of times is specified in top level code, and
 implemented in the function.  You should not have a literal 10 in
 the function. 
-- 
DaveA

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


Re: [Tutor] while loop

2014-03-30 Thread Alan Gauld

On 30/03/14 02:36, Scott Dunning wrote:


Your while loop doesn't quit after 10 times, it keeps going.  Can
you figure out why?


This works without a break.

> Is this more a long the line of what the excercise was
> looking for you think?

Yes.


 while n <= 10:
 print s
 n = n + 1


Python while loops effectively come in two patterns:

1) while some condition
  do stuff
  modify the test condition

2) while True:
  if some condition:
 break
  else
 do stuff


The first version is actually the intended use of while from a computing 
science point of view.


The second one, which creates an infinite loop and then breaks
out of it is a bit of a kluge which pure structured programming
theory says is bad practice. It has become idiomatic in Python
however, because it often avoids another bad practice, namely
repeating yourself.

For example if we only used the first pattern we often
need to do this:

display_menu()
choice = input('pick a choice: ')
while choice != 'quit':
if choice == 'save':
   do_save()
elif choice == ...
display_menu()
choice = input('pick a choice: ')

Notice how we have to have the menu/input pair
both before and inside the loop.

We can avoid that using the infinite loop version:

while True:
display_menu()
choice = input('pick a choice: ')
if choice == 'quit'
   break
elif choice == 'save':
   do_save()
elif choice == ...

So we have effectively chosen the lesser of two evils.
Compromising on computer science purity is not unusual
in the real world of programming.

In your example there was no need to repeat code so
you could use the uncompromised, pure while loop with
an effective test condition. In that case you can and
should modify the test condition variables inside
the loop, which is what you did with the n = n+1 line.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] while loop

2014-03-30 Thread Scott Dunning

On Mar 29, 2014, at 12:47 AM, Dave Angel  wrote:
> 
> So did your code print the string 10 times?  When asking for help,
> it's useful to show what you tried,  and what was expected,  and
> what actually resulted. 
> 
> You use * to replicate the string,  but that wasn't what the
> assignment asked for. So take out the *n part. You're supposed to
> use iteration,  specifically the while loop. 
> 
> Your while loop doesn't quit after 10 times, it keeps going.  Can
> you figure out why?

This works without a break.  Is this more a long the line of what the excercise 
was looking for you think?
> 
def print_n(s, n):
while n <= 10:
print s
n = n + 1

print_n("hello\n", 0)


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


Re: [Tutor] while loop

2014-03-30 Thread Scott Dunning

On Mar 29, 2014, at 12:47 AM, Dave Angel  wrote:
> 
> What are you uncertain about,  assert or isinstance?  Such
> statements are frequently used to make sure the function
> arguments are of the right type. 
I’m not sure exactly what it’s doing.  I guess I need to read up on it again.
> 
>> 
>> 
>> This is what I have so far but I’m not really sure it’s what the excersise 
>> is asking for?
>> 
>> n = 5
>> def print_n(s, n):
>>   while n > 0:
>>   print s * n
>> 
>> print_n("hello", 10)
>> 
> 
> So did your code print the string 10 times?  When asking for help,
> it's useful to show what you tried,  and what was expected,  and
> what actually resulted. 
Yes it repeated forever, I put a break after the print statement.  
> 
> You use * to replicate the string,  but that wasn't what the
> assignment asked for. So take out the *n part. You're supposed to
> use iteration,  specifically the while loop. 
That’s where I was confused, I wasn’t sure how to get the while loop to work 
just the n times and then stop.
> 
> Your while loop doesn't quit after 10 times, it keeps going.  Can
> you figure out why?
> 
I understand why it didn’t stop after 10 times, because I said while n is 
greater than 0 print s, and I have the value of n as 5 so it will never stop, 
that’s why I added a break after the print statement.  I’m sure there is a 
better way , I’m just not seeing it.  Any hints?  


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


Re: [Tutor] while loop

2014-03-30 Thread Scott Dunning

On Mar 28, 2014, at 10:36 PM, Ben Finney  wrote:
> 
> A good programming exercise will show an example input and the expected
> output, to give an unambiguous test case. Does the homework have that?
This is what the exercise has as examples…


"""Print the string `s`, `n` times.

Parameters
--
s -- A string
n -- an integer, the number of times to
 print `s'

Examples


>>> print_n("hello", 3)
hello
hello
hello

>>> print_n("bye", 0)

>>> print_n("a", 6)
a
a
a
a
a
a

"""
assert isinstance(s, str)
assert isinstance(n, int)

#TODO: Implement the function

> 
> If not, you're unfortunately left to your own interpretation of what the
> requirements mean.
> 
I’m not sure what assert isinstance means?  

This is what I have, it works but I’m not sure it’s what the exercise is asking 
for.

n = 5
def print_n(s, n):
while n > 0:
print s * n
break

print_n("hello\n", 10)



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


Re: [Tutor] while loop

2014-03-29 Thread Dave Angel
 Scott W Dunning  Wrote in message:
> 
> On Mar 28, 2014, at 9:54 PM, Scott W Dunning  wrote:
> 
>> Hello, I’m working on some practice exercises from my homework and I’m 
>> having some issues figuring out what is wanted.  
>> 
>> We’re working with the while loop and this is what the question states;
>> 
>> Write a function print_n that prints a string n times using iteration.
>> 
>>  """Print the string `s`, `n` times. 
>> 
>> 
>> This is also in the exercises and I’m not sure what it means and why 
>> it’s there.
>> 
>> assert isinstance(s, str)
>> assert isinstance(n, int)

What are you uncertain about,  assert or isinstance?  Such
 statements are frequently used to make sure the function
 arguments are of the right type. 

>
> 
> This is what I have so far but I’m not really sure it’s what the 
> excersise is asking for?
> 
> n = 5
> def print_n(s, n):
>while n > 0:
>print s * n
> 
> print_n("hello", 10)
> 

So did your code print the string 10 times?  When asking for help,
 it's useful to show what you tried,  and what was expected,  and
 what actually resulted. 

You use * to replicate the string,  but that wasn't what the
 assignment asked for. So take out the *n part. You're supposed to
 use iteration,  specifically the while loop. 

Your while loop doesn't quit after 10 times, it keeps going.  Can
 you figure out why?



-- 
DaveA

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


Re: [Tutor] while loop

2014-03-28 Thread Jay Lozier


On 03/29/2014 01:18 AM, Scott W Dunning wrote:

On Mar 28, 2014, at 9:54 PM, Scott W Dunning  wrote:


Hello, I’m working on some practice exercises from my homework and I’m having 
some issues figuring out what is wanted.

We’re working with the while loop and this is what the question states;

Write a function print_n that prints a string n times using iteration.

"""Print the string `s`, `n` times.


This is also in the exercises and I’m not sure what it means and why it’s there.

assert isinstance(s, str)
assert isinstance(n, int)


Any help is greatly appreciated!

Scott

This is what I have so far but I’m not really sure it’s what the excersise is 
asking for?

n = 5
def print_n(s, n):
while n > 0:
print s * n

print_n("hello", 10)


Scott,

Are required to use a while loop?

Two ways to solve this, while loop and for in range loop

while loop
n = 5
s = 'some string'

def while_print(s, n):
index = o
while index < n:
print(index, s)
index += 1

def alternative_print(s, n):
for index in range(0, n):
print(index, s)

The while loop requires that a counter variable or some loop exit 
condition so you do not end up in an endless loop. This is a common 
problem with while loops in programming, not just Python. So, if there 
is alternative method of looping available, good programming practice is 
to avoid a while loop in any language. The for loop version 
automatically iterates over the range from 0 to n-1 (5 times). I 
included the index variable in the print to show the increase of the index.


The results for both:
0 some string
1 some string
2 some string
3 some string
4 some string

--
Jay Lozier
jsloz...@gmail.com

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


[Tutor] while loop

2014-03-28 Thread Scott W Dunning
Hello, I’m working on some practice exercises from my homework and I’m having 
some issues figuring out what is wanted.  

We’re working with the while loop and this is what the question states;

Write a function print_n that prints a string n times using iteration.

"""Print the string `s`, `n` times. 


This is also in the exercises and I’m not sure what it means and why it’s there.

assert isinstance(s, str)
assert isinstance(n, int)


Any help is greatly appreciated!

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


Re: [Tutor] while loop

2014-03-28 Thread Ben Finney
Scott W Dunning  writes:

> On Mar 28, 2014, at 9:54 PM, Scott W Dunning  wrote:
>
> > We’re working with the while loop and this is what the question states;
> > 
> > Write a function print_n that prints a string n times using iteration.
> This is what I have so far but I’m not really sure it’s what the
> excersise is asking for?

A good programming exercise will show an example input and the expected
output, to give an unambiguous test case. Does the homework have that?

If not, you're unfortunately left to your own interpretation of what the
requirements mean.

-- 
 \ “Truth would quickly cease to become stranger than fiction, |
  `\ once we got as used to it.” —Henry L. Mencken |
_o__)  |
Ben Finney

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


Re: [Tutor] while loop

2014-03-28 Thread Scott W Dunning

On Mar 28, 2014, at 9:54 PM, Scott W Dunning  wrote:

> Hello, I’m working on some practice exercises from my homework and I’m having 
> some issues figuring out what is wanted.  
> 
> We’re working with the while loop and this is what the question states;
> 
> Write a function print_n that prints a string n times using iteration.
> 
>   """Print the string `s`, `n` times. 
> 
> 
> This is also in the exercises and I’m not sure what it means and why it’s 
> there.
> 
> assert isinstance(s, str)
> assert isinstance(n, int)
> 
> 
> Any help is greatly appreciated!
> 
> Scott

This is what I have so far but I’m not really sure it’s what the excersise is 
asking for?

n = 5
def print_n(s, n):
   while n > 0:
   print s * n

print_n("hello", 10)


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


Re: [Tutor] While loop

2013-04-06 Thread Sayan Chatterjee
# skip 5
if count == 5:
continue # means "Jump back to the top of the looop"

It is the reason. You yourself have mentioned it right inside the code!


On 7 April 2013 09:40, Dave Angel  wrote:

> On 04/06/2013 11:23 PM, Najam Us Saqib wrote:
>
>> Hi,
>>
>> Would you please help me by explaining that why " 5 " is skipped and not
>> printed in the following program?
>>
>>
> Seems to me the comments say it pretty well.  The continue statement
> causes execution to continue at the while statement, which has the effect
> of skipping the print.  Like Monopoly:  go directly to jail, do not pass go.
>
>
>  Thank you.
>> Najam.
>>
>> count = 0
>> while True:
>>  count += 1
>>  # end loop if count is greater than 10
>>  if count > 10:
>>  break # means "break out of the loop"
>>  # skip 5
>>  if count == 5:
>>  continue # means "Jump back to the top of the looop"
>>  print count
>>
>> raw_input("\n\nPress the enter key to exit.")
>>
>> Output:
>>
>> 1
>> 2
>> 3
>> 4
>> 6
>> 7
>> 8
>> 9
>> 10
>>
>>
>> Press the enter key to exit.
>>
>
> Incidentally, this looks like a transliteration of something written for
> some other language.  An experienced Python programmer would never write it
> this way.
>
> I'd use something like (untested):
>
> for count in xrange(11):
> if count != 5:
> print count
>
> On the other hand, a course --teaching a C programmer to use Python--
> might well use this as an early example, showing you later how much
> elegantly it can be done.
>
>
> --
> DaveA
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>



-- 


--
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While loop

2013-04-06 Thread Dave Angel

On 04/06/2013 11:23 PM, Najam Us Saqib wrote:

Hi,

Would you please help me by explaining that why " 5 " is skipped and not 
printed in the following program?



Seems to me the comments say it pretty well.  The continue statement 
causes execution to continue at the while statement, which has the 
effect of skipping the print.  Like Monopoly:  go directly to jail, do 
not pass go.




Thank you.
Najam.

count = 0
while True:
 count += 1
 # end loop if count is greater than 10
 if count > 10:
 break # means "break out of the loop"
 # skip 5
 if count == 5:
 continue # means "Jump back to the top of the looop"
 print count

raw_input("\n\nPress the enter key to exit.")

Output:

1
2
3
4
6
7
8
9
10


Press the enter key to exit.


Incidentally, this looks like a transliteration of something written for 
some other language.  An experienced Python programmer would never write 
it this way.


I'd use something like (untested):

for count in xrange(11):
if count != 5:
print count

On the other hand, a course --teaching a C programmer to use Python-- 
might well use this as an early example, showing you later how much 
elegantly it can be done.



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


Re: [Tutor] While loop

2013-04-06 Thread Dave Angel

On 04/06/2013 11:23 PM, Najam Us Saqib wrote:

Hi,

Would you please help me by explaining that why " 5 " is skipped and not 
printed in the following program?



Seems to me the comments say it pretty well.  The continue statement 
causes execution to continue at the while statement, which has the 
effect of skipping the print.  Like Monopoly:  go directly to jail, do 
not pass go.




Thank you.
Najam.

count = 0
while True:
 count += 1
 # end loop if count is greater than 10
 if count > 10:
 break # means "break out of the loop"
 # skip 5
 if count == 5:
 continue # means "Jump back to the top of the looop"
 print count

raw_input("\n\nPress the enter key to exit.")

Output:

1
2
3
4
6
7
8
9
10


Press the enter key to exit.


Incidentally, this looks like a transliteration of something written for 
some other language.  An experienced Python programmer would never write 
it this way.


I'd use something like (untested):

for count in xrange(11):
if count != 5:
print count

On the other hand, a course --teaching a C programmer to use Python-- 
might well use this as an early example, showing you later how much 
elegantly it can be done.



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


[Tutor] While loop

2013-04-06 Thread Najam Us Saqib
Hi,

Would you please help me by explaining that why " 5 " is skipped and not 
printed in the following program?

Thank you.
Najam.

count = 0
while True:
    count += 1
    # end loop if count is greater than 10
    if count > 10:
        break # means "break out of the loop"
    # skip 5
    if count == 5:
        continue # means "Jump back to the top of the looop"
    print count

raw_input("\n\nPress the enter key to exit.")

Output:

1
2
3
4
6
7
8
9
10


Press the enter key to exit.___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While Loop

2012-06-12 Thread Dave Angel
On 06/13/2012 01:29 AM, Andrew Brunn wrote:
> Let me preface by saying that I am currently taking my first programming
>  class; so I have been a "programmer" for just over a week now.
>
> Here is my question;
>
> I
>  am trying to create a while loop that will allow me ask for a username 
> and password.  If a wrong username and password is entered, I would like
>  the program to prompt the user to re-enter the username and password 
> until they get it correct.  That means even if they get it wrong a 
> thousand times, I want to program to keep asking them.
>
> This is my code;
>
> [code]
> username = ""
>
> while not username:
> username=raw_input("Username: ")
>
> password = ""
>
> while not password:
>
>  password=raw_input("Password: ")
> if username == "john doe" and password == "fopwpo":
> print "Login successful"
> else:
> print "Error. Please re-enter your username and password."
> [code]
>
>
>
> Andy Brunn
>

So put the whole thing in a while loop.  For that matter, also put it in
a function.  Anything over about 3 lines should be written as one or
more functions.

The simplest change would be to make the while loop look likewhile
True:, and put a break right after the print "Login successful" line,

def  getUserPass():
while True
 (existing code here)
 if username == "" and password == "":
   print "login successful"
   break
  else:
   print "Error:  Please "



-- 

DaveA

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


[Tutor] While Loop

2012-06-12 Thread Andrew Brunn
Let me preface by saying that I am currently taking my first programming
 class; so I have been a "programmer" for just over a week now.

Here is my question;

I
 am trying to create a while loop that will allow me ask for a username 
and password.  If a wrong username and password is entered, I would like
 the program to prompt the user to re-enter the username and password 
until they get it correct.  That means even if they get it wrong a 
thousand times, I want to program to keep asking them.

This is my code;

[code]
username = ""

while not username:
    username=raw_input("Username: ")
   
password = ""

while not password:
   
 password=raw_input("Password: ")
if username == "john doe" and password == "fopwpo":
    print "Login successful"
else:
    print "Error. Please re-enter your username and password."
[code]



Andy Brunn___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loop ends prematurly

2012-01-02 Thread Walter Prins
Hi again,

On 2 January 2012 06:28, Steven D'Aprano  wrote:
>> Another answer is to use Decimal class, which CAN represent decimal values
>> exactly.
>
>
> That only applies to decimal values which can be represented using a fixed
> number of decimal places. So 1/5 is fine, and is 0.2 exactly, but 1/3 is
> not, since it would require an infinite number of decimal places.

It's occurred to me that I should've probably used the term "exact
decimal" in my comment, so please read it as such.  (The general class
of decimals include 3 types of decimals: exact, recurring and
non-recurring.  Generally when people use the word decimal they tend
to mean "exact decimals".  Apologies for not being clearer.)

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


Re: [Tutor] while loop ends prematurly

2012-01-02 Thread Dave Angel
(You accidentally forgot to include the list when you replied.  The 
easiest way (for most people) to avoid that is to use Reply-all)


On 01/02/2012 01:00 AM, Sarma Tangirala wrote:

On 2 Jan 2012 08:56, "Dave Angel"  wrote:


Easiest answer is to use integers.  Scale everything up by a factor of

100, and you won't need floats at all.  Just convert when printing (and
even then you may get into trouble).

Just to add a bit here. I've seen a couple of people do it this way -
subtract the two numbers and check if the result is above a particular
threshold value, and if so they are not equal.

That was also in that Fortran reference from '67.  The trick on that is 
to subtract, and compare the absolute value to an epsilon value.


if abs(a-b)< threshold:
equals-logic goes here
else:
unequals-logic goes here

It can get tricky to pick a good threshold. In this case, a thousandth 
of a penny is clearly enough.  But for many programs the threshold also 
has to be calculated.


In APL, this comparison logic is automated, via a concept called fuzz. 
You typically specify the fuzz value once, and the threshold is 
automatically calculated by something like multiplying fuzz by the 
larger (in absolute value) of the two numbers being compared.


These approaches are also tricky, and when they fail, debugging them can 
be very difficult.




Another answer is to use Decimal class, which CAN represent decimal

values exactly.





When I implemented the microcode math package for a processor (which 
predated microprocessors like the 8080 and 8086), it was all decimal. 
We had decimal logic in the hardware for adding two-digit integers, 
everything more complicated was a loop in the microcode.  With that 
system, if you printed out a value, you saw an exact equivalent of what 
was stored internally.


--

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


Re: [Tutor] while loop ends prematurly

2012-01-02 Thread Walter Prins
Hi Steven,

On 2 January 2012 06:28, Steven D'Aprano  wrote:
> That only applies to decimal values which can be represented using a fixed
> number of decimal places. So 1/5 is fine, and is 0.2 exactly, but 1/3 is
> not, since it would require an infinite number of decimal places.

Just a small nit pick with the above:  1/3 is however not a decimal
number.   The word decimal means "tenth part", decimal numbers are
generally defined/understood as numbers that are expressible as
decimal fractions, meaning numbers where the denominator is a power of
10 or is an exact "tenth part".  Understood as such, decimal numbers
are therefore obviously accurately representable by the Decimal class
which is the whole point of calling the class "Decimal".

To backtrack slightly, numbers like 1/3, 1/5 etc are in general called
common or vulgar fractions, the only requirement being that they have
an integer numerator and an integer non-zero denominator.  The class
of numbers representible like this is called rational numbers and the
test for whether a number can be called rational is whether it can be
written as such.

The set of numbers we refer to as decimal numbers then, are a subset
of rational numbers, the test for whether they can be called decimal
being whether they can be written as a rational number with the
additional requirement that the denominator be a power of ten.
Addtionally, any rational number with a denominator of which the prime
factors are 2 and 5 may therefore be rewritten as a decimal number,
thus we know that 2/5 can also be accurately represented by a decimal
number (since the prime factors of 5 is 5), as can 1/50 (since the
prime factors of 50 are 2,5,5), but 1/3 can not, since 3 has only 3 as
its prime factor (and not 2 or 5), and neither 1/24 (since the prime
factors are 2,2,2,3).  So an additional test for whether a given
rational number can be accurately rewritten as a decimal (tenth part)
number, is to inspect the prime factors of the denominator.  If this
consists solely of 2's and 5's it can be expressed as a decimal, if
any other factors are present then it cannot be accurately expressed
as a decimal.

A happy and prosperous 2012 to all,

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


Re: [Tutor] while loop ends prematurly

2012-01-01 Thread Steven D'Aprano

Dave Angel wrote:

Easiest answer is to use integers.  Scale everything up by a factor of 
100, and you won't need floats at all.  Just convert when printing (and 
even then you may get into trouble).


Another answer is to use Decimal class, which CAN represent decimal 
values exactly.


That only applies to decimal values which can be represented using a fixed 
number of decimal places. So 1/5 is fine, and is 0.2 exactly, but 1/3 is not, 
since it would require an infinite number of decimal places.


BTW, if this is supposed to represent US legal tender, you left out the 
fifty-cent piece as well as the two dollar bill.


http://kowb1290.com/our-two-cents-on-the-two-dollar-bill/



--
Steven

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


Re: [Tutor] while loop ends prematurly

2012-01-01 Thread Hugo Arts
On Mon, Jan 2, 2012 at 3:48 AM, brian arb  wrote:
> Hello,
> Can some please explain this to me?
> My while loop should continue while "owed" is greater than or equal to "d"
>
> first time the function is called
> the loop exits as expected
> False: 0.00 >= 0.01
> the next time it does not
> False: 0.01 >= 0.01
>
> Below is the snippet of code, and the out put.
>
> Thanks!
>
> def make_change(arg):
>   denom = [100.0, 50.0, 20.0, 10.0, 5.0, 1.0, 0.25, 0.10, 0.05, 0.01]
>   owed = float(arg)
>   payed = []
>   for d in denom:
>     while owed >= d:
>       owed -= d
>       b = owed >= d
>       print '%s: %f >= %f' % (b, owed, d)
>       payed.append(d)
>   print sum(payed), payed
>   return sum(payed)
>
> if __name__ == '__main__':
>   values = [21.48, 487.69] #, 974.41, 920.87, 377.93, 885.12, 263.47,
> 630.91, 433.23, 800.58]
>   for i in values:
>     make_change(i))
>
>
> False: 1.48 >= 20.00
> False: 0.48 >= 1.00
> False: 0.23 >= 0.25
> True: 0.13 >= 0.10
> False: 0.03 >= 0.10
> True: 0.02 >= 0.01
> True: 0.01 >= 0.01
> False: 0.00 >= 0.01
> 21.48 [20.0, 1.0, 0.25, 0.1, 0.1, 0.01, 0.01, 0.01]
> True: 387.69 >= 100.00
> True: 287.69 >= 100.00
> True: 187.69 >= 100.00
> False: 87.69 >= 100.00
> False: 37.69 >= 50.00
> False: 17.69 >= 20.00
> False: 7.69 >= 10.00
> False: 2.69 >= 5.00
> True: 1.69 >= 1.00
> False: 0.69 >= 1.00
> True: 0.44 >= 0.25
> False: 0.19 >= 0.25
> False: 0.09 >= 0.10
> False: 0.04 >= 0.05
> True: 0.03 >= 0.01
> True: 0.02 >= 0.01
> False: 0.01 >= 0.01
> 487.68 [100.0, 100.0, 100.0, 100.0, 50.0, 20.0, 10.0, 5.0, 1.0, 1.0, 0.25,
> 0.25, 0.1, 0.05, 0.01, 0.01, 0.01]
>

What happened is that you ran into the weirdness that we call the IEEE
754-2008 standard, otherwise known as floating point numbers. in quite
simple terms, the way the computer represents floating point numbers
means that inaccuracies sneak in when performing math on them, and
some numbers can't even be represented correctly, like 0.1. You can
notice this in some of the simplest calculations:

>>> 0.1
0.1
>>> # seems normal? Well, python is actually tricking you. Let's force it to 
>>> show us this number with some more accuracy:
>>> "%.32f" % 0.1 # force it to show 32 digits after the period
'0.1555111512312578'
>>> # whoops! that's not quite 0.1 at all! let's try some more:
>>> 9 * 0.1
0.9
>>> 0.9
0.9
>>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1
0.8999
>>> "%.32f" % 0.9
'0.90002220446049250313'
>>> # what?! those aren't even the same numbers!!
>>> 0.1 + 0.2
0.30004
>>> # what the hell?

Usually this doesn't really matter, because we don't really care about
what happens after you get way far into the decimal spaces. But when
you compare for equality, which is what you're doing here, this stuff
can bite you in the ass real ugly. If you replace the %f with %.32f in
that debugging statement, you'll see why the loop bails:

False: 0.0077 >= 0.0100

That kinda sucks, doesn't it? floating point errors are hard to find,
especially since python hides them from you sometimes. But there is a
simple solution! Multiply all numbers by 100 inside that function and
then simply work with integers, where you do get perfect accuracy.

HTH,
Hugo

P.S.: this problem is not in inherent to python but to the IEEE
standard. The sacrifice in accuracy was made deliberately to keep
floating point numbers fast, so it's by design and not something that
should be "fixed." Pretty much all languages that use floats or
doubles have the same thing. If you really want decimal numbers, there
is a Decimal class in Python that implements 100% accurate decimal
numbers at the cost of performance. Look it up.

P.P.S.: for more information you should read these. The first link is
a simple explanation. The second is more complicated, but obligatory
reading material for every programmer worth his salts:
the floating point guide: http://floating-point-gui.de/
what every computer scientist should know about floating-point
arithmetic: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loop ends prematurly

2012-01-01 Thread Dave Angel

On 01/01/2012 09:48 PM, brian arb wrote:

Hello,
Can some please explain this to me?
My while loop should continue while "owed" is greater than or equal to "d"

first time the function is called
the loop exits as expected
False: 0.00>= 0.01
the next time it does not
False: 0.01>= 0.01

Below is the snippet of code, and the out put.

Thanks!

def make_change(arg):
   denom = [100.0, 50.0, 20.0, 10.0, 5.0, 1.0, 0.25, 0.10, 0.05, 0.01]
   owed = float(arg)
   payed = []
   for d in denom:
 while owed>= d:
   owed -= d
   b = owed>= d
   print '%s: %f>= %f' % (b, owed, d)
   payed.append(d)
   print sum(payed), payed
   return sum(payed)

if __name__ == '__main__':
   values = [21.48, 487.69] #, 974.41, 920.87, 377.93, 885.12, 263.47,
630.91, 433.23, 800.58]
   for i in values:
 make_change(i))


False: 1.48>= 20.00
False: 0.48>= 1.00
False: 0.23>= 0.25
True: 0.13>= 0.10
False: 0.03>= 0.10
True: 0.02>= 0.01
True: 0.01>= 0.01
False: 0.00>= 0.01
21.48 [20.0, 1.0, 0.25, 0.1, 0.1, 0.01, 0.01, 0.01]
True: 387.69>= 100.00
True: 287.69>= 100.00
True: 187.69>= 100.00
False: 87.69>= 100.00
False: 37.69>= 50.00
False: 17.69>= 20.00
False: 7.69>= 10.00
False: 2.69>= 5.00
True: 1.69>= 1.00
False: 0.69>= 1.00
True: 0.44>= 0.25
False: 0.19>= 0.25
False: 0.09>= 0.10
False: 0.04>= 0.05
True: 0.03>= 0.01
True: 0.02>= 0.01
False: 0.01>= 0.01
487.68 [100.0, 100.0, 100.0, 100.0, 50.0, 20.0, 10.0, 5.0, 1.0, 1.0, 0.25,
0.25, 0.1, 0.05, 0.01, 0.01, 0.01]

You're using float values and pretending that they can accurately 
represent dollars and cents. 0.19 (for example) cannot be exactly 
represented in a float, and when you start adding up multiple of these, 
sooner or later the error will become visible.  This is a problem with 
binary floating point, and I first encountered it in 1967, when the 
textbook for Fortran made an important point about never comparing 
floating point values for equals, as small invisible errors are bound to 
bite you.


Easiest answer is to use integers.  Scale everything up by a factor of 
100, and you won't need floats at all.  Just convert when printing (and 
even then you may get into trouble).


Another answer is to use Decimal class, which CAN represent decimal 
values exactly.


BTW, if this is supposed to represent US legal tender, you left out the 
fifty-cent piece as well as the two dollar bill.


--

DaveA

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


[Tutor] while loop ends prematurly

2012-01-01 Thread brian arb
Hello,
Can some please explain this to me?
My while loop should continue while "owed" is greater than or equal to "d"

first time the function is called
the loop exits as expected
False: 0.00 >= 0.01
the next time it does not
False: 0.01 >= 0.01

Below is the snippet of code, and the out put.

Thanks!

def make_change(arg):
  denom = [100.0, 50.0, 20.0, 10.0, 5.0, 1.0, 0.25, 0.10, 0.05, 0.01]
  owed = float(arg)
  payed = []
  for d in denom:
while owed >= d:
  owed -= d
  b = owed >= d
  print '%s: %f >= %f' % (b, owed, d)
  payed.append(d)
  print sum(payed), payed
  return sum(payed)

if __name__ == '__main__':
  values = [21.48, 487.69] #, 974.41, 920.87, 377.93, 885.12, 263.47,
630.91, 433.23, 800.58]
  for i in values:
make_change(i))


False: 1.48 >= 20.00
False: 0.48 >= 1.00
False: 0.23 >= 0.25
True: 0.13 >= 0.10
False: 0.03 >= 0.10
True: 0.02 >= 0.01
True: 0.01 >= 0.01
False: 0.00 >= 0.01
21.48 [20.0, 1.0, 0.25, 0.1, 0.1, 0.01, 0.01, 0.01]
True: 387.69 >= 100.00
True: 287.69 >= 100.00
True: 187.69 >= 100.00
False: 87.69 >= 100.00
False: 37.69 >= 50.00
False: 17.69 >= 20.00
False: 7.69 >= 10.00
False: 2.69 >= 5.00
True: 1.69 >= 1.00
False: 0.69 >= 1.00
True: 0.44 >= 0.25
False: 0.19 >= 0.25
False: 0.09 >= 0.10
False: 0.04 >= 0.05
True: 0.03 >= 0.01
True: 0.02 >= 0.01
False: 0.01 >= 0.01
487.68 [100.0, 100.0, 100.0, 100.0, 50.0, 20.0, 10.0, 5.0, 1.0, 1.0, 0.25,
0.25, 0.1, 0.05, 0.01, 0.01, 0.01]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loop problem

2009-03-08 Thread Lie Ryan

mustafa akkoc wrote:
hello i have syntax problem in this program 







After correcting the indentations, and putting a missing parentheses in 
line 24 (the last line), I don't see any Syntax Error.


#!/usr/bin/python
# Filename: while.py
number = 23
running = True

while running :
guess= int(input('Enter an integer : '))  # it give a syntax error 
this line can you me ?


if guess == number:
print('Congratulations, you guessed it.')
running = False # this causes the while loop to stop

elif guess < number:
print('No, it is a little higher than that.')

else:
print('No, it is a little lower than that.')

else:
print('The while loop is over.')

# Do anything else you want to do here
print('Done')  # you missed a paren, probably CopyPasteError

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loop problem

2009-03-08 Thread Alan Gauld


"mustafa akkoc"  wrote


hello i have syntax problem in this program
#!/usr/bin/python
# Filename: while.py
number = 23
running = True

while running :
guess= input('Enter an integer : ')  # it give a syntax error this 
line can

you me ?


Always post the full text of error messages please. It helps us a lot.

Howevbder in this case I suspect the problem is that you do not
seem to have indented the line under the while loop (although that
may be due to email reformatting issues...) But that should say
IndentationError not Syntax error?

Also you don;t say what version of Python you are using.
input() has changed slightly in v3...

HTH,

Alan G. 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] while loop problem

2009-03-08 Thread mustafa akkoc
hello i have syntax problem in this program
#!/usr/bin/python
# Filename: while.py
number = 23
running = True

while running :
guess= input('Enter an integer : ')  # it give a syntax error this line can
you me ?

if guess == number:
print('Congratulations, you guessed it.')
running = False # this causes the while loop to stop

elif guess < number:
print('No, it is a little higher than that.')

else:
print('No, it is a little lower than that.')

else:
print('The while loop is over.')

# Do anything else you want to do here
print('Done'


-- 
Mustafa Akkoc
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While loop counter

2008-07-07 Thread David

Thank you John & Allen,

See the loops section of my tutorial for more about for
and while loops.

Yes, great tutorial, just getting it to sink in, now thats the problem :)

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While loop counter

2008-07-07 Thread Alan Gauld

"David" <[EMAIL PROTECTED]> wrote

Hi, I am trying to get a while loop that will execute 5 time then 
stop.


Copngratulations, you have succeeded.
Unfortunately nothing happens inside your loop. I suspect you
actually want to execute some code 5 times?


#counter = 0
#while counter < 5 :
#counter = counter + 1


Yep, this would have done it.


while True:
   mytime.tick()
   mytime.print_time()
   time.sleep(1) # Sleep for 1 second


And this loop runs forever because you never break
out of it.


counter = 0
while counter < 5 :
   counter = counter + 1


If you did get out of the infinite loop above then  this one does do 
it too.
But all it does is increment the counter. If you want code to be 
executed

it must also be inside the loop (ie inside the indented code section).

So what I think you wanted would be:

counter = 0
while counter < 5:
   mytime.tick()
   mytime.print_time()
   time.sleep(1) # Sleep for 1 second
   counter = counter + 1

But since its for a fixed number of iterations you are better
off using a for loop:

for counter in range(5)
   mytime.tick()
   mytime.print_time()
   time.sleep(1) # Sleep for 1 second

Note we don't need to increment the counter in this version.

See the loops section of my tutorial for more about for
and while loops.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While loop counter

2008-07-07 Thread John Fouhy
On 08/07/2008, David <[EMAIL PROTECTED]> wrote:
> Hi, I am trying to get a while loop that will execute 5 time then stop.

Hi David,

The standard pattern is like this:

i = 0
while i < 5:
# the stuff you want to do goes here
i = i + 1

Note that if you know exactly how many times you will execute your
loop, you should use a for loop instead:

for i in range(5):
# the stuff you want to do goes here

HTH!

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] While loop counter

2008-07-07 Thread David

Hi, I am trying to get a while loop that will execute 5 time then stop.

#!/usr/bin/python
# Filename myfirstclass.py
#
# A Little digital clock

from time_class import Time
import sys
import time

mytime = Time()

print "Can you tell me the time (24h)?"
hour = input("Give the hour: ")
minute = input("Give the minutes: ")
second = input("Give the seconds: ")

mytime.set_time(hour, minute, second)
#counter = 0
#while counter < 5 :
#counter = counter + 1
while True:
   mytime.tick()
   mytime.print_time()
   time.sleep(1) # Sleep for 1 second
counter = 0
while counter < 5 :
   counter = counter + 1

Here is the class;

#!/usr/bin/python
# Filename: time_class.py

class Time:

   def __init__(self):
   self.__hour = 0
   self.__minute = 0
   self.__second = 0

   def set_time(self, hour, minute, second):
   self.set_hour(hour)
   self.set_minute(minute)
   self.set_second(second)

   def set_hour(self, hour):
   if 0 <= hour and hour < 24:
   self.__hour = hour

   def set_minute(self, minute):
   if 0 <= minute and minute < 60:
 self.__minute = minute
  
   def set_second(self, second):

   if 0 <= second and second < 60:
   self.__second = second

   def tick(self):
   self.__second += 1
   self.__minute += self.__second / 60
   self.__hour += self.__minute / 60
  
   self.__hour = self.__hour % 24

   self.__minute = self.__minute % 60
   self.__second = self.__second % 60
  
  
   def print_time(self):

   print '%02d:%02d:%02d' % (self.__hour, self.__minute, self.__second)

Thanks, very new to Python.
-david

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while Loop

2007-07-26 Thread Mike Hansen
> -Original Message-
> Subject: Re: [Tutor] while Loop
> 
> Oops, didn't notice the uppercase U, thanks Luke.
> 
> - Original Message - 
> Subject: Re: [Tutor] while Loop
> 
> 
> >> define it with usedPocketsOne = 192000?
> > no, I said UsedPocketsOne was not defined.  Note the 
> different starting 
> > letter.
> > Python is case senstitive, meaning usedPocketsOne is not 
> the same as 
> > UsedPocketsOne.
> > So yes, you defined usedPocketsOne with the assignment to 
> 192000, but 
> > you did not define UsedPocketsOne.
> > 

I've been out of the office for the last week, so I'm catching up.

You might use something like PyChecker, PyLint, or PyFlakes. Those
utilities would catch errors like this.

I have a hotkey in VIM that kicks off PyFlakes on the current buffer. 

Also, I'm not 100% sure, but I think Komodo IDE would catch this as
well.

Mike
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while Loop

2007-07-18 Thread Darren Williams
Oops, didn't notice the uppercase U, thanks Luke.

- Original Message - 
From: "Luke Paireepinart" <[EMAIL PROTECTED]>
To: "Darren Williams" <[EMAIL PROTECTED]>
Cc: 
Sent: Wednesday, July 18, 2007 3:08 PM
Subject: Re: [Tutor] while Loop


> Darren Williams wrote:
>> Luke and Kent, you're right, I didn't think JavaScript calculated 
>> multiplaction and division before addition and subtraction but seems 
>> it does :)
>>
>> I dunno what you mean about usedPocketsOne not being defined, didn't I 
>> define it with usedPocketsOne = 192000?
> no, I said UsedPocketsOne was not defined.  Note the different starting 
> letter.
> Python is case senstitive, meaning usedPocketsOne is not the same as 
> UsedPocketsOne.
> So yes, you defined usedPocketsOne with the assignment to 192000, but 
> you did not define UsedPocketsOne.
> 
> Note what happens when I test your code:
> >>> def main():
> 
> usedPocketsOne = 192000
> junkiesOne = 500
> labSpaceOne = 0
> 
> resultOne = 0
> while usedPocketsOne > (junkiesOne - labSpaceOne) * 17:
> resultOne = resultOne + 1
> usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17
> 
>
> >>> main()
> 
> Traceback (most recent call last):
>  File "", line 1, in -toplevel-
>main()
>  File "", line 10, in main
>usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17
> NameError: global name 'UsedPocketsOne' is not defined
> 
> You should get a similar error, unless you've somehow defined 
> UsedPocketsOne somewhere else.
> HTH,
> -Luke
> 
> Correction of previous e-mail: This raises a NameError, not a 
> SyntaxError, as I said before.  sorry about that.
> 
> 
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while Loop

2007-07-18 Thread Luke Paireepinart
Darren Williams wrote:
> Luke and Kent, you're right, I didn't think JavaScript calculated 
> multiplaction and division before addition and subtraction but seems 
> it does :)
>
> I dunno what you mean about usedPocketsOne not being defined, didn't I 
> define it with usedPocketsOne = 192000?
no, I said UsedPocketsOne was not defined.  Note the different starting 
letter.
Python is case senstitive, meaning usedPocketsOne is not the same as 
UsedPocketsOne.
So yes, you defined usedPocketsOne with the assignment to 192000, but 
you did not define UsedPocketsOne.

Note what happens when I test your code:
 >>> def main():

 usedPocketsOne = 192000
 junkiesOne = 500
 labSpaceOne = 0
 
 resultOne = 0
 while usedPocketsOne > (junkiesOne - labSpaceOne) * 17:
 resultOne = resultOne + 1
 usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17


 >>> main()

Traceback (most recent call last):
  File "", line 1, in -toplevel-
main()
  File "", line 10, in main
usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17
NameError: global name 'UsedPocketsOne' is not defined

You should get a similar error, unless you've somehow defined 
UsedPocketsOne somewhere else.
HTH,
-Luke

Correction of previous e-mail: This raises a NameError, not a 
SyntaxError, as I said before.  sorry about that.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while Loop

2007-07-18 Thread Darren Williams
Luke and Kent, you're right, I didn't think JavaScript calculated 
multiplaction and division before addition and subtraction but seems it does 
:)

I dunno what you mean about usedPocketsOne not being defined, didn't I 
define it with usedPocketsOne = 192000?

- Original Message - 
From: "Luke Paireepinart" <[EMAIL PROTECTED]>
To: "Darren Williams" <[EMAIL PROTECTED]>
Cc: 
Sent: Wednesday, July 18, 2007 11:57 AM
Subject: Re: [Tutor] while Loop


> Darren Williams wrote:
>> Hi all,
>>  I'm writing a calculator for an online game that I used to play but 
>> don't seem to be able to break out of the while loop, the program will 
>> just go over and over the loop, crashing the program and I don't know if 
>> Python is just really slow at this type of thing or i'm doing it 
>> completely wrong in Python (the equivalent code in JavaScript works 
>> fine).
> I don't think you're doing it completely wrong, just partially :)
> And I doubt that, if it's quick in Javascript, it will be any slower in 
> Python, since Javascript is interpreted as well, but by the browser while 
> it's simultaneously downloading the content of the webpage and rendering 
> it to the screen.
> Also, I'm pretty sure the code here is not equivalent to the Javascript 
> code you included (specific remarks below.)
>>  Python code -
>>  def main():
>> usedPocketsOne = 192000
>> junkiesOne = 500
>> labSpaceOne = 0
>>  resultOne = 0
>> while usedPocketsOne > (junkiesOne - labSpaceOne) * 17:
> I don't know much about Javascript, but doesn't it have order of 
> operations?
> For example,
> usedPocketsOne > junkiesOne - labSpaceOne * 17
> is generally assumed to be
> x = labSpaceOne * 17
> y = junkiesOne - x
> usedPocketsOne > y
>
>
> Whereas your Python equivalent, with the parenthesis,
> usedPocketsOne > (junkiesOne - labSpaceOne) * 17
>
> changes the order of operations (forces the subtraction before the 
> multiplication)
> and hence changes the resulting value.  That is, unless Javascript 
> evaluates left-to-right with no operator heirarchy (which I would be 
> saddened to learn, if it's true.)
>> resultOne = resultOne + 1
>> usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17
> This shouldn't even run - you should get a syntax error because 
> UsedPocketsOne is not defined anywhere else in the program (that you've 
> shown us.)
> Perhaps you're running it in IDLE with no subprocess and some value for 
> UsedPocketsOne is hanging around (from previous edits of the program, or 
> interpreter session, or something else) and mucking up the works?
> -Luke
>
>
> 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while Loop

2007-07-18 Thread Luke Paireepinart
Darren Williams wrote:
> Hi all,
>  
> I'm writing a calculator for an online game that I used to play but 
> don't seem to be able to break out of the while loop, the program will 
> just go over and over the loop, crashing the program and I don't know 
> if Python is just really slow at this type of thing or i'm doing it 
> completely wrong in Python (the equivalent code in JavaScript works fine).
I don't think you're doing it completely wrong, just partially :)
And I doubt that, if it's quick in Javascript, it will be any slower in 
Python, since Javascript is interpreted as well, but by the browser 
while it's simultaneously downloading the content of the webpage and 
rendering it to the screen.
Also, I'm pretty sure the code here is not equivalent to the Javascript 
code you included (specific remarks below.)
>  
> Python code -
>  
> def main():
> usedPocketsOne = 192000
> junkiesOne = 500
> labSpaceOne = 0
>  
> resultOne = 0
> while usedPocketsOne > (junkiesOne - labSpaceOne) * 17:
I don't know much about Javascript, but doesn't it have order of operations?
For example,
usedPocketsOne > junkiesOne - labSpaceOne * 17
is generally assumed to be
x = labSpaceOne * 17
y = junkiesOne - x
usedPocketsOne > y


Whereas your Python equivalent, with the parenthesis,
usedPocketsOne > (junkiesOne - labSpaceOne) * 17

changes the order of operations (forces the subtraction before the 
multiplication)
and hence changes the resulting value.  That is, unless Javascript 
evaluates left-to-right with no operator heirarchy (which I would be 
saddened to learn, if it's true.)
> resultOne = resultOne + 1
> usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17
This shouldn't even run - you should get a syntax error because 
UsedPocketsOne is not defined anywhere else in the program (that you've 
shown us.)
Perhaps you're running it in IDLE with no subprocess and some value for 
UsedPocketsOne is hanging around (from previous edits of the program, or 
interpreter session, or something else) and mucking up the works?
-Luke


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while Loop

2007-07-18 Thread Kent Johnson
Darren Williams wrote:
> Hi all,
>  
> I'm writing a calculator for an online game that I used to play but 
> don't seem to be able to break out of the while loop, the program will 
> just go over and over the loop, crashing the program and I don't know if 
> Python is just really slow at this type of thing or i'm doing it 
> completely wrong in Python (the equivalent code in JavaScript works fine).
>  
> Python code -
>  
> def main():
> usedPocketsOne = 192000
> junkiesOne = 500
> labSpaceOne = 0
>  
> resultOne = 0
> while usedPocketsOne > (junkiesOne - labSpaceOne) * 17:
> resultOne = resultOne + 1
> usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17

Maybe this should be
  usedPocketsOne = UsedPocketsOne - junkiesOne + labSpaceOne * 17

which is what you have in the JS.

Kent

> junkiesOne = junkiesOne + 1
>  
> main()
>  
> And the JavaScript equivalent (incase there are any stalwarts beside 
> Alan here) -
>  
> function main() {
> var usedPocketsOne = 192000
> var junkiesOne = 500
> var labSpaceOne = 0
>  
> var resultOne = 0
> while (usedPocketsOne > junkiesOne - labSpaceOne * 17) {
> resultOne = resultOne + 1
> usedPocketsOne = usedPocketsOne - junkiesOne + labSpaceOne * 17
> junkiesOne = junkiesOne + 1
> }
> }
>  
> Thanks in advance for any help :)
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] while Loop

2007-07-18 Thread Darren Williams
Hi all,

I'm writing a calculator for an online game that I used to play but don't seem 
to be able to break out of the while loop, the program will just go over and 
over the loop, crashing the program and I don't know if Python is just really 
slow at this type of thing or i'm doing it completely wrong in Python (the 
equivalent code in JavaScript works fine).

Python code -

def main():
usedPocketsOne = 192000
junkiesOne = 500
labSpaceOne = 0

resultOne = 0
while usedPocketsOne > (junkiesOne - labSpaceOne) * 17:
resultOne = resultOne + 1
usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17
junkiesOne = junkiesOne + 1

main()

And the JavaScript equivalent (incase there are any stalwarts beside Alan here) 
-
 
function main() {
var usedPocketsOne = 192000
var junkiesOne = 500
var labSpaceOne = 0

var resultOne = 0
while (usedPocketsOne > junkiesOne - labSpaceOne * 17) {
resultOne = resultOne + 1
usedPocketsOne = usedPocketsOne - junkiesOne + labSpaceOne * 17
junkiesOne = junkiesOne + 1
}
}

Thanks in advance for any help :)___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "while" loop for satisfing two conditions , advice requested

2006-01-15 Thread Pujo Aji
in understanding while loop someone should understand "if conditional" first.In "If conditional" there are common relational symbol "and" and "or"Let's discuss  "and" conditional
Condition 1 Condition 2  ResultTrue    True    TrueTrue    False  FalseFalse  True    False
False  False  FalseIn short, and equal True if and only if both condition are true."If the while loop result condition  is true it will execute its block."
example:x = 1y = 1while x==1 and y==1: # it will be processed if x==1 and y==1 are both true, in this case it is!another example:x=1y=2while x==1 and y==1:

 # it will be processed if x==1 and y==1 are both true, in this case it is not!
Hope this help!pujoOn 1/15/06, John Joseph <[EMAIL PROTECTED]> wrote:
Hi   I am trying to use "while" loop  , here I wantwhile loop to check for two conditions , I  am notgetting an idea  how to use "while" loop for  checkingtwo conditionsI  used "&" condition , but it is not
giving me the expected resultsI used in this way while (condition no 1) & (condition no2):print "Results" I request guidanceThanks
 Joseph John___NEW Yahoo! Cars - sell your car and browse thousands of new and used cars online! 
http://uk.cars.yahoo.com/___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "while" loop for satisfing two conditions ,

2006-01-15 Thread Kent Johnson
> From: John Joseph <[EMAIL PROTECTED]>

>I am trying to use “while” loop  , here I want
> while loop to check for two conditions , I  am not
> getting an idea  how to use “while” loop for  checking
> two conditions 
> I  used "&" condition , but it is not
> giving me the expected results 
> I used in this way 
>   
>  while (condition no 1) & (condition no2):
>   print “Results” 

Use 'and' instead of &. & is a bitwise logical AND - it operates on the 
individual bits of its arguments. 'and' treats the full operand as a logical 
value. The results can be different:
 >>> [1] & [2]
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unsupported operand type(s) for &: 'list' and 'list'
 >>> [1] and [2]
[2]
 >>> 2 & 1
0
 >>> 2 and 1
1

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "while" loop for satisfing two conditions , advice requested

2006-01-15 Thread Carlo Capuano
Hi

>while (condition no 1) & (condition no2):
>   print "Results"
> 

While (condition no 1) and (condition no2):
print "Results"


in python you use the words

and, or, not, is

like:

if myvar1 is not None and myvar2 == '1':
 print 'what a nice snowing day!'

Carlo
 
what is ITER? www.iter.org

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] "while" loop for satisfing two conditions , advice requested

2006-01-15 Thread John Joseph
Hi 
   I am trying to use “while” loop  , here I want
while loop to check for two conditions , I  am not
getting an idea  how to use “while” loop for  checking
two conditions 
I  used "&" condition , but it is not
giving me the expected results 
I used in this way 
  
 while (condition no 1) & (condition no2):
print “Results” 

 I request guidance 
Thanks 
 Joseph John 




___ 
NEW Yahoo! Cars - sell your car and browse thousands of new and used cars 
online! http://uk.cars.yahoo.com/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While loop exercise

2005-05-22 Thread Andrei
. ,  hotmail.com> writes:

> I just finished the chapter which includes while loop, if-else-elif 
> structure and randrange().
> 
> Can anyone suggest me 3 exercises to remind of the chapter?

The standard exercise which includes all three would be a number guessing game
where the computer picks a number and the user guesses it (the opposite is also
possible, but then randrange is not useful). A while loop is standard in *any*
program that can be executed more than once. E.g. asking someone for a string is
a single line of code, but asking for an unlimited number of strings directly
requires a while loop.

> Looking forward to writing some programs!

At this stage there aren't many really useful application you can make, but you
should use your fantasy. Pick a subject you know something about and make a
simple application for it. I think there are lots of suitable subjects in maths,
physics and children's games, but you can find suitable subjects in lots of
other fields too.

Other possible small programs using while and if (randrange is a bit exotic and
not that useful):
- let the user input names and dates of birth. Calculate membership fee to a
club based on whether the person is a child, an adult or a senior citizen.
- a quadradic formula solver (would have to check whether the determinant < 0)
- a hangman game
- a free fall calculator (given an object that is dropped from a certain height,
calculate a table with its position as a function of time)
- a quiz program about some topic you like (could even use randrange in this one
to pick questions)
- a program which combines some of the programs above - e.g. allow the user to
play either number guessing or hangman.
- a hotel booking application which allows making reservations for one or
2-person rooms and applies a discount if the reservation is on a day between
monday and thursday. 

Yours,

Andrei

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] While loop exercise

2005-05-21 Thread . ,
Hi,

I just finished the chapter which includes while loop, if-else-elif 
structure and randrange().

Can anyone suggest me 3 exercises to remind of the chapter?

Exercises shouldn't be too difficult because i'm newbie!

Looking forward to writing some programs!

Thanks.

_
FREE pop-up blocking with the new MSN Toolbar - get it now! 
http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor