Ene Uran 638 Posting Virtuoso

A first quick look revealed a number of things. Give attention to my comments marked with "!!!!". Here is code that should work, so you can improve on it:

# this is supposed to be simple
# I am trying to simulate combat
# As easy as I can
# "Untitled"
# By Franki
# You find the crystals to destroy the Solomon Terminal

import random   # needed for random.randrange(2) or other random thingies

crystals = 0

"""
# declare global variables inside functions only!!!!
global gotCrystal_1
global gotCrystal_2
global gotCrystal_3
global gotCrystal_4
global gotGold_1
global gotGold_2
global gotGold_3
global gotGold_4
"""

# use False, later set to True, is more readable
gotCrystal_area1 = False
gotCrystal_area2 = False
gotCrystal_area3 = False
gotCrystal_area4 = False

gotGold_area1 = False
gotGold_area2 = False
gotGold_area3 = False
gotgold_area4 = False

gold = 0

# I am using Classes to make monsters (I don't know why)
# so you can later refer to as bad_warrior.level, should be 3
# or bad_hunter.name which is 'Cavernian Hunter'
# you can also define some action within the class
class Monster(object): 
    """Monster"""
    def __init__(self,name,level):
        self.name = name
        self.level = level

# The Monsters
bad_hunter = Monster("Cavernian Hunter","1")
bad_scout = Monster("Cavernian Scout","2")
bad_warrior = Monster("Cavernian Warrior","3")
bad_commander = Monster("Cavernian Troop Commander","4")

def place_monster():
    # the integer 1 places Monster, all others place nothing
    Monster_in = random.randrange(2)    # replaced MOnster_in with Monster_in spelling!!!!!
    if Monster_in == (0 or 2):
        return 0
    Monster = random.randrange(4)
    if Monster == 0:
        Monster = …
Ene Uran 638 Posting Virtuoso

Read on another forum:

With Python you learn how to drive the car, with C++ you learn how to build the car.

Ene Uran 638 Posting Virtuoso

Use:

os.path.exists(filename)  # returns True or False

I you don't want to truncate an existing file with 'w' or 'w+' use the 'a' option for append.

Ene Uran 638 Posting Virtuoso

You may want to change the 12 to more spaces, or the scores gets pushed to the right, still readable, just not as pretty.

Here is an another example of formatting:

def format_dollar(amount):
    """formats amount to dollars and cents"""
    return "$%.2f" % amount

print format_dollar(123.9 * 0.07)  # $8.67
Ene Uran 638 Posting Virtuoso

As far as I know only wxPython has a password option, the Tkinter Entry widget does not. An easy way to get around this, is to give the password entry widget a bg="yellow" and fg="white". This will be very hard to see for a bystander, as you type in the password, after the return key has been pressed clear the contents. If you want to be tricky, rather then clear, put in a silly password.

If you don't want to show your password in your code see:
http://www.daniweb.com/techtalkforums/post220840-56.html

Ene Uran 638 Posting Virtuoso

Printing with a format string comes in handy with tables. Let's say you have a list of player scores:

player_scores = [
["Freddy", 9234],
["Grace", 8723],
["Nutty Fuddy", 7143],
["Lurcher", 9545]]

for ps in player_scores:
    player = ps[0]
    score = ps[1]
    print player, score

"""
somewhat ugly:
Freddy 9234
Grace 8723
Nutty Fuddy 7143
Lurcher 9545    
"""

print "-"*50

for ps in player_scores:
    player = ps[0]
    score = ps[1]
    print "%-12s %d" % (player, score)

"""
much nicer table:
Freddy       9234
Grace        8723
Nutty Fuddy  7143
Lurcher      9545    
"""
Ene Uran 638 Posting Virtuoso

Each time you move s, n, e, or west heal the monster(s) a little. That would be in your while loop's if command == 's' etc.

Ene Uran 638 Posting Virtuoso

This from the Win32 Programmer's Reference:

The GetPixel function retrieves the red, green, blue (RGB) color value of the pixel at the specified coordinates.

COLORREF GetPixel(

HDC hdc, // handle of device context
int XPos, // x-coordinate of pixel
int nYPos // y-coordinate of pixel
);


Parameters

hdc

Identifies the device context.

nXPos

Specifies the logical x-coordinate of the pixel to be examined.

nYPos

Specifies the logical y-coordinate of the pixel to be examined.

Return Values

If the function succeeds, the return value is an RGB value. If the pixel is outside of the current clipping region, the return value is CLR_INVALID.

Remarks

The pixel must be within the boundaries of the current clipping region.
Not all devices support GetPixel. An application should call GetDeviceCaps to determine whether a specified device supports this function.

A related function SetPixel() is used in one of the C code snippets about plotting. Vegaseat is probably right, for low level things like direct screen access C or C++ is best.

Ene Uran 638 Posting Virtuoso

To me VBasic is almost unreadable! Does it still produce a zillion different files for every small program you write?

I keep hearing that MS is dropping any further development with VB.

Ene Uran 638 Posting Virtuoso

I have to applaud your teacher for teaching Python rather than the usual "ugly syntax stuff" like C, C++ or Java. Colleges with their all too often ultra conservative teachers are just warming up to Python. So you and your teacher are way ahead!

I will be playing around with your code to get a feel, then let you know what I think.

Here is a quote from Donald Knuth who has written many books on computer science:

Donald E. Knuth, December 1974 -->
"We will perhaps eventually be writing only small
modules which are identified by name as they are
used to build larger ones, so that devices like
indentation, rather than delimiters, might become
feasible for expressing local structure in the
source language."

Ene Uran 638 Posting Virtuoso

Works nicely, welcome to GUI programmig! You seemed to have learned quite a bit!

Now, you can do a few cosmetic improvements, like making all the buttons the same sice and introducing some color.

Just a matter of taste, but I would have lined up all the buttons on top of each other for now. Later, as you add more links, use grid() to locate/group them in an order.

Great job!

Ene Uran 638 Posting Virtuoso

Here is a mildly more modern way:

// convert string to all lower case

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>

using namespace std;

int lower_case ( int c )
{
  return tolower ( c );
}

int main()
{
  string s = "THIS IS A TEST";

  transform( s.begin(), s.end(), s.begin(), lower_case );
  cout << s << endl;
}

I know you are looking also at Python:

str1 = "THIS IS A TEST"
str2 = str1.lower()
print str2

Or as a one-liner:

print "THIS IS A TEST".lower()
Ene Uran 638 Posting Virtuoso

Let's not forget the Python allows Functional (ala Lisp) and Meta Programming. Just a different approach (higher level) to pogramming.

Do we need that?
Once you play with it you'll miss it!

Ene Uran 638 Posting Virtuoso

The size of a character in a string is a byte. You could use ord() and chr() to convert back and forth. Make your life interesting!

Ene Uran 638 Posting Virtuoso

The integer is the smallest number in Python.

For the purpose of shift and mask operations, integers are assumed to have a binary, 2's complement notation using 32 or more bits, and hiding no bits from the user (i.e., all 4294967296 different bit patterns correspond to different values).

Ene Uran 638 Posting Virtuoso

What do you mean with reversing a hex string?

Ene Uran 638 Posting Virtuoso

I think we just had a discussion related to the same issue at:
http://www.daniweb.com/techtalkforums/thread55436.html

Ene Uran 638 Posting Virtuoso

At first glance, random.choice('01') returns a string '0' or '1' so your if statement has to reflect that:

def fight_unicorn():
    global monster_HP1
    global hp
    hit_miss = random.choice('01')
    if hit_miss == '1':                  #!!!!!!!
        print "You hit the monster!"
        monster_HP1 = monster_HP1 - 1
        if monster_HP1 == '0':      #!!!!!!!!
            print "You win!"
            master_bedroom()
        else:
            monster_turn1()
    else:
        print "You Missed"
        monster_turn1()

