Solved

Confused on how to make Python code more efficient

Posted on 2013-11-08
3
569 Views
Last Modified: 2013-11-11
Hi Guys,

I'm new to Python Programming. I'm used to Ruby and how you don't really have to have return statements and such for your functions. Learning Python has been a real struggle for me. I'm trying to create a simple fuel calculation program below and feel i had to type so much code in order to get input from a user and convert that string input back to either a float or int. Is there anyway I can make my code more efficient? Are there any better practices I can follow? I don't seem to understand why self always have to be called because in Ruby you never have to worry about "self"

#!/usr/bin/python

class TripCost:
	def __init__(self, miles_per_gallon, distance, price_per_gallon):
		self.miles_per_gallon = miles_per_gallon
		self.distance = distance
		self.price_per_gallon = price_per_gallon
	#self always has to explicityly called when using class level functions
	def Mileageprice_per_gallon(self):
		return (self.price_per_gallon * self.distance)
	def Roundtrip(self):
		return(self.distance * 2)

#Creating a new object called trip with a car that has 22 mpg 13.6 mile drive and 3.27 for gas
trip1 = TripCost(22, 13.5, 3.27)
mpg =trip1.Mileageprice_per_gallon()
print "The cost of the price per gallon and distance will be : " 
print mpg
roundTrip = trip1.Roundtrip()
print "The round trip will be"
print roundTrip
x_mpg = raw_input('How many miles per gallon does your vehicle give you?')
print 'Your vehicle gives you ' + x_mpg
x_distance = raw_input('How Far is your one way commute? ')
print 'Your one way commute is ' + x_distance
x_price_per_gallon = raw_input('What is the cost of fuel per gallon?')
print 'The cost of fuel is ' + x_price_per_gallon
#Convert all string input to integers
i_mpg = int(x_mpg)
print i_mpg
i_distance = float(x_distance)
print i_distance
mult = (i_distance * i_mpg)
print mult
i_price_per_gallon = float(x_price_per_gallon)
print i_price_per_gallon



trip2 = TripCost(i_mpg, i_distance, i_price_per_gallon)
mpg2 = trip2.Mileageprice_per_gallon()
print mpg2

Open in new window

0
Comment
Question by:Tbalz
3 Comments
 
LVL 45

Expert Comment

by:aikimark
ID: 39635559
I would refactor this into a function that has multiple parameters.  The user supplies the necessary parameter values when they invoke the code.
0
 
LVL 16

Accepted Solution

by:
gelonida earned 500 total points
ID: 39635579
Concerning  you don't understand why you have to specify self.

Any language has a sligthly different philosopy. Python for example tries to be rather readable and prefers being a little verbose and explicit.
You'll get used to writing 'self' and being a little more explicit. though I agree, that sometimes I'd really love to have some magic way to replace lines 4 to 7 of your script with something more concise. one has the impression, that the word init and the three parameters would be all one really wanted to type.


Apart from that a few small suggestions for the naming style.
(I would use CamelCase for class names like ( MySuperClass)
for variables and functions I'd use lowercase only with underscores like
def my_function_name(self, one_variable, another_variable)



You could add two functions like
def read_int(prompt):
    """ pronpts, reads a string and converts it to an int
         validation code / try except statements
        could be added here later on as well
   """
    value = int(raw_input(prompt))
    return value

def read_float(prompt):
    value = float(raw_input(prompt))
    return value

Open in new window

or if you can handle slighhtl;y different messages:
def read_float(item_txt):
    value = float(raw_input('please enter a value for ' + item_text))
    print('%s is %f' % (item_text, value)) 
    return value

Open in new window



Instead of

print "The cost of the price per gallon and distance will be : " 
print mpg

Open in new window


you could write

print("The cost of the price per gallon and distance will be : \n%s" % mpg) 

Open in new window


P.S. The way I write print statements ensures, that they'll work with python 2.7 and with Python 3
0
 
LVL 28

Expert Comment

by:pepr
ID: 39635664
I do not know Ruby (a bit only). It could be nice if you show the Ruby equivalent of the code here. Then we can compare and discuss the differences better.

Now, some basic Python things. (I understand how beginners in some language feel even though they may be quite experienced in another one, no offence.)

In Python 2, print is a command (the print being a keyword). The list of arguments is comma separated, and the list is separated from the keyword by space. The print command converts each argument to the string representation, adds space for separation of arguments, and appends \n if you do not suppress it. This way, you can also write:
print "The cost of the price per gallon and distance will be :", mpg

Open in new window

In Python 3, print is a built-in function. Because of that, you need to use parentheses when called. Otherwise, the behaviour resembles the Python 2 print command. When using the transitional Python 2.7, you can tell explicitly that you prefer the new form from Python 3.

The return is the command in both Pythons. This way, you need not use the parentheses -- they are parsed as belonging to the following expression, not to the return.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

It’s 2016. Password authentication should be dead — or at least close to dying. But, unfortunately, it has not traversed Quagga stage yet. Using password authentication is like laundering hotel guest linens with a washboard — it’s Passé.
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now