Page 1 of 4 123 ... Last
  • Jump to page:
    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    27
    Rep Power
    0

    Python quiz/test, Assistance Needed


    I'm currently following a computer science course online. I'm not officially signed up for the class though, instead, i'm working through the posted material on my own, as best I can.

    The course provides quizzes via downloadable worksheets which enlisted students can send in to have graded. Now since i'm not enlisted, the option to have my work graded is not available to me. As such, I thought i'd try to find some proficient people to look at my work and offer any advice they can.

    I'm not asking anyone to play professor, simply that anyone willing, look over what I post and offer feedback.

    I'll be posting my completed work here in hopes that someone comes along and offers assistance. In many cases, you guys will see that the answers can be figured out using the interpreter. That said, a lot of questions are open ended and it's those that I'd like to focus on.

    Thanks in advance for your time and help
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    Usually Japan when not on contract
    Posts
    240
    Rep Power
    12

    Thumbs up


    Wow, the exact opposite of the typical "do my homework for me" sort of question. This might be interesting.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    27
    Rep Power
    0
    Chapter 1: Create a custom Calculator

    Exercise 1 Review:

    1. Write a line of code that will print your name:

    Code:
    print("Wretch")

    2. How do you enter a comment in a program?:

    There are two methods:

    The pound key will make python ignore any text that follows it.

    e.g.

    Code:
    #This is a comment
    Alternately, putting any text within triple quotations marks will have the same effect. This second method is useful when the comment is lengthy and uses many lines.

    e.g.

    Code:
    """This comment is long and takes up several lines. Instead of placing '#' on each line, we use triple quotation marks."""

    3. What do the following lines of code output? (python v3.3.1):

    a. print(2 / 3)
    b. print(2 // 3)


    Code:
    print(2 / 3) #will output 0.6666666666666666
    print(2 //3) #will output 0 as 0.667 is rounded down to the nearest integer

    4. Write a line of code that creates a variable called pi and sets it to an appropriate value:

    Code:
    pi = 3.14

    5. Why does this code not work?:

    A = 22
    print(a)


    Improper syntax: the variable name should start with a lower case letter

    e.g.

    Code:
    a = 22
    print(a)

    6. All of the variable names below can be used. But which of these is the better variable name to use?:

    a
    A
    Area
    AREA
    area
    areaOfRectangle
    AreaOfRectangle


    The better variable is:

    areaOfRectangle


    7. Which of these variables names are not allowed in Python? (More than one might be wrong.):

    apple
    Apple
    APPLE
    Apple2
    1Apple
    account number
    account_number
    account.number
    accountNumber
    account#


    The following variable names are not allowed:

    1Apple
    account number
    account.number
    account#


    8. Why does this code not work?

    print(a)
    a=45


    Because the variable is named below the command, hence python does not recognize the "a" variable


    9. Explain the mistake in this code:

    pi = float(3.14)


    While this will still output 3.14 if printed, float is not necessary as it isnt nested in a string. if we were asking the user to input pi, then 'float' would be used so that 3.14 is not read as a string.


    10. Explain the mistake in the following code:

    radius = input("Radius:")
    x = 3.14
    pi = x
    area = pi * radius ** 2


    The value for radius will be read as a string:

    e.g

    Code:
    area = pi * "users input for radius" ** 2
    For the code to work as intended, it could be written as follows:

    Code:
    radius = input("Radius:")
    radius = float(radius)
    x = 3.14
    pi = x
    area = pi  * radius ** 2

    11. Explain the mistake in the following code:

    a = ((x)*(y))


    The x and y variables aren't defined


    12. Explain the mistake in the following code:

    radius = input(float("Enter the radius:"))


    float and input's positions are mixed up

    proper code:

    Code:
    radius = float(input("Enter the radius:")
    Note: Might need explanation as to why this is the case


    13. Explain the mistake in the following code:

    area = π*radius**2


    'π' and 'radius' are not defined as variables


    14. Write a line of code that will ask the user for the length of a square's side and store the result in a variable. Make sure to convert the value to an integer.

    Code:
    length_of_square_side = input("Enter the length of a square's side")
    length_of_square_side = float(length_of_square_side)

    15. Write a line of code that prints the area of the square, using the number the user typed in that you stored in question 9.

    Code:
    length_of_square_side = input("Enter the length of a square's side. ")
    length_of_square_side = float(length_of_square_side)
    area_of_square = length_of_square_side ** 2
    print(area_of_square)
    16. Do the same as in questions 14 and 15, but with the formula for the area of an ellipse:

    Code:
    a_focus = input("Enter the length of focus \'a\'. ")
    a_focus = int(a_focus)
    b_focus = input("Enter the length of focus \'b\'. ")
    b_focus = int(b_focus)
    pi = 3.14
    area = pi * a_focus * b_focus
    print(area)

    17. Do the same as in questions 14 and 15, but with a formula to find the pressure of a gas.

    nRT / V = P

    Where n is the number of moles, T is the absolute temperature, V is the volume, and R is the gas constant 8.3144.


    Code:
    n = input("Enter the number of moles:" )
    n = float(n)
    moles_of_gas = n
    t = input("Enter the absolute temperature:" )
    t= float(t)
    absolute_temperature = t
    v = input("Enter the volume:" )
    v = float(v)
    volume = v
    r = 8.3144
    gas_constant = r
    p = n * r * t / v
    pressure_of_gas = p
    print(p)
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,897
    Rep Power
    481

    better answers to 4 and 5


    #Better answers to 4 and 5:

    #4: line of code to produce pi

    from math import pi






    5. Why does this code not work?:

    A = 22
    print(a)

    This is a name error. The syntax has no problems.

    Comments on this post

    • Wretch11 agrees : Noted and thanks :)
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    Usually Japan when not on contract
    Posts
    240
    Rep Power
    12
    I'll go through and comment anywhere I think something could be usefully expanded. In most cases that will probably mean that I elaborate on an idea related to the question or answer only to plant a seed in your mind. This is to give you some mental brush-clearing ammo later on down the road when you are thinking through some aspect of how Python works.

    Originally Posted by Wretch11
    2. How do you enter a comment in a program?:
    There are two methods:
    ...
    Alternately, putting any text within triple quotations marks will have the same effect. This second method is useful when the comment is lengthy and uses many lines.
    e.g.
    Code:
    """This comment is long and takes up several lines. Instead of placing '#' on each line, we use triple quotation marks."""
    The triple-quote version is also useful for another reason: it is the pretty/easy way of writing docstrings. You might think that docstrings are silly and don't channel your inner bash haXor the way hash comments do, but nearly every auto-doc tool in the Python universe uses them to (amazing) effect.
    Links:
    Once a project gets past the willy-nilly evolution phase the hashes usually disappear and docstrings begin to form the basis for published documentation and API notes.
    6. All of the variable names below can be used. But which of these is the better variable name to use?:
    ...
    The better variable is:
    areaOfRectangle
    Whoever wrote the quiz seems to have not yet lived down his Java experience. In every serious project I've ever worked on in Python folks follow recommendations from PEP 8 -- the Python Style Guide. Class definitions will be CamelCase, constants will be UPPER_CASE and variable and function names will be lower-case with words separated by underscores like_this. So the "best" variable name as per real-world practice wasn't even mentioned: area_of_rectangle.

    Links:

    7. Which of these variables names are not allowed in Python?
    ...
    The following variable names are not allowed:
    ...
    account.number
    An interesting thing about the dot in Python is that it is actually an operator. And it can be overloaded (if you're really nuts). Keep that in mind. Its why line continuations like this work (borrowing an object structure from DJango):
    python Code:
    foo = spam.models.Record.objects\
                    .filter(name='eggs')\
                    .exclude(status='broken')\
                    .order_by('something')

    11. Explain the mistake in the following code:
    a = ((x)*(y))

    The x and y variables aren't defined
    True. But later on in the real world you will very often be looking at snippets where assignments aren't made in the snippet in question -- this is particularly true of functional paradigms. When dealing with n00b code, though, you will nearly always need to see how something was created to find the source of a problem.
    13. Explain the mistake in the following code:
    area = π*radius**2

    'π' and 'radius' are not defined as variables
    Its also usually a bad idea to use non-latin characters as variable names. This isn't absolutely true, but it usually is.
    14. Write a line of code that will ask the user for the length of a square's side and store the result in a variable. Make sure to convert the value to an integer.
    Code:
    length_of_square_side = input("Enter the length of a square's side")
    length_of_square_side = float(length_of_square_side)
    Almost, but that's not a line and length_of_square_side is not an integer. Try:
    python Code:
    length_of_square_side = int(input("Enter length of side:"))

    15. Write a line of code that prints the area of the square, using the number the user typed in that you stored in question 9.
    ...
    16. Do the same as in questions 14 and 15, but with the formula for the area of an ellipse:
    ...
    17. Do the same as in questions 14 and 15, but with a formula to find the pressure of a gas.
    Hmm... is there a pattern here? Why, yes there is. These last three questions may be an attempt to get you to identify task-based abstractions to make your life easier.

    The input task is always the same. So we shouldn't be doing it line by line, because you have to write it again every time. Instead, let's write a function that does it for us:
    python Code:
    def query_length():
        return int(input('Enter length of side of square (as an integer):'))

    Now what about all those tasks up there for determining dimensions? Each one could be wrapped up in its own function as well:
    python Code:
    area_of_rectangle(length, width):
        return length * width
     
    area_of_square(side_length):
        return area_of_rectangle(side_length, side_length)

    And now we have a little human-friendly vocabulary for what is going on that we can string together all at once, or make more conversational by using variable assignments:
    python Code:
    length = query_length()
    print (area_of_square(length))
     
    # or
     
    print (area_of_square(query_length()))

    A similar process can be used to break down the parts of the other questions. When you are writing programs you will almost never identify what can be broken down at the outset. Bear in mind for the rest of your hacker life that simplicity follows complexity -- always. Its how beautifully you can revise your writing that determines how well the final product will be, not how perfect the rough draft is. So write your verbose, ugly, conditional-ridden, tragically-line-continuing, confusing poo first as you think through a problem, and then come back later and re-read it with the intent of identifying the generally useful bits.

    What tends to happen is that whether you actually reuse the parts you think are generally useful again anywhere or not, by breaking them down into mini-functions you reduce the total line-count you are trying to keep in your head at any given time. In Python functions of less than 10 lines are nearly always obviously correct. Functions that span 100 lines tend to merely provide the expected output, but the details are mysterious. Locating a bug in ten 10-liners is almost always easier than locating a bug in one 100 liner.

    That said, when it comes to the core logic of a program a few data structures operated on by a large number of tiny functions is usually better than a large number of data structures masquerading as different aspects of a common concept.

    You clearly understand enough to start working on a small project you care about. I don't think a class is going to help you as much as working on something you care about with a browser open to the Python docs would. Classes are good for people who want to get a certain grade, but people who are self motivated to learn don't seem to benefit from them. If you are going to become a good programmer it'll happen with or without a class.

    The classes that will teach you a lot that would be hard to otherwise learn are things like electrical engineering, processor architecture, digital signals, concepts of design (SICP comes to mind) and compiler/runtime classes.

    Comments on this post

    • Wretch11 agrees : Thank you for being helpful. Much appreciated
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    27
    Rep Power
    0
    Pardon the expression, but holy crap!!

    Wasn't expecting such extensive feedback. -Much- appreciated, you guys are awesome.

    I'll be taking a close look at everything posted and will post questions if I have any.

    In the meantime though, so those interested can see what im working off and what my goals are: Here's the site on which im taking the course : programarcadegames.com

    I'm currently working the lab exercise for chapter 1. I'll post that here as soon as it's completed.

    Oh and just cause im curious. zxq9, say you were a professor and had to grade my work above. What score would you give it?

    Thanks again for the help. I'll make the most of it
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    Usually Japan when not on contract
    Posts
    240
    Rep Power
    12
    I don't have time to really read the site just now, but that looks like a pretty fun way to get your feet wet while touching several aspects of programming.
    Originally Posted by Wretch11
    Oh and just cause im curious. zxq9, say you were a professor and had to grade my work above. What score would you give it?
    Hmmm... grades are hard because I don't know what the rating system would look like. But assuming we're just doing full, partial and no credit per question in the quiz, you'd get a B+ (like 89% or so).

    The detractions would be on 14, 15, 16, and 17, getting half credit for each. While each function accomplished its stated goal, the stated form wasn't adhered to (single line formulations).

    Keep in mind, though, that were I the teacher I wouldn't have written the final four questions in a way that forces a specific notation (nested function called to achieve a single-line). I would have instead hinted more heavily at the compositional nature of functions and stacked the questions in a way that would have naturally led to a task-based breakdown between input, calculation and output tasks in your source file. Then the final questions would require you to compose them into calls that would have probably (but not mandatorily) been single lines, analogous to the way I wrote the input/area/print solution above.

    My goal would have been to structure things so that the right answers were obvious consequences of the path of questioning for the mentally engaged students. (And to leave the lazy ones in the dust and drop them from the course the first chance I got -- which is why I prefer C as a first language for students...)
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    27
    Rep Power
    0
    hmm...would you then recommend that i attempt achieving my current goal (that being: to program a simple arcade game)
    in C instead of python?

    EDIT:

    Chapter 1 Lab Exercise:

    Note: Again, whether the code works or not is simply a matter of using an interpreter, so I know all these work. I'm simply looking for feedback and observations.

    1. Create a program that asks the user for a temperature in Fahrenheit, and then prints the temperature in Celsius. Search the internet for the correct calculation. Look at Chapter 1 for the miles-per-gallon example to get an idea of what should be done.

    Sample run:

    Enter temperature in Fahrenheit:32
    The temperature in Celsius: 0.0


    Code:
    fahrenheit = float (input("Enter the temperature in Farhenheit: " ))
    celcius = (fahrenheit - 32) / 1.8
    print(celcius)
    My Question: This works, but I get 4 decimals with the values i used, which is kind of ugly. How would I go about making the code print a single decimal after the dot?


    2. Create a new program that will ask the user for the information needed to find the area of a trapezoid, and then print the area. The formula for the area of a trapezoid is:

    A = 1/2 (x1+x2) h

    Sample run:

    Area of a trapezoid
    Enter the height of the trapezoid:5
    Enter the length of the bottom base:10
    Enter the length of the top base:7
    The area is: 42.5


    Code:
    print("Area of a Trapezoid")
    height= float (input("Enter the height of a trapezoid: "))
    h = height
    bottom_base = float (input("Enter the length of the bottom base: "))
    x_1 = bottom_base
    top_base = float (input("Enter length of top base: "))
    x_2 = top_base
    half = 0.5
    area_of_trapezoid = half * (x_1 + x_2) * h
    print(area_of_trapezoid)
    This one went well, no questions. Just putting it up in case you guys notice something that could be improved.


    3. Create your own original problem and have the user plug in the variables.

    Code:
    print("An Audi Le Mans accelerates from rest at 5.7 meter/second squared for 8 seconds.What is it's velocity at the end of this time?")
    print(" ")
    starting_speed = float (input("Enter the Audi\'s starting speed: "))
    u = starting_speed
    acceleration = float (input("Enter the Audi\'s acceleration: "))
    a = acceleration
    time = float (input("Enter the time of the Audi\'s acceleration (in seconds): "))
    t = time
    velocity = u + (a * t)
    v = velocity
    
    print("The velocity is equal to", v, "Meters/second squared" )
    My Question: In this one, you might notice that I had to resort to print(" ") to skip a line. Not sure if it's acceptable, but in any case, I'm pretty sure there has to be a proper way to accomplish the same result.

    That's it for this lab, again, thanks in advance
    Last edited by Wretch11; June 29th, 2013 at 03:11 AM. Reason: added lab
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    Usually Japan when not on contract
    Posts
    240
    Rep Power
    12
    Originally Posted by Wretch11
    hmm...would you then recommend that i attempt achieving my current goal (that being: to program a simple arcade game) in C instead of python?
    Not at this point. Its certainly possible to do so, and pretty fun, but you've already got a solid grasp of this environment, so I suggest that you continue on in this way until your basic game is complete.

    One of the cool things about Python (and Haskell, Guile and SBCL) is that you can rewrite any part of your programs in C later on without changing the meaning of the system itself. So the door is open to learn as much about what is really going on down inside the system as you want while working on this same project with which you will already be intimately familiar (a huge bonus).

    That's as good a reason as any to continue to learn the high level architecture stuff now since you're already in that mode and then switch gears later and start learning what the computer is really up to while the game is running.
    How would I go about making the code print a single decimal after the dot?
    There are a number of ways to do this, but the most worthwhile to learn is Python's string formatting. This is a link to the relevant part of the docs.

    You'll wind up with a solution like this:
    python Code:
    >>> f = 34.2452464
    >>> f
    34.2452464
    >>> '{0:.1f}'.format(f)
    '34.2'

    As a side note Python is one of the very few open source projects out there with extremely thorough, robust, readable and complete documentation. I recommend you spend a day skimming through the tutorial and the language reference to get an idea what is available so you know where to poke around next time you have a question like this.
    Code:
    print("Area of a Trapezoid")
    height= float (input("Enter the height of a trapezoid: "))
    h = height
    bottom_base = float (input("Enter the length of the bottom base: "))
    x_1 = bottom_base
    top_base = float (input("Enter length of top base: "))
    x_2 = top_base
    half = 0.5
    area_of_trapezoid = half * (x_1 + x_2) * h
    print(area_of_trapezoid)
    This one went well, no questions. Just putting it up in case you guys notice something that could be improved.
    Right now it is a series of steps, not really a program. What I mean is that nothing about it is usable anywhere else and there is no concept of abstraction or labeled procedure aggregation. For example, the input tasks are intermixed with the processing tasks -- which is nearly always inappropriate. You should start thinking about program structure right now, not just the mechanics behind getting the output you want.

    Remember, you are working in a very high level language at the moment so you need to be concentrating your effort on understanding how abstraction works. If we were going to just work on how to make a computer perform a fixed series of actions then we would be studying assembler instead of Python.

    With the above in mind, what you wrote is not bad, it is merely incomplete. Its not worthy of your name in a comment line just yet. Nearly all programs go through this phase, though, which means you made a good start, just haven't continued on developing it from the stage of being a hacked-together series of steps to where the result is a well structured program that is composed of well defined elements that can be read as a sort of prose.

    That might not make sense just yet, but keep the idea of evolving programs in the back of your mind and you will be making small revelations in this direction daily for the rest of your life.
    In this one, you might notice that I had to resort to print(" ") to skip a line. Not sure if it's acceptable, but in any case, I'm pretty sure there has to be a proper way to accomplish the same result.
    Here once again there are a lot of ways to accomplish this, all the way from doing what you just did to appending a newline character at the beginning or end of whatever string is being printed to clearing the screen to taking control of the terminal and positioning the cursor yourself to making a full-screen terminal application with ncurses. For now, don't worry about it. If it bugs you enough (and it probably will eventually) skim through the Python docs and try out some of the formatting and pretty print options and functions available.
  18. #10
  19. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,897
    Rep Power
    481

    documentation


    Tests are critical. The doctest module gives the means to both test your code and document it at the same time. Python3 also accepts annotations. Short of literate programming in noweb or external documents, this short program demonstrates all but one of the documentation schemes I can think of at the moment. The other scheme is a use case testing framework such as unittest distributed with python or nosetest.
    Code:
    '''
        doctests show how to use your codes and test them as well!
        Run the doctest with
    
        $ python -m doctest -v this_file.py
    
    
        >>> # 'annotations'
        >>> document.__annotations__ == {'function': str, 'python': 3, 'return': str}
        True
    
        >>> # used by interactive help and (probably) by pydoc
        >>> help(document)
        Help on function document in module p:
        <BLANKLINE>
        document(python: 3, function: str) -> str
            docstring!
            Programmer can use the annotations for type checking.
        <BLANKLINE>
    
        >>> # function output
        >>> print(document('the annotations are any object','and are unused by python'))
        still another way to document programs
    '''
    
    # a comment
    def document(python:3, function:str)->str:
        '''
            docstring!
    	Programmer can use the annotations for type checking.
        '''
        return 'still another way to document programs'
    [code]Code tags[/code] are essential for python code and Makefiles!
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    27
    Rep Power
    0
    Code:
    #imports
    import random
    
    # Variables
    strength = 8
    dex = 8
    con = 8
    wis = 8
    intel = 8
    cha = 8
    x_str = random.randrange(12)
    x_dex = random.randrange(12)
    x_con = random.randrange(12)
    x_wis = random.randrange(12)
    x_int = random.randrange(12)
    x_cha = random.randrange(12)
    total_str = strength + x_str
    total_dex = dex + x_dex
    total_con = con + x_con
    total_wis = wis + x_wis
    total_int = intel + x_int
    total_cha = cha + x_cha
    
    reroll = False
    while not reroll:
        if total_str == 19:
            total_str = total_str - (random.randrange(7) // 2)
            print(total_str)
        if total_dex == 19:
            total_dex = total_dex - (random.randrange(7) // 2)
            print(total_dex)
        if total_con == 19:
            total_con = total_con - (random.randrange(7) // 2)
            print(total_con)
        if total_wis == 19:
            total_wis = total_wis - (random.randrange(7) // 2)
            print(total_wis)
        if total_int == 19:
            total_int = total_int - (random.randrange(7) // 2)
            print(total_int)
        if total_cha == 19:
            total_cha = total_cha - (random.randrange(7) // 2)
            print(total_cha)
                                
        else:
            print("Str:", total_str, "Dex:", total_dex, "Con:", total_con, "Wis:", total_wis, "Int:", total_int, "Cha:", total_cha)
            print(' ')
        roll_dice_again = input ("Do you want to reroll stats? ")
        if roll_dice_again != 'y':
            reroll = True;
    Question: I'm trying to loop a bit of code that prints a series of variables + a series of randomly generated variables.
    For some reason, when I loop, the program keeps re-printing the previous results. Could someone shed some light?

    Thanks in advance
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    Usually Japan when not on contract
    Posts
    240
    Rep Power
    12
    Because you only assigned your variables once. Assignment isn't a part of the loop, so the original values are the only thing to print.

    Break the big list of variable assignments out into its own function, then call it from within the loop and you'll get new values each time. Actually, since all of your tasks are redundant you can get a lot of benefit out of loops in general:
    python Code:
    from random import randrange
     
    # Stat generation is a task your game will have to do all the time, so
    # let's name this task instead of just making it some inline thing:
    def gen_stats(base=8, favor=12, curse=7):
        # Let's make the list of possible stats. Computers are good at
        # processing lists of things, so this way we can minimize your work.
        STATS = ['str', 'dex', 'int', 'con', 'wis', 'cha']
     
        # Now let's loop through these to assign them to a single structure
        # that represents a single character's stats, all in one place.
        char_stats = {}
        for s in STATS:
            blessing = randrange(favor)
            total = base + blessing
            if total == 19:
                total = total - (randrange(curse) // 2)
            char_stats[s] = total
        return char_stats
     
    # Now do the loop:
    reroll = False
    while reroll is False:
        # Generate a stats dictionary
        stats = gen_stats()
        # print() stats here
        # Ask user if they want to reroll, etc.

    Now we have done something special (other than avoided mountains of typing by making loops work for us). We have a generally useful function, gen_stats(), that can generate stats for any sort of character -- a player, an NPC, a mob, a fireball, whatever. This is at the heart of program design.

    As for the detail of the question you asked, you weren't generating any values in your loop, just knocking them down from the point cap of 19 the first time through (the second time through nothing would be at 19 anymore, so all those "if" statements would have been false anyway). The call to gen_stats() above, however, is happening within the loop body which means that the stats dictionary is refreshed every time the loop executes.

    Loops are awesome things. Consider that without comments the code above is only 14 lines. Line count is not the measure of a program, of course, but whenever you find yourself writing lines that mean identical things over and over it is a sign the computer should be doing all that writing for you.

    Comments on this post

    • Wretch11 agrees : Immensely helpful tip.
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    27
    Rep Power
    0
    Ok, seeing as i haven't covered functions in my course yet, lemme just summarize this out loud to see if I understand what's going on in the code. I'll be jumping some self explanatory lines:

    on line 5: you created a function called gen_stats and gave it three arguments

    on line 8: you created a list of strings as a value for the STATS variable and nested it in the gen_stats function

    on line 12: you created a variable called char_stats and gave it a value of { } (not quite sure on this one)

    on line 13: you created a for loop that will loop until all the strings in the STATS list have been returned

    on line 14: you made the blessing variable equal to a random number between 0 and 11 (inclusive)

    on line 15: you created a total variable equal to gen_stats' base argument plus the result of gen_stats' blessing argument

    on line 19: you create a variable named char_stats and make it equal to the total variable. (Only thing i'm not clear on hear is the [s] after the char_stats variable name. I figure it relates to the 'for s in STATS' but aint exactly sure how.

    The rest is fine.

    Another Question: The end result prints {'con': 12, 'cha': 13, 'dex': 14, 'str': 10, 'wis': 8, 'int': 8}

    How would I go about removing the brackets and quotation marks so as to be left with:

    con: 12, cha: 13, dex: 14, str: 10, wis: 8, int: 8

    Thanks again for taking the time to explain.
  26. #14
  27. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    Usually Japan when not on contract
    Posts
    240
    Rep Power
    12
    I appologize for using so many constructs with which you are not yet familiar. Fortunately you are paying attention, and basic Python constructs are generally readable by people who are paying attention (which you just totally proved -- sort of cool, actually).

    [] denotes a list, () denotes a tuple, and {} denotes a dictionary.
    You access all in a very similar fashion, but each has its own way of doing things.

    A list acts much like an array in C. You can add things to it, cut things from it, insert in random places, use it as a stack, etc. Its an inherently mutable (changable) list of things. The accessor is by index position within brackets after the name of the list (and there is slice/step notation, but don't worry about that now).

    Accessing things in a tuple works the same as accessing things in a list. A tuple is not changable after you create it, though, so there is no inserting or stripping or popping or whatever going on. A tuple, once created, is unchangable. Why would you want such a thing? Well, a list should be of things but it is safe to describe something in terms of a tuple. What that means is, you can tell your program that foo[0] is always a string that is the name of an NPC, foo[1] is always its spawn location, and so on because a tuple can't accidentally get sorted, popped, inserted to or anything and accessing tuple values is very fast compared to lists and especially dictionaries. So positions within a tuple are free to mean something. Members in a list, on the other hand, should be completely self-contained -- which means that a list of tuples is a natural way to express a list of complex values if you choose to go that route.

    But these days processing is pretty cheap and core memory is really fast -- so for most complex values people use dictionaries. Here instead of a numeric index you can have a value of (nearly) any type -- including a string to use as a label as a key which points to whatever the value is. You access a dictionary value the same way you access a list or tuple value, but instead of the index being a numeric position in the array, you use the key value and get back whatever the key pointed at. You can also add new elements to a dictionary on the fly, so long as the new key you add doesn't already exist (if it does it will reassign the value, not add a new one). So...
    python Code:
    >>> foo = {'str': 15, 'int': 12}
    >>> foo['str']
    15
    >>> foo['dex'] = 18
    >>> foo['dex']
    18
    >>> foo['str'] = 13
    >>> foo['str']
    13

    So what was going on with the for loop over STATS? In a for loop you declare a temporary variable to hold each successive element of whatever you are looping over. So the "s" variable actually contained one of the strings in STATS each iteration and used it as a key in char_stats[s]. I created an empty dictionary with the statement "char_stats = {}" so that we would have something to start working with, and added new elements as the loop proceeded.

    And finally, about that function definition... I provided some arguments -- but I also included default values. If I call the function missing any values then the defaults will be assumed. If I call the function with my own argument values those will be used instead. Pretty simple to get used to -- in fact some things about Python argument handling will spoil you.

    I know you're in the middle of a course, but if you have an hour or so to spare I strongly recommend giving this a scan:

    Within an hour or so you can learn everything you need to read most stuff, or at least know where to reference things the next time you encounter something you don't recognize.

    Get familiar with the Python docs. Its got some of the best online documentation anywhere. I've never even read a Python tutorial or anything -- the docs are so good that I just started writing programs straight from the language reference and never stopped. Along the way I learned a million new things about the language (its a pretty large language compared to C and most Lisps), most of which are not essential but are really slick once you learn how to use them.

    I wrote an article about version string comparison that uses a lot of iterable (list-like) features in Python which includes some examples which might be interesting to you:
    Last edited by zxq9; July 1st, 2013 at 11:05 AM.
  28. #15
  29. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    27
    Rep Power
    0
    Sorry if I seem slow on the uptake, all the new terminology alone is enough to give pause and considering this is my 6th day learning Python and that I have -zero- prior experience with programming... let's just say this is all very new.

    But anyway let's see if I can put some of what you just explained into my own words.

    Basically the { } (dictionary) in the char_stats variable works as an empty placeholder that gets populated with the results of the 'total' variable as they loop?

    Also, the [s] in front of 'char_stats[s] = total' basically fetches strings from the STATS list, which is then paired to the result of each 'total' inside the dictionary?

    is that close to right?
Page 1 of 4 123 ... Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo