Jump to content

Beginner python coding questions..


555
 Share

Recommended Posts

I am reading an online tutorial and it gives this example..

#!/usr/bin/python

var1 = 100
if var1:
   print "1 - Got a true expression value"
   print var1

var2 = 0
if var2:
   print "2 - Got a true expression value"
   print var2
print "Good bye!"

I am guessing #whatever.. is used to comment in python? so #!/usr/bin/python just is telling me that it is a python script?

and it says the result of this code will output to the screen

1 - Got a true expression value
100
Good bye!

why would it not output

1 - Got a true expression value
100
2 - Got a true expression value
0
Good bye!

source link: http://www.tutorialspoint.com/python/python_if_else.htm

another question.. the elif command, so is it pretty much the same as an if/else command but backwords else/if "elif"? used to make code shorter? also im guessing python counts from 0? thanks..!

Link to comment
Share on other sites

# is used for commenting in python. the #!/usr/bin/python is so you can just run ./whatever.py (once you chmod +x it).

It wouldn't print "2 - Got a true expression value" and "0" because 0 is false. so if var2 becomes if 0 which is if false.

elif is elseif in python. Example:

if a==b:
    #do stuff
elif a==c:
    #do other stuff
else:
    #do other other stuff

Link to comment
Share on other sites

another question.. the elif command, so is it pretty much the same as an if/else command but backwords else/if "elif"? used to make code shorter? also im guessing python counts from 0? thanks..!

elif is a shorter way of nesting if statments in an else with out actualy nesting it.

if i = 1:
  print("face")
else:
  if i = 2:
    print("face2")
  else:
    print("Don't know")

could more easily be written as

if i = 1:
  print("face")
elif: i = 2:
  print("face2")
else:
  print("Don't know")

making it more like a case/switch statment

Link to comment
Share on other sites

ok i think i see now..

so

input i
while i <= 0
do print "i is equal or less then 0"
elif i > 0 print "i is greater then 0"
elif i > 50 print "i is greater then 50"

does that looks right?

with python is there no end statements? like you dont have to put End If, End Module, or End function at the end of the code? thanks!

Link to comment
Share on other sites

ok i think i see now..

so

input i
while i <= 0
do print "i is equal or less then 0"
elif i > 0 print "i is greater then 0"
elif i > 50 print "i is greater then 50"

does that looks right?

with python is there no end statements? like you dont have to put End If, End Module, or End function at the end of the code? thanks!

Not quite, you need an opening if, and also "i is greater then 50 will" never be printed because if i is grater than 50 it is also grater than 0.

Link to comment
Share on other sites

Thanks man, I appriciate the help. I have alot more reading to do now :) I am diggin the Python language so far and love how it works with all 3 - Windows, Mac and Linux.. when ending a module or function do you have to declare it? like say

Module main()

  declare text1 = string

  set text1 = "hello world!"

  print text1

End Module

?...

so a python scripts do not need a beginning and end to the code :?

Link to comment
Share on other sites

In python, you have beginnings, such as "if(a==c):" or "def myfunction(someparam):", but all the text in that block that follows that line must be indented (the standard appears to be 4 spaces), so the end is easily identifiable when glancing at it. There is no 'end if' or 'end function', because that's defined by the indentation.

make sense?

Link to comment
Share on other sites

I think so.. I'm still trying to figure out what the heirarchy chart of a program written in python would look like..

or maybe a flowchart. So the function / module ends at the end of the .py file? and you can import variables and such from another .py file that you import at the beginning of the main modules code?

How would this puesdo code translate to python?

Module Main()
    // prints the sales report header
    Call salesHeader()
    // prints the detail of the report
    Call salesDetails()
End Module
////////////////////////////////////////

Module salesHeader()
    Print "Brewster's Used Cars, Inc. Monthly Sales report"
    Print
    Print "Sales persons ID                                Sale amount"
    Print "========================================"
End Module

//////////////////////////////////////