def monster_turn1():
    monster_hit = random.choice('01')
    if monster_hit == '1':             #!!!!!!
        print "You are hit!"
        hp = hp-1
        if hp == 0:
            print "Game Over"
    else:
        print "The monster missed"
        fight_unicorn()

Note, if you want an integer returned, use one of the following:

x = random.choice([0, 1])
print x, type(x)  # testing

x = random.randrange(0, 2)
print x, type(x)

x = random.randint(0, 1)
print x, type(x)
Ene Uran 638 Posting Virtuoso

In the case of:

import random
random.randint(5)

random is a module, and you are using the namespace random. Note that random is not a class!

To find out if an object is a class use something like this:

import inspect
if inspect.isclass(object_name):
    print "object_name is a class"

Generally, Python recommends to start class names with a Capital letter. This disinguishes them from module namespaces.

Here is a case where making an instance of an empty class means something:

class Employee:
    pass


john = Employee() # Create an empty employee record/struct
ted = Employee()

# fill the fields of the record/struct
john.name = 'John Johnson'
john.dept = 'computer lab'
john.salary = 3000

ted.name = 'Ted Tetris'
ted.dept = 'human resources'
ted.salary = 5000

print "%s works in the %s and earns $%s/month" % (john.name, john.dept, john.salary)

In other words, you can create new class variables outside the class!

Ene Uran 638 Posting Virtuoso

I use the DrPython IDE and that one allows me to set arguments like they would come from the command line.

Take a look at:
http://www.daniweb.com/techtalkforums/post193207-50.html

I have used a default argument under the else, particular for testing a program.

Ene Uran 638 Posting Virtuoso

Its me, Ene,
note that each button ends up executing a function defined in the program. The button uses the command=function statement. The function is activated via its object (ie. just function rng), and not the usual function call (ie. would be rng() ).

Also note that rng is not a keyword, but just a name vegaseat picked for the function he defined earlier. So if you want an RNG going, put it into the function rng() (or whatever you want to name it), then activate it via command=rng.

reRanger commented: Always helpful and nice ;) +1
Ene Uran 638 Posting Virtuoso

I took the liberty to modify vegaseat's previous example code to show you how buttons would work:

from Tkinter import *

root = Tk()
root.title("Press Button!")

def show_image2():
    canvas1.create_image(x, y, image=photo2)

def show_image3():
    canvas1.create_image(x, y, image=photo3)


# pick three GIF image files you have in your working directory
# image1 is larger than image2 and image3
# create all three image objects now
image1 = "Red200x200.GIF"
photo1 = PhotoImage(file=image1)

image2 = "Green100x100.GIF"
photo2 = PhotoImage(file=image2)

image3 = "Blue100x100.GIF"
photo3 = PhotoImage(file=image3)

# make canvas the size of image1/photo1
width1 = photo1.width()
height1 = photo1.height()
canvas1 = Canvas(width=width1, height=height1)
canvas1.pack()

# display photo1, x, y is center
x = (width1)/2.0
y = (height1)/2.0
canvas1.create_image(x, y, image=photo1)

# create two buttons to display smaller images
btn1 = Button(root, text="Image2", command=show_image2)
btn1. pack()
btn2 = Button(root, text="Image3", command=show_image3)
btn2. pack()

root.mainloop()
Ene Uran 638 Posting Virtuoso

I don't know what editor you are using, but for some odd reason you lost all the indentations (critical for Python to work). I doctored up your code and added a number of temporary print statements, always good for troubleshooting. I noticed that your mult() has no return statement, so result = None is the returned.
Here is the doctored code:

