Jump to content

Help With First Program

- - - - -

  • Please log in to reply
7 replies to this topic

#1
Shadow21

Shadow21

    Newbie

  • Members
  • PipPip
  • 12 posts
I'm working on my first program (at least my first useful program) and I've gone through a lot of trial and error and I've been able to fix all the errors but now I'm stuck.

This is the part of my code that I'm running that is not doing exactly what I want:

#!/usr/bin/python3


class FanControl:


	def __init__(self):

		try:

			open('settings.txt', 'r')

		except IOError:

			CreateSettings.MinTemp()	


class CreateSettings:

	

	mintemp = 0

	maxtemp = 0	

	

	def MinTemp():


		SettingsFile = open('settings.txt', 'w')


		CreateSettings.mintemp = int(input('Minimum temperature for temperature range: '))

		minspeed = int(input('Fan speed for temperature range "*C <= {0}*C": '.format(CreateSettings.mintemp)))

		save = str((0, CreateSettings.mintemp, minspeed))

		SettingsFile.write(save)

		print('~~~~~~')

		

		CreateSettings.AvgTemp()

		

	def AvgTemp():


		loop = 'yes' 

		SettingsFile = open('settings.txt', 'w') #####


		while loop == 'yes':


			CreateSettings.mintemp = CreateSettings.mintemp+1

			CreateSettings.maxtemp = int(input('Maximum temperature for next temperature range: '))

			speed = int(input('Fan speed for temperature range "{0}*C <= *C <= {1}*C": '.format(CreateSettings.mintemp, CreateSettings.maxtemp)))

			save = str((CreateSettings.mintemp, CreateSettings.maxtemp, speed))

			SettingsFile.write(save)

			print(save)

			CreateSettings.mintemp = CreateSettings.maxtemp

			loop = str(input('Add another temperature range? (yes/no): '))

			while loop != 'yes' and loop != 'no':

				loop = str(input('Add another temperature range? (yes/no): '))

			print('~~~~~')


		SettingsFile.close() #####

I'm wanting it to print the three numbers as a tuple (converted to strings) to a settings file. The MinTemp function prints to the file correctly but when it goes to the AvgTemp function and runs through the loop the first time it only prints a ")" to the file. After the it runs the loop once it does start printing the tuples to the file correctly.

This is what I get when I run the program:

Minimum temperature for temperature range: 10

Fan speed for temperature range "*C <= 10*C": 10

~~~~~~

Maximum temperature for next temperature range: 20

Fan speed for temperature range "11*C <= *C <= 20*C": 20

(11, 20, 20)

Add another temperature range? (yes/no): yes

~~~~~

Maximum temperature for next temperature range: 30

Fan speed for temperature range "21*C <= *C <= 30*C": 30

(21, 30, 30)

Add another temperature range? (yes/no): yes

~~~~~

Maximum temperature for next temperature range: 40

Fan speed for temperature range "31*C <= *C <= 40*C": 40

(31, 40, 40)

Add another temperature range? (yes/no): yes

~~~~~

Maximum temperature for next temperature range: 50

Fan speed for temperature range "41*C <= *C <= 50*C": 50

(41, 50, 50)

Add another temperature range? (yes/no): no

~~~~~


This is what the settings file looks like:

(0, 10, 10))(21, 30, 30)(31, 40, 40)(41, 50, 50)

Why is it printing ")" when it runs through the loop in the AvgTemp function for the first time?

I'm not really wanting advice on how to make my program better or smaller yet because I want to try and figure that out on my own at first.

Thanks!

Edited by Shadow21, 02 March 2011 - 09:17 PM.


#2
Shadow21

Shadow21

    Newbie

  • Members
  • PipPip
  • 12 posts
Can anyone help?

#3
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Hmm, I think it may be because you're opening the file to be written to twice, and when you open it the second time, it writes over the buffer to write to the file. When the file is closed the buffer is flushed, so on this line of code:
SettingsFile.close() #####
The SettingsFile is flushed in the AvgTemp function, NOT the MinTemp function! That means that flushes (actually writes) to the file first, then the second one flushes automatically when Python closes it because you didn't. Then it writes to the same file, which writes over your first object. So after the first flush your file looks like this:
(11, 20, 20)(21, 30, 30)(31, 40, 40)(41, 50, 50)
Then on the second flush:
(0, 10, 10))(21, 30, 30)(31, 40, 40)(41, 50, 50)
So the way to fix this is to pass the file object to the second function, then close it in the first:
        def AvgTemp(SettingsFile):


		loop = 'yes' 


		while loop == 'yes':


			CreateSettings.mintemp = CreateSettings.mintemp+1

			CreateSettings.maxtemp = int(input('Maximum temperature for next temperature range: '))

			speed = int(input('Fan speed for temperature range "{0}*C <= *C <= {1}*C": '.format(CreateSettings.mintemp, CreateSettings.maxtemp)))

			save = str((CreateSettings.mintemp, CreateSettings.maxtemp, speed))

			SettingsFile.write(save)

			print(save)

			CreateSettings.mintemp = CreateSettings.maxtemp

			loop = str(input('Add another temperature range? (yes/no): '))

			while loop != 'yes' and loop != 'no':

				loop = str(input('Add another temperature range? (yes/no): '))

			print('~~~~~')