Module salesDetails()
    // variables for the fields
    Declare Integer salesID
    Declare Real salesAmount
    
    //accumulator variables
    Declare Real salesTotal = 0
    Declare Real total = 0
    
    // a variable to use in the control break logic
    Declare Integer currentID
    //declare an input file and open it
    Declare InputFile salesFile
    Open salesFile "sales.dat"
    //read the first record
    Read salesFile salesID, salesAmount
    //save the student ID number
    Set currentID = salesID
    //print the report details
    While NOT eof(salesFile)
        If salesID != currentID then
            Print "Total salesAmounts for sales agent: ",
                currencyFormat(salesTotal)
            Print
            Set currentID = salesID
            Set salesTotal = 0
        End If
        Print salesID, Tab, currencyFormat(salesAmount)
        // update the accumulators
        Set salesTotal = salesTotal + salesAmount
        Set total = total + salesAmount
        // read the next record
        Read salesAmountsFile, salesID, salesAmount
    End While

    //print the total for the last agent
    Print " Total sales for this salesperson is: ",
        currencyFormat(salesTotal)
    Print " Total of all the sales: ",
        currencyFormat(total)
    //close the file
    Close salesFile
End Module

Link to comment
Share on other sites

I think so.. I'm still trying to figure out what the heirarchy chart of a program written in python would look like..

or maybe a flowchart. So the function / module ends at the end of the .py file? and you can import variables and such from another .py file that you import at the beginning of the main modules code?

How would this puesdo code translate to python?

...

Something like this:

def currencyFormat(x):
    return '$%d.%02d' % (x/100,x%100)

def salesHeader():
    print "Brewster's Used Cars, Inc. Monthly Sales report"
    print
    print "Sales persons ID                                Sale amount"
    print "========================================"

def salesDetails():
    #accumulator variables
    salesTotal = 0
    total      = 0
    salesFile  = open("sales.dat")

    currentID = salesID = None

    for line in salesFile:
        salesID,salesAmount = line.strip().split()
        salesAmount = int(salesAmount)
        if salesID != currentID: 
            if currentID != None: #Don't print this on the first iteration of the loop
                print "Total salesAmounts for sales agent: ",currencyFormat(salesTotal)
                print
            currentID = salesID
            salesTotal = 0

        print salesID, '\t', currencyFormat(salesAmount)
        #update the accumulators
        salesTotal += salesAmount
        total      += salesAmount


    #print the total for the last agent
    print " Total sales for this salesperson is: ",currencyFormat(salesTotal)
    print " Total of all the sales: ",currencyFormat(total)
    salesFile.close()

salesHeader()
salesDetails()

Link to comment
Share on other sites

Something like this:

def currencyFormat(x):
    return '$%d.%02d' % (x/100,x%100)

def salesHeader():
    print "Brewster's Used Cars, Inc. Monthly Sales report"
    print
    print "Sales persons ID                                Sale amount"
    print "========================================"

def salesDetails():
    #accumulator variables
    salesTotal = 0
    total      = 0
    salesFile  = open("sales.dat")

    currentID = salesID = None

    for line in salesFile:
        salesID,salesAmount = line.strip().split()
        salesAmount = int(salesAmount)
        if salesID != currentID: 
            if currentID != None: #Don't print this on the first iteration of the loop
                print "Total salesAmounts for sales agent: ",currencyFormat(salesTotal)
                print
            currentID = salesID
            salesTotal = 0

        print salesID, '\t', currencyFormat(salesAmount)
        #update the accumulators
        salesTotal += salesAmount
        total      += salesAmount


    #print the total for the last agent
    print " Total sales for this salesperson is: ",currencyFormat(salesTotal)
    print " Total of all the sales: ",currencyFormat(total)
    salesFile.close()

salesHeader()
salesDetails()

Whoa! :) Your the man! Looks alot different in python, I will be sure to take notes and google alot. You are very talented, thanks for your help.

What is this? "return '$%d.%02d' % (x/100,x%100)" and the other /% codes or \n and such? (I understand the return statement just not the %\stuff) So does the programming go backwards with python? or I guess instead of closing the statement at the end of each module or function you end it at the very end of the python file? for example would this be correct?..