class dimensions:
    def __init__(self, listofTuples):
        self.expr = listofTuples
 
    def sub(self, other):
        for value in self.expr:
            if not value in other.expr:
                return "incompatible"
            return self.expr

    def mult(self, other):
        tempTuple1=list()
        tempTuple2=list()
        print tempTuple1 # []
        print tempTuple2 # []
        print other.expr # [('j', 2), ('km', 1), ('f', 5)]
        print self.expr  # [('j', 2), ('f', 1)]

        i=0
        for unit,value in other.expr:
            for unit2,value2 in self.expr:
                if unit2 == unit:
                    tempTuple1.append((unit, value+value2))
                    tempTuple2.append(())

##      for unit2,value2 in self.expr:
##          for unit,value in other.expr:
##              if unit2 != unit:
##                  tempTuple1.append((unit2,value2))
 
        print tempTuple1 # [('j', 4), ('f', 6)]
        print tempTuple2 # [(), ()]
        # what does mult() return?????

t = dimensions([('j',2),('km',1), ('f',5)])
print t # <__main__.dimensions instance at 0x00AE6BE8>
w = dimensions([('j',2),('f',1)])
print w # <__main__.dimensions instance at 0x00AE6EE0>
print w.mult(t) # gives None, correct since there is no return

How new are you to Python?

Ene Uran 638 Posting Virtuoso

You need to give us more of your code, otherwise this will be an exercise in mind reading!

Ene Uran 638 Posting Virtuoso

Nice, nice, nice and spooky!!!! Just in time for Halloween!
I haven't tested it all the way, but made few recommendations and corrections indicated by the #!!!!! marks:

#Text Adventure.py
#By Chris O'Leary

# functions will pick the external gold value (for instance), as long as gold is not 
# a variable declared locally inside the function, this behaviour may change in future
# versions of Python, the safest way would be add the statement "global gold" to each 
# function that uses it !!!!!!!!!!!!

"""
# global declarations go into the functions that use them!!!!!
global gold
global gotGold_reading
global gotGold_SQ
global gotGold_liv
global gotGold_draw
global gotGold_din
"""

gold = 0
gotGold_reading = 0
gotGold_SQ = 0
gotGold_liv = 0
gotGold_draw = 0
gotGold_din = 0

# recommend to make help a function and give a few more details ...
def help():
    print "look, examine (object), n, w, e, s, take (item)"
    print "Example: examine vase, take gold"

    

def start():
    print '''
        ADVENT HOUSE v1.0
    You find yourself in the foyer of a large house. You
    have no idea how you got there. You look around, and see the front door.
    It is locked and barred, and the bar is nailed down. There is
    no way to open it. There are three other doors in the area. A voice says
    '50 gold is what you need,
    to escape my grasp, of this take heed!'

    Note: All instructions must be typed in small letters. No capitals.'''
    # recommend …
Ene Uran 638 Posting Virtuoso

Sorry, shoud have read your info better. Here is a potential solution, using images, where a somewhat larger canvas forms a frame for the picture:

# image load and display using Tkinter only
# Tkinter reads only GIF and PGM/PPM images
# (for additional formats use Image, ImageTk from PIL)

from Tkinter import *

root = Tk()

# pick a GIF or PGM/PPM file you have in your working directory
imagefile = "Image1.gif"
photo1 = PhotoImage(file=imagefile)

width1 = photo1.width()
height1 = photo1.height()
# make canvas 100 pixels larger than the picture to create a frame
canvas1 = Canvas(width=width1+100, height=height1+100, bg='red')
canvas1.pack()

# anchor=CENTER is default
# x, y forms the center coordinates here, this gives image a red frame ...
x = (width1+100)/2.0
y = (height1+100)/2.0
canvas1.create_image(x, y, image=photo1)
root.mainloop()

Hope your images are pretty well fixed in size, otherwise you have to fix the size of the canvas to fit all your images. Have fun with the coding!

Ene Uran 638 Posting Virtuoso

Are you thinking of somethig like this?