Wow I changed my sig!

#4
Shadow21

Shadow21

    Newbie

  • Members
  • PipPip
  • 12 posts
Thank you! That worked :)

This is the code with the edits:

#!/usr/bin/python3


class FanControl:


	def __init__(self):

		try:

			open('settings.txt', 'r')

		except IOError:

			CreateSettings.MinTemp()	


class CreateSettings:

	

	mintemp = 0

	maxtemp = 0	

	

	def MinTemp():


		SettingsFile = open('settings.txt', 'w')


		CreateSettings.mintemp = int(input('Minimum temperature for temperature range: '))

		minspeed = int(input('Fan speed for temperature range "*C <= {0}*C": '.format(CreateSettings.mintemp)))

		save = str((0, CreateSettings.mintemp, minspeed))

		SettingsFile.write(save)

		print('~~~~~~')

		

		CreateSettings.AvgTemp(SettingsFile) 

		

	def AvgTemp(SettingsFile): 


		loop = 'yes' 


		while loop == 'yes':


			CreateSettings.mintemp = CreateSettings.mintemp+1

			CreateSettings.maxtemp = int(input('Maximum temperature for next temperature range: '))

			speed = int(input('Fan speed for temperature range "{0}*C <= *C <= {1}*C": '.format(CreateSettings.mintemp, CreateSettings.maxtemp)))

			save = str((CreateSettings.mintemp, CreateSettings.maxtemp, speed))

			SettingsFile.write(save)

			print(save)

			CreateSettings.mintemp = CreateSettings.maxtemp

			loop = str(input('Add another temperature range? (yes/no): '))

			while loop != 'yes' and loop != 'no':

				loop = str(input('Add another temperature range? (yes/no): '))

			print('~~~~~')


		CreateSettings.MaxTemp(SettingsFile) 

	

	def MaxTemp(SettingsFile):


		CreateSettings.maxtemp = CreateSettings.maxtemp+1

		save = str((CreateSettings.maxtemp, 1000, 100))

		SettingsFile.write(save)

		SettingsFile.close()

		print('Final temperature range is "{0}*C < oo" at 100% fan speed.'.format(CreateSettings.maxtemp))

	


FanControl()

I'm still really new to Python so I didn't know I could pass the variables to another function that way.

#5
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
You can encapsulate this behavior better using the ability to pass arguments like this into functions. Also I notice you're using a class, so we can actually have SettingsFile as a class object that is initialized by the FanControl constructor and then the methods act on it! This is the best way to do it, but because Python is garbage collected, you'll have to add a "cleanup()" like function to FanControl.

class FanControl:

    def __init__(self):

        self.success = false #This variable is necessary to keep it safe if an IOError is thrown.

        try:

            self.SettingsFile = open('settings.txt', 'rw')

        except IOError:

            print "Failure to open settings.txt to read/write."

            return

        self.write_data = [] # We'll fill this with the 3-tuples to write to SettingsFile.

        self.success = true


    def intInput(self, user_string):

        return int(input(user_string))


    def getMinTemp(self):

        return intInput('Minimum temperature for temperature range: ')


    def getMaxTempNext(self):

        return intInput('Maximum temperature for next temperature range: ')


    def getMinSpeed(self, first, second):

        return intInput('Fan speed for temperature range "{0}*C <= *C <= {1}*C": '.format(first, second))


    def writeDataToFile(self):

        for tup in self.write_data:

            self.SettingsFile.write(tup)


    def cleanup(self):

        if (!success) return None

        self.SettingsFile.close()


    def startProgram(self):

        if (!success) return None

        first_temp = getMinTemp()

        first_speed = getMinSpeed(0, first_temp)

        write_data.append((0, first_temp, first_speed))

        prev_temp = first_temp + 1

        while True:

            print('~~~~~')

            temp = getMaxTempNext()

            speed = getMinSpeed(prev_temp, temp)

            write_data.append((prev_temp, temp, speed))

            prev_temp = temp + 1



fan = FanControl()

fan.startProgram()

fan.cleanup()

Wow I changed my sig!

#6
Shadow21

Shadow21

    Newbie

  • Members
  • PipPip
  • 12 posts
How can I make it so each tuple is written to its own line in the file?

Ex:

(0, 10, 10)

(11, 20, 20)

(21, 30, 30)

(31, 40, 40)

(41, 50, 50)



#7
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Simply add another SettingsFile.write() statement that writes a "\n", which is the end line character.

        self.SettingsFile.write(tup)

        self.SettingsFile.write("\n")

Wow I changed my sig!

#8
Shadow21

Shadow21

    Newbie

  • Members
  • PipPip
  • 12 posts
This should hopefully be one of my last question for this program.

How do I retrieve the string (which is in tuple format) from the file and convert it back into the tuple that it looks like? When I retrieve it from the file and convert it back to a tuple it looks something like this:

('(', '0', ',', ' ', '1', '0', ',', ' ', '1', '0', ')')

EDITED: Woo! I was able to figure it out by myself. I had to change the way the numbers would be written to the file but I was able to get them to be read as a tuple by my program.

Edited by Shadow21, 09 March 2011 - 03:44 PM.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users