#commenting my python code

def helloworld()

#######################putting a bunch of these - can I? without an error?? ##################

print "Hello world!"

print "This is just a test..."

Link to comment
Share on other sites

Whoa! :) Your the man! Looks alot different in python, I will be sure to take notes and google alot. You are very talented, thanks for your help.

What is this? "return '$%d.%02d' % (x/100,x%100)" and the other /% codes or \n and such? (I understand the return statement just not the %\stuff) So does the programming go backwards with python? or I guess instead of closing the statement at the end of each module or function you end it at the very end of the python file? for example would this be correct?..

#commenting my python code

def helloworld()

#######################putting a bunch of these - can I? without an error?? ##################

print "Hello world!"

print "This is just a test..."

The currencyFormat looks a bit odd because it wasn't implemented in the original. I took a guess that it was presenting an integer representing the number of cents (say 1234) and displaying that as a string like $12.34. The line '$%d.%02d' % (x/100,x%100) is an example of the old-style of python string formatting. It says create a string that consists of a $ followed by a number, followed by a dot, followed by a 2 digit number padded with zeros. It then fills the first number with x/100 (so the number of dollars) and the second with x mod 100 (the remainder when x is divided by 100), which is the number of cents.

Regarding the main function being at the end rather than the beginning, it's not that python is backwards, but rather that it is interpreted line by line. In your pseudocode example you had to create a main function, with the understanding that when your code was run that function would be executed first. When python scripts are executed they are simply executed line by line from the top. The functions are created first with def commands, which sets them up but doesn't execute them. Once they are set up we call them just like the main function in your pseudocode.

Your example illustrates the above quite nicely. If you were to run it (after adding a colon to the end of def helloworld and indenting the subsequent 2 prints) you would find that it doesn't do anything. That's because you've created your function, but not called it. You could either add a line helloworld() at the end, or just get rid of the function definition and have your script just be the print lines.

It sounds like you'd benefit from playing with a python interpreter, there are several you can access through a browser online, for example http://try-python.mired.org/

Link to comment
Share on other sites

The currencyFormat looks a bit odd because it wasn't implemented in the original. I took a guess that it was presenting an integer representing the number of cents (say 1234) and displaying that as a string like $12.34. The line '$%d.%02d' % (x/100,x%100) is an example of the old-style of python string formatting. It says create a string that consists of a $ followed by a number, followed by a dot, followed by a 2 digit number padded with zeros. It then fills the first number with x/100 (so the number of dollars) and the second with x mod 100 (the remainder when x is divided by 100), which is the number of cents.

Interesting read, I have will to dig more into this..

Regarding the main function being at the end rather than the beginning, it's not that python is backwards, but rather that it is interpreted line by line. In your pseudocode example you had to create a main function, with the understanding that when your code was run that function would be executed first. When python scripts are executed they are simply executed line by line from the top. The functions are created first with def commands, which sets them up but doesn't execute them. Once they are set up we call them just like the main function in your pseudocode.

Your example illustrates the above quite nicely. If you were to run it (after adding a colon to the end of def helloworld and indenting the subsequent 2 prints) you would find that it doesn't do anything. That's because you've created your function, but not called it. You could either add a line helloworld() at the end, or just get rid of the function definition and have your script just be the print lines.

I see, so python is a interpreted programming language instead of.. I forget the name at the moment but im thinking the word is compiled language? In school I remember there are 2 different kinds. One that goes line by line like python, which does not need to be compiled in order to execute, would that be correct?

So this would be a basic working example using the def command?

 
def helloworld():
    print "hello world" * 5

helloworld()

edit:: yes it works, just checked

It sounds like you'd benefit from playing with a python interpreter, there are several you can access through a browser online, for example http://try-python.mired.org/

Very cool link, I also downloaded python 2.5 and have been playing with python IDLE.. well, time to get to reading and coding :) thanks for all your help!

after playing with the python interpreter I see how important those 4 spaces are after the def lol i got a "print" error not using the spaces after the def command.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...