# explore Tkinter canvas.create_rectangle(x0, y0, x1, y1, option, ...)

from Tkinter import *

root = Tk()
root.title("Tkinter Rectangle")

canvas = Canvas(root, width=400, height=400)
canvas.pack()

# red rectangle is drawn with corner 
# coordinates x1=50, y1=50 and x2=350, y2=350
canvas.create_rectangle(50,50,350,350,fill='red')

# draw a smaller blue rectangle on top of the larger one
canvas.create_rectangle(150,150,250,250,fill='blue')

root.mainloop()
Ene Uran 638 Posting Virtuoso

This seems to work too:

a = unichr(88).encode('utf8')
b = unichr(257).encode('utf8')
c = unichr(109).encode('utf8')
d = unichr(258).encode('utf8')
print a,b,c,d
e = a+b+c+d
print e
print
for c in e:
    print c
print
for i in e.decode('utf8'):
    print ord(i)
Ene Uran 638 Posting Virtuoso

I agree, Python is fun! Take a look at:
http://www.daniweb.com/techtalkforums/post225611-64.html
You can modify this to fit your needs.

Ene Uran 638 Posting Virtuoso

I enjoyed the flow of this discussion, learned a lot!

Ene Uran 638 Posting Virtuoso

I am willing to wait! Good things take their time. Hehe, try to tell that to your boss!

Ene Uran 638 Posting Virtuoso

The major difference between C++ and Python is that Python compiles source code to byte code and then interprets the byte code. There are programs that combine the byte code with the interpreter and package to an executable for distribution. More and more computers have Python already installed, so you can just distribute your Python programs as source code, or more secretive byte code.

Some programs can run slower than the corresponding C++ program, but there are ways around this with modules written in C or C++, or just in time compilers similar to Java. Python has an easy way to handle modules.

Python is a high level language, very powerful, very modern, with a wealth of builtin classes and functions/methods. For instance, most of the STL containers that you are familiar with in C++ are builtin. If its not built into the language it is supplied as modules. Many modules are written in C or C++, transparent to you. Python has a very efficient memory manager builtin, so the notorious memory leaks of C++ are gone!

The major advantage of Python over C++ is its rapid development time for programs. On the average, programs are developed up to 10 times faster. Python code is easy to write, read, test and maintain. One of the reasons that Google uses Python extensively. Microsoft does not, and seems to lack behind most of the time. In my opinion, knowing C++ and Python is the best of both worlds.

Ene Uran 638 Posting Virtuoso

You are off to an interesting start! Nice foyer, hehe, almost like mine at home!

Declare the variable gold global in each function that uses this global variable. This would also apply to strength, weapons, or any monster-kill flags. If a monster has been killed in a room you can set the flag so that this monster does not attack again. Of course you could revive the monster and make things much more difficult.

Sorry, I just realized that in your first version you might not go with monsters yet. Just explore, find enough gold, and get out! It will be interesting to read all your room descriptions.

Ene Uran 638 Posting Virtuoso

It depends what you want to do. If you just want to make a simple fun game, there is no need for class objects. If you want to to do this to learn OOP, then by all means go for it. Your progress will be initially slow, because there is quite a learning curve.

Your approach making a class Room with the basics that all rooms can share, and then a class for each individual room that inherits the class Room makes the most sense. However, a lot of thought has to be put into this approach before any of the fun starts.

Just let us know what you have come up with, and how you would test each class to make sure it does what you want it to do.

Ene Uran 638 Posting Virtuoso

You really don't need the function press_enter() there, since you are already executing your selected program.

Ene Uran 638 Posting Virtuoso

The easiest game would be with a number of rooms. Draw yourself a map of 9 rooms (maybe a 3x3 pattern). Make notes on the map about details of the room, number of doors, contents, pictures, furniture and so on.

Let's say you come into the first room from the south. Now this room has a total of 4 doors, one to the south (S) where you came in, one to the east (E), north (N) and west (W). Ask the player which door he/she wants to enter. Like: "You want to go E, N or W?"

