Welcome to our forums...

If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed.

Forum Statistics

  • Forum Members:
  • Total Threads:
  • Total Posts: 8
There are 1 users currently browsing forums.
General Programming Here you can talk about scripting in other languages such as Perl, Delphi, Pascal and Python.

Reply
  #1  
Old 02-05-2010
Toddler
 
Join Date: Jan 2010
Posts: 7
Rep Power: 0
Galileo228 is on a distinguished road
Output function results

Hey All,

I keep running into this problem in one form or another.

I've developed a rudimentary program that lets me enter grades I think I might receive for this semester, and then calculates my cumulative GPA.

So, to prompt for the grade I think I might receive in International Law, I have:

def IL():
return input("Enter grade for Int Law: ")

I have functions for four other courses, and then I use simple math calculations with IL() and the other courses to arrive at CGPA, which is the cumulative GPA.

I can PRINT this value:

print ("This is your cum GPA: ", FGPA)

What I CANNOT do is output this (or the value of IL()) to another file.

Thus, after the calculations of the program are run, this is what I'd like to do:

openfile = open('results.txt','w')
openfile.write('You selected', IL(), 'as your grade in International Law. \n \
Your cum GPA is: ', FGPA).

This does not work! Instead of returning the originally entered value for IL(), it runs the function again, and neither does it let me use FGPA.

Can anyone explain how to output these values to the file?

Thank you for your help!

Matt
Reply With Quote
  #2  
Old 02-05-2010
Moderator
 
Join Date: Dec 2005
Posts: 1,862
Rep Power: 6
Umang is on a distinguished road
Re: Output function results

Some points:
You are facing this problem because you don't seem to store the value returned from IL(). You are getting the value by calling it. What you should do is store the value returned by IL() in a variable and retrieve it from the variable whenever required.

Also, using arrays would reduce the complication by a huge amount. You would have two variables and one function and the ability to add/remove courses without having to change the code.

In Python:
Code:
courses = ['IL', 'Phy', 'Socio', 'CS']
results = {}
for course in courses:
    results[course] = raw_input("Enter result for %s: "%course)

print results
# you will get something like {'IL': 'A+', 'Phy':B-, 'Socio':'A-', 'CS': 'B'}
You can now create a function called get_CGPA that will take your results dict and get a CGPA.

Hope this helps,

Last edited by Umang; 02-05-2010 at 08:22 PM.
Reply With Quote
  #3  
Old 02-06-2010
Toddler
 
Join Date: Jan 2010
Posts: 7
Rep Power: 0
Galileo228 is on a distinguished road
Re: Output function results

Umang,

I've tried to store the value of IL() to a variable, but I get error msgs saying that I "can't assign to function call." Maybe this is a basic step I missed as I've been teaching myself, but what is the basic way to store a function's return in a variable? IL() = new_var keeps giving me the error msg I stated above (even when I've initialized the new variable (new_var = 0) before I've even defined IL().

Secondly, how can I construct a function to manipulate just the values in a dictionary? So assuming grades = {'IL':4.0, 'Psy':3.7, 'CS':3.7}, what is the syntax for a function that would let me call just the values in this dictionary and manipulate them?

Thank you!

Matt
Reply With Quote
  #4  
Old 02-07-2010
Moderator
 
Join Date: Dec 2005
Posts: 1,862
Rep Power: 6
Umang is on a distinguished road
Re: Output function results

It's the wrong way around! Don't worry, these things happen when you're starting. It's new_var = IL().

Also, once you've got your grades dictionary, you can easily make the keys, values or both into a tuple.
Code:
>>> grades.values()
[3.7000000000000002, 3.7000000000000002, 4.0]
>>> grades.keys()
['CS', 'Psy', 'IL']
>>> grades.items()
[('CS', 3.7000000000000002), ('Psy', 3.7000000000000002), ('IL', 4.0)]
So if you want the average grade, then
Code:
>>> sum(grades.values())/len(grades)
3.8000000000000003
>>>
If you read diveintopython, you'll pick up a lot of these tricks. I'm sure you'll find them in many other tutorials also. Python is full of convenient shortcuts like these.

EDIT: You don't worry about the 3.7000000000000002. It's called a floating point error. Some slightly more advanced reading: http://en.wikipedia.org/wiki/Floatin...uracy_problems

Last edited by Umang; 02-07-2010 at 07:14 AM.
Reply With Quote
  #5  
Old 4 Weeks Ago
Toddler
 
Join Date: Jan 2010
Posts: 7
Rep Power: 0
Galileo228 is on a distinguished road
Re: Output function results

Umang,

Thanks for the help. Here's the program I wrote:

Code:
nc, n, a = 0, 1, 1
qp_list = []
cred_list = []
clist = {}
A, Aminus = 4.0, 3.67
Bplus, B, Bminus = 3.33, 3.0, 2.67
Cplus, C = 2.33, 2.0

def main():
    return input('Enter number of classes this semester: ')
    
def EnterData():
    cname = raw_input('\nEnter name for class %s: '%a)
    ccreds = input('Enter number of credits for %s: '%cname)
    cgrade = input('Enter expected grade for %s: '%cname)
    print " "
    cred_list.append(ccreds)
    clist[cname] = cgrade
    cqp = ccreds * cgrade
    qp_list.append(cqp)
    
nc = main() 
while n <= nc:
    EnterData()
    n = n + 1
    a = a + 1
    
print 'To recap, you have selected the following classes:\n'
for x in clist:
    print 'You have selected', x, 'with a grade of: ',clist[x]

cgpa = sum(qp_list) / sum(cred_list) 
FGPA = (sum(qp_list) + 179) / (sum(cred_list) + 52)

