[Tutor] While loop counter

David david at abbottdavid.com
Tue Jul 8 00:18:40 CEST 2008


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



More information about the Tutor mailing list