Rooms may have 2, 3 or 4 doors. Now the adventure begins. Some rooms contain a strength potion, or weapon, or some treasure, or cryptic instructions to read, or monsters to fight. When you fight a monster you lose strength. Some monsters are stronger than others. The player starts with a certain amount of strength points and gains more strength by picking up strength potions. Also loses less strength by picking up a better weapons. Each weapon has hit points, the more the better!

Describe the new room as the player enters. Like: "You entered a room that is painted green. There is a picture on the wall of an elderly gentleman. There are 5 gold pieces on the table for you. There are doors to the E and W. Do you want to go E or W?"

The rest is up to your imagination. When the player finds …

Ene Uran 638 Posting Virtuoso

many thanks

how to add enter function in this script?

Very simple:

raw_input("Press Enter ...")  # wait till the Enter key is pressed

or ...

def press_enter():
    raw_input("Press enter to continue ...")

Python does not have a clear the screen function, but you could add:

print '\n' * 25

or:

import os
os.system('clear') # linux

instead of clear.

Ene Uran 638 Posting Virtuoso

Your or statements weren't written correctly. In this case it's simpler to see if the word is in a tuple (or list) of choices:

#1337 to Human dictionary:
    
leet = {
"1337": "l-EET/nReally Awesome",
"noob": "(n00b) nOOb/nPerson who can't accept that s/he's wrong",
"-xxors": "Suffix, pron: zors.\nUsed to accent an important verb, e.g. roxxors",
"newb": "new-b,\nPerson who is new to a game and needs help. Not to be\nconfused with noob"
}
    
word = 1
while word not in ("", "0"):
    word = raw_input("Input a word to define: ")
    # correct use of or ...
    if word == "noob" or word == "n00b" or word == "nOOb":
        print leet['noob']
    # simpler, is word in a tuple (or list) ...
    elif word in ("leet", "elite", "1337", "l33t"):
        print leet['1337']
    elif word in ("xxors", "roxxors", "boxxors", "-xxors"):
        print leet['-xxors']
    elif word in ("newb", "newbie"):
        print leet['newb']
Ene Uran 638 Posting Virtuoso

Nice code so far!
It would be easier on the user, if you only ask the user numbers to be entered once and then run the computer numbers against that! I like your compare, but there is a flaw. Lists [1,2,3,4,5,6] and [1,3,4,5,6,7] should have 5 matches, your compare would only show 1 match. I got to have time to look at it closer. To segregate 3, 4, 5 or 6 matches you just establish a counter for each. You might have to go to a million plus tries to get 6 matches!

Ene Uran 638 Posting Virtuoso

This example uses list comprehension to remove duplicate elements, and is a modified version from vagaseat's code snippet at: http://www.daniweb.com/code/snippet454.html

gwb = "We got into deficit because the economy went into the recession that is how we got into deficit"

# convert to all lower case words
gwb = gwb.lower()

# form a list of words
rawList = gwb.split()

print "The raw list containing duplicates:"
print rawList

"""
result -->
The raw list containing duplicates:
['we', 'got', 'into', 'deficit', 'because', 'the', 'economy', 'went', 'into', 'the', 'recession', 'that', 'is', 'how', 'we', 'got', 'into', 'deficit']
"""

# create an empty list
uniqueList = []
# use list comprehension to exclude duplicate words when forming uniqueList
[uniqueList.append(str1) for str1 in rawList if not uniqueList.count(str1)]

print "\nThe unique list (no duplicates):"
print uniqueList

"""
result -->
The unique list (no duplicates):
['we', 'got', 'into', 'deficit', 'because', 'the', 'economy', 'went', 'recession', 'that', 'is', 'how']
"""
Ene Uran 638 Posting Virtuoso

To make this song challenging you could change part of it:

def print_charlieVerse():
    print "Charlie was a pidgeon, a pidgeon, a pidgeon."
    print "Charlie was a pidgeon, a pidgeon that flew."
    print "He flew in the morning, he flew in the night."
    print "And when he came home he was covered in str3"   # covered in what?
    print

Where str3 rhymes with night and comes at random from a list of words.
Or, more involved:

def print_charlieVerse():
    print "Charlie was a pidgeon, a pidgeon, a pidgeon."
    print "Charlie was a pidgeon, a pidgeon that flew."
    print "He flew in the str1, he flew in the str2."
    print "And when he came home he was covered in str3"   # covered in what?
    print

Where str1 and str2 make sense and str3 rhymes with str2. You could also replace "flew", and be really annoying!

Ene Uran 638 Posting Virtuoso

Several problems with your program, I corrected some of them:

from Tkinter import *

root = Tk()

def hello():
    print "Hello!"

# removed unneeded arguments (metre,cm)
def metres_to_centimetres():
    metre = input("Put in a distance in metres: ")
    cm = metre*100
    print "Distance in Centimetres = ",cm
 
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Hello", command=hello)

# command accepts a function object but not a function call
# to pass any arguments you have to wrap the object in lambda
#filemenu.add_command(label="M to Cm", command=metres_to_centimetres(metre,cm))  # gives error
# actually you don't need to pass any arguments
filemenu.add_command(label="M to Cm", command=metres_to_centimetres)

filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
mainloop()

Now the major problem is that you are mixing console only functions like print and input with a GUI environment. In a GUI program you use widget Label for prompts and results, and widget Entry for data entry/input or display. Actions are generally done with a button click. Here is an example:

# example of a labeled data entry, a button and a result label
# use grid to position widgets, also set cursor to focus on entry
# a rather generic Tkinter GUI template for calculations

from Tkinter import *

def calculate():
    try:
        # get the enter1 value
        # use float() for either float or integer entry
        num1 = float(enter1.get())
        # do the calculation
        result = num1 * 100
        # display the result string
        # use str() to convert numbers to string for concatination with +
        label2.config(text=str(num1) + 'meters = ' …
Ene Uran 638 Posting Virtuoso

I think vegaseat meant "Projects for the Beginner" to be for the beginning programmer who understood the basics of Python and wanted to do something with that knowledge. It was probably not meant to be a tutorial, just projects with a few hints thrown in.

You are right, why not a series of small projects that help you learn basic Python programming. I will try to come up with some fun projects as time permits, sure others will help too! So keep looking at "Projects for the Beginner".

Ene Uran 638 Posting Virtuoso

One word of advice right away:
"Do not use list as a variable name since list is a function in Python!"

Use listA or something like that:

listA = ['Herring','used','to','be','abundant','in','the','Atlantic','Ocean','then','herring','got','overfished']
# start with an empty list
listB = []
# go through each word in listA
# convert it to lower case
# add it to listB with append()
for word in listA:
    word = word.lower()
    listB.append(word)

print listB

"""
result:
['herring', 'used', 'to', 'be', 'abundant', 'in', 'the', 'atlantic', 'ocean', 'then', 'herring', 'got', 'overfished']
"""

To make listB unique via a set, add this to the above code:

setB = set(listB)
listC = list(setB)
print listC

"""
notice that set() changes the word order to its own efficient hash order
result:
['be', 'used', 'overfished', 'then', 'ocean', 'to', 'atlantic', 'in', 'got', 'the', 'abundant', 'herring']
"""
Ene Uran 638 Posting Virtuoso

Looks a lot more like C or C++ rather than Python!

Ene Uran 638 Posting Virtuoso

If anyone figures out a different way to sort by word length, or form a unique word list, please attach your code to this thread! Would be fun to see your ideas!!!!!

Ene Uran 638 Posting Virtuoso

There are several ways to do this.

First use a for loop, word.lower() and list2.append(word) to create a new list2 from list1 with all lower case words.

Now you can convert list2 to a set with set1 = set(list2) which by design has only unique words. Convert this back to a list with list3 = list(set1). Use print in each case to check your interim results.

You can also construct the for loop so that you only append the lowercase word if its not already in list2. Then you don't need to do the set() stuff.

Vegaseat makes you think, doesn't he?

Ene Uran 638 Posting Virtuoso

Oh, one of Vegaseat's brain teasers. There are several ways to solve this. If you look in the Python reference manual under sort for lists, you find that you can specify your own custom sort method. In this case it would be sorting by length of each word/string in the list. Here is an example:

list1 = ['Herring','used','to','be','abundant','in','the','Atlantic','Ocean','then','herring','got','overfished']
print "Original list1:"
print list1
print
print "Using list1.sort(), which is case sensitive sort:"
list1.sort()
print list1
print 
print "using list1.sort(key=str.lower), makes a case insensitive sort:"
# actually compares everything as all lower case
list1.sort(key=str.lower)
print list1
print
print "Reverse the last list using list1.reverse()"
list1.reverse()
print list1
print
print "Sort list1 by length of word, short to long:"

def bylength(word1, word2):
    """
    write your own compare function:
    returns value > 0 of word1 longer then word2
    returns value = 0 if the same length
    returns value < 0 of word2 longer than word1
    """
    return len(word1) - len(word2)

# change the compare method of sort
list1.sort(cmp=bylength)

print list1

I have added some comments, please study it carefully and experiment with it until you undertand fully.

Ene Uran 638 Posting Virtuoso

Good! The try/except is part of error checking you will tackle next.

What it does in the above code is the following, it tries to load the data file, if there is an error like a missing data file, it does the except part. In the except part you can be more specific about the exact error. Well anyway, have fun learning Python.

Ene Uran 638 Posting Virtuoso

Watch out when you start your program that your basic students dictionary does not override the newly loaded dictionary. Here is your code sample that works:

import pickle

max_points = [25,25,50,25,100]
assignments = ["hw ch 1","hw ch 2","quiz   ","hw ch 3","test"]

try:
    file = open("students.dat", "r")
    students = pickle.load(file)
    file.close()
except:
    students = {"#Max":max_points}
    print "students.dat file not found, starting with", students

def print_menu():
    print "1. Add student"
    print "2. Remove student"
    print "3. Print grades"
    print "4. Record grade"
    print "5. Exit"

def print_all_grades():
    print "\t",
    for i in range(len(assignments)):
        print assignments[i],"\t",
    print
    keys = students.keys()
    keys.sort()
    for x in keys:
        print x,"\t",
        grades = students[x]
        print_grades(grades)
 
def print_grades(grades):
    for i in range(len(grades)):
        print grades[i],"\t\t",
    print
    
print_menu()
menu_choice = 0
while menu_choice != 5:
    print
    menu_choice = input("Menu Choice (1-6): ")
    if menu_choice == 1:
        name = raw_input("Student to add: ")
        students[name] = [0]*len(max_points)
    elif menu_choice == 2:
        name = raw_input("Student to remove: ")
        if students.has_key(name):
            del students[name]
        else:
            print "Student: ",name," not found"
    elif menu_choice == 3:
        print_all_grades()
    elif menu_choice == 4:
        print "Record Grade"
        name = raw_input("Student: ")
        if students.has_key(name):
            grades = students[name]
            print "Type the number of the grade to record"
            print "Type a 0 (zero) to exit"
            for i in range(len(assignments)):
                print i+1," ",assignments[i],"\t",
            print
            print_grades(grades)
            which = 1234
            while which != -1:
                which = input("Change which Grade")
                which = which-1
                if 0 <= which < len(grades):
                    grade = input("Grade: ")
                    grades[which] = grade
                elif which != -1:
                    print "Invalid Grade Number"
        else:
            print …