print '\nGiven the varying credit weight of each class,'
print 'your GPA for the semester would be: ',cgpa;
print '\nYour final GPA would be',round(FGPA, 3),'.'
print '\nComputer, end program.'
Note in particular this portion:

Code:
def EnterData():
    cname = raw_input('\nEnter name for class %s: '%a)
    ccreds = input('Enter number of credits for %s: '%cname)
    cgrade = input('Enter expected grade for %s: '%cname)
When I was assigning ccreds and cgrade, I couldn't figure out why I couldn't just use cname as a variable in those input strings, considering cname was defined first. After looking at your '%' instructions, I hit upon the above by experimentation and it worked, although I have no idea why. (MUST %var_name be used to return the value of var_name in subsequent input strings?)

After I got this to work, I was messing around with the same kind of program but using a class, and there I could NOT get it to work.

So, for example:

Code:
class law:
class law:
    def __init__(self,course,creds,grade):
        self.course = course
        self.creds = creds
        self.grade = grade
        . . .

c1 = law(raw_input('Enter course name: '),input('Enter number of credits for %s: '%course), input('Enter grade for %s: '%course))
Above, for the 'c1' instance of the law class, the use of %s does not work. I get error messages. Neither %course, %self.course, nor %law.course will display the value entered for the 'course' variable in the input string for the 'creds' or 'grade' variable.

Would you be able to explain why the %s trick does not work with classes (or if I'm using it incorrectly)?

Thank you again.

Matt
Reply With Quote
  #6  
Old 4 Weeks Ago
Moderator
 
Join Date: Dec 2005
Posts: 1,862
Rep Power: 6
Umang is on a distinguished road
Re: Output function results

Before I read you post fully, I'll point out that you repeated the mistake of using input instead of raw_input quite a few times. NEVER do that. I think I've already explain (tell me if I haven't) why you should (almost) never use input (unless you know what you are doing).

Code:
class law:
    def __init__(self,course,creds,grade):
        self.course = course
        self.creds = creds
        self.grade = grade
        . . .

c1 = law(raw_input('Enter course name: '),input('Enter number of credits for %s: '%course), input('Enter grade for %s: '%course))
You haven't defined course. (Unless you meant to do this:

Code:
class law:
    def __init__(self,course,creds,grade):
        self.course = course
        self.creds = creds
        self.grade = grade
        # . . .
        c1 = law(raw_input('Enter course name: '),raw_input('Enter number of credits for %s: '%course), raw_input('Enter grade for %s: '%course))
In which case it should (haven't tested) work.
Reply With Quote
  #7  
Old 4 Weeks Ago
Toddler
 
Join Date: Jan 2010
Posts: 7
Rep Power: 0
Galileo228 is on a distinguished road
Re: Output function results

Umang,

You never explained why one should never use 'input'. I'm all ears!

Matt
Reply With Quote
  #8  
Old 4 Weeks Ago
Moderator
 
Join Date: Dec 2005
Posts: 1,862
Rep Power: 6
Umang is on a distinguished road
Re: Output function results

raw_input gets the string that was entered and stores *that*. input, however, doesn't return the string. It first executes the string as python code and then returns the whatever the code returns. Hopefully this will give you a good idea:
Code:
umang@home-ubuntu:~$ python
Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15) 
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> grade = input("Please enter the grade for IL: ")
Please enter the grade for IL: sys.exit(1)
umang@home-ubuntu:~$ python
Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15) 
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> grade = input("Please enter the grade for IL: ")
Please enter the grade for IL: ", ".join(['abc', 'def', 'ghi'])
>>> grade
'abc, def, ghi'
Notice that when it asked me for my grade, I "fooled" it by entering "sys.exit(1)" and I "closed" python. When I later entered another python command (i.e. ", ".join(['abc', 'def', 'ghi']) ) it executed it and returned the value ('abc, def, ghi').

If I try to enter a normal string, here's what happens:
Code:
>>> grade = input("Please enter the grade for IL: ")
Please enter the grade for IL: hello!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    hello!
        ^
SyntaxError: unexpected EOF while parsing
Obviously, hello! is not python code. So python cannot execute hello!.

However, if I used raw_input, it just reads the input and puts it into a string:
Code:
umang@home-ubuntu:~$ python
Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15) 
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> grade = raw_input("Please enter the grade for IL: ")
Please enter the grade for IL: sys.exit(1)
>>> grade
'sys.exit(1)'
>>> grade = raw_input("Please enter the grade for IL: ")
Please enter the grade for IL: ", ".join(['abc', 'def', 'ghi'])
>>> grade
'", ".join([\'abc\', \'def\', \'ghi\'])'
>>> grade = raw_input("Please enter the grade for IL: ")
Please enter the grade for IL: hello!
>>> grade
'hello!'
>>>
Finally, here's why you should never ever use input: When you use input, you are letting your user execute python code. Now the user can do whatever he/she wants, including make you application malfunction like hell, or just quit it immediately (by entering sys.exit(1) if you've imported sys).

Oh and I don't think what I said in my previous post was right. Could you explain what you were trying to do with
Code:
class law:
    def __init__(self,course,creds,grade):
        self.course = course
        self.creds = creds
        self.grade = grade
        . . .

c1 = law(raw_input('Enter course name: '),input('Enter number of credits for %s: '%course), input('Enter grade for %s: '%course))
and I could help you there.
Reply With Quote


Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Tutorial: Handy function to include a file if that file exists. bfsog .Net Programming 0 07-28-2008 05:10 AM
PHP Tutorial - Functions and Classes DKing PHP Articles 5 07-06-2005 08:14 PM
The Real Basics of Functions in ASP parker General Web Programming 0 01-02-2005 05:46 AM
javascript part 6 hayabusa Javascript Articles 0 09-05-2004 09:11 AM