Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Python (http://www.programmingforums.org/forum43.html)
-   -   Novice questions. (http://www.programmingforums.org/showthread.php?t=6258)

snafu Oct 4th, 2005 5:06 PM

Novice questions.
 
Hello all,

I've enjoyed looking over the forums the past couple days. You have a great community.

What brought me here was the need for custom scripts to make my life easier (necessity is the mother of invention, right?). I'm in charge of enterprise backups using Legato. We have some scripts (that look like they were written in C?) that were made years ago but they need tweaking. I would also eventually like to write some scripts to aid me in daily tasks that I am accomplishing now through the GUI, which is extremely time-consuming. I also know and use the equivalent unix commands to what I do through the GUI which is my I'm eager to learn Python.

I've avoided programming my entire life after trying to learn C at age 12 (traumatizing). I'm much more logical now and figure it's a good skill to have plus I could really use it. So, please bear with my n00b questions. :)

Anyway, this is my third day into Python. I'm using 'O'Reilly: Learning Python, 2nd Edition' and 'Non-Programmers Tutorial For Python' as well as DrPython (much more enjoyable than IDLE).

So, one of the exercises I was assigned was to "Write a program that gets 2 string variables and 2 integer variables from the user, concatenates (joins them together with no spaces) and displays the strings, then multiplies the two numbers on a new line."

I could just bang out the bare minimum but I understand better when it's something useful. This isn't too over-the-top.

:

#!
##  This program prints
##  your name and also
##  calculates your net
##  and gross annual
##  income.

first_name = raw_input("What is your first name?")
last_name = raw_input("What is your last name?")
hourly_wage = input("How much do you make per hour?")
tax_rate = input("How much would you say is withheld from your paycheck for taxes (percentage)?")
gross_annual = hourly_wage*2000
print first_name +"",last_name +", your approximate gross annual income is", gross_annual
taxed = gross_annual * tax_rate
net_annual = gross_annual - taxed
print "Also, assuming a federal income tax rate of", tax_rate
print ", your annual net income is", net_annual


My Questions
1. In order for the math to come out right I need the tax_rate entered by the user to be a decimal (they enter 25 and is read by the program as .25). How can I accomplish this?
2. How do you insert a variable mid sentence and then have the sentence continue on? I can't quite figure that out. The last two lines I would like to combine into one but am getting syntax errors.
3. How can I clean up this code? Am I making something too difficult or can something be done more efficiently?

I understand about hash bang and thought I would just include it in all my scripts for good practice (minus the path). Thanks a lot for your help. :D

Sane Oct 4th, 2005 6:33 PM

Quote:

Originally Posted by snafu
1. In order for the math to come out right I need the tax_rate entered by the user to be a decimal (they enter 25 and is read by the program as .25). How can I accomplish this?

Another word for a decimal type variable, is a float. A number can be converted to float, by calling it in the function float().

Example:
:

x = 25
x = float(x) / 100.0
print x


That would turn 25 in to 0.25 . Because 25 is converted to 25.0, then divided by 100.0 to get 0.25.

Quote:

Originally Posted by snafu
2. How do you insert a variable mid sentence and then have the sentence continue on? I can't quite figure that out. The last two lines I would like to combine into one but am getting syntax errors.

You need to wrap commas (',') around the variable:

:

a = 1
b = 2
c = 3
print 'A is', a, '. B is', b, '. C is', c, '.'


You could also concact them as strings:

:

a = 1
b = 2
c = 3
print 'A is ' + str(a) + ' . B is ' + str(b) + ' . C is ' + str(c) ' .'


str() converts any type to string. Which is the only capable type of being concated.

And I don't want to overload you, but the final and best (IMO) option is:

:

a = 'One'
b = 2
c = 3.0
print 'A is %s. B is %d. C is %s.'%(a, b, c)


%s represents a call to a string (but works with anything), %d a call to an integer

Those calls are filled in after the literal inside %().

Quote:

Originally Posted by snafu
3. How can I clean up this code? Am I making something too difficult or can something be done more efficiently?

Cleanliness does not apply much for a simple series of executions. But something that would be useful to know in the future. Is to get all your inputs in one section, mathematical calculations in another section, and output all your results in the last.

The way you have it it's a bit scrambled. And your output is a little messy, but see the answer to #2 for answers to that.

:

#!
##  This program prints
##  your name and also
##  calculates your net
##  and gross annual
##  income.

#get input
first_name = raw_input("What is your first name?")
last_name = raw_input("What is your last name?")
hourly_wage = input("How much do you make per hour?")
tax_rate = input("How much would you say is withheld from your paycheck for taxes (percentage)?")

#analyze input
gross_annual = hourly_wage*2000
taxed = gross_annual * tax_rate
net_annual = gross_annual - taxed

#send output
print "%s %s, your approximate gross annual income is %s."%(first_name, last_name, gross_annual)
print "Also, assuming a federal income tax rate of %s, your annual net income is %s."%(tax_rate, net_annual)


Congrats on your first program.

Hope I helped.
:)



BTW. For future reference. input() can be a bad command to use in your programs. If they enter a character, your program crashes. Here's a quick way to fix that:

:

try:
    number = input('Enter a number: ')
    print "Your number is", number
except NameError:
    print "I said number fool!!"


except will except the mentioned error type and execute the indented block under except, as long as that error fell under the indented block in try. Understand?

snafu Oct 5th, 2005 2:04 PM

Sane,

Thanks a lot. A few follow-up questions.

1. Changing the type to floating did the trick but the number is always followed by six zeros (i.e. "Also, assuming a federal income tax rate of 25.000000, ...). While technically correct, how can I make this number less... exact. I would prefer 25.0.

2. You said that input() can be a bad command to use. What would you use in place of input()? Raw_input()?

3. Also, in my program can you specify where the "except NameError:" line should go? Do I need to place it after every line where they could enter a char instead of an int? I tried placing it at the very end but received a syntax error.

Thanks for the help.

Sane Oct 5th, 2005 5:03 PM

Quote:

Originally Posted by snafu
1. Changing the type to floating did the trick but the number is always followed by six zeros (i.e. "Also, assuming a federal income tax rate of 25.000000, ...). While technically correct, how can I make this number less... exact. I would prefer 25.0.

:

x = 3.141592
x = round(x, 1) #1 = round to 1 digit place
print x

Outputs: 3.1

Quote:

Originally Posted by snafu
2. You said that input() can be a bad command to use. What would you use in place of input()? Raw_input()?

You would use the code example I gave you with try and except. That is if you need integer input. Always use raw_input for string input.

Quote:

Originally Posted by snafu
3. Also, in my program can you specify where the "except NameError:" line should go? Do I need to place it after every line where they could enter a char instead of an int? I tried placing it at the very end but received a syntax error.

Well for something like this, you shouldn't worry too much about safety, but here is what it would look like:

:

def safe_input(x):
    from sys import exit
    try:
        return input(x)
    except NameError:
        print "I said number fool!!"
        exit()

#get input
first_name = raw_input("What is your first name?")
last_name = raw_input("What is your last name?")
hourly_wage = safe_input("How much do you make per hour?")
tax_rate = safe_input("How much would you say is withheld from your paycheck for taxes (percentage)?")

#analyze input
tax_rate = round( float(tax_rate) / 100.0, 1)
gross_annual = hourly_wage*2000
taxed = gross_annual * tax_rate
net_annual = gross_annual - taxed

#send output
print "%s %s, your approximate gross annual income is %s."%(first_name, last_name, gross_annual)
print "Also, assuming a federal income tax rate of %s, your annual net income is %s."%(tax_rate, net_annual)


I'm not sure if you've used functions yet. But that's a little example of how a function can improve the functionality of your code by breaking repeated steps.

In this case the function is defined as "safe_input". And inside the () we call variable x, or the message that is passed through safe_input(). We return the value from the input call, but if the user entered a string. We use the function exit() from the import sys.

The biggest advantage to using a function, is instead of using exit(), we can just go safe_input(x). That is something called a recursive function. The advantage of this, is it'll keep asking for the same input until it finally gets a number, or else it just recurses upon itself.

:

def safe_input(x):
    try:
        return input(x)
    except NameError:
        print "Invalid Input"
        safe_input(x)

Neat eh?

It's a little complicated to go much more in to detail. Your tutorial will tell you all about functions, don't be intimidated. ;)


All times are GMT -5. The time now is 4:22 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC