JoshuaBurleson 23 Posting Whiz

it sounds like you probably haven't learned how to use classes or OOP yet, when you do get there the benefits are that you need less Global variables and you have a reusable class to use for other players or the computer and that using the deck that way makes it easier to recreate the deck after it's expended.

JoshuaBurleson 23 Posting Whiz

there are quicker ways to do it, but I prefer something like what I have below to do it step-by-step:

suit=['c', 'd', 'h', 's']
vals=[1,2,3,4,5,6,7,8,9,10,'J','Q','K','A']
deck=[]
for st in suit:
    for val in vals:
        card=str(val)+str(st)
        deck.append(card)
import random
random.shuffle(deck)
hand=deck[0:2]

Now I believe you said you want a double deck, and while there are several other ways to do this, since you're new I'd suggest doing it step-by-step to get the feel

suit=['c', 'd', 'h', 's']
vals=[1,2,3,4,5,6,7,8,9,10,'J','Q','K','A']
deck1=[]
deck2=[]
deck=[]
for st in suit:
    for val in vals:
        card=str(val)+str(st)
        deck1.append(card)
deck2=deck1[:]#this means make a copy of deck1 as opposed to just pointing at it.
deck1.append(deck2)#    <
deck.append(deck1)#     <not both of these are necessary, one is enough but it makes things clearer for learning to me. 
import random
random.shuffle(deck)
hand=deck[0:2]
deck.pop(0)
deck.pop(1)
random.shuffle(deck)
JoshuaBurleson 23 Posting Whiz

woooee's list of tuples is quite similar to what I went with, another method would be to create a hand class and have a method to check the hand for face cards and add their values to some variable and check that total maybe something like:

class class Hand(object):
    """A black jack hand"""
    def __init__(self, cards, player,hand_val=0):
        self.cards=cards
        self.total_check(cards)
        hand_val=0
        self.player=player
    """Check the value of the hand"""
    def total_check(self, cards):
        self.hand_val=0
        for card in cards:
            if card == 'A':
                card=11
                self.hand_val+=card
            if card=='J' or card=='K' or card=='Q':
                card=10
                self.hand_val+=card
            else:
                self.hand_val+=card
        if self.hand_val>21:
            self.bust()
        else:
            self.hit_or_stay()

    def bust(self):
        print(self.cards,'=',self.hand_val,'\n', self.player,'busted!')
       
    def hit_or_stay(self):
        print('\nCurrent hand:', self.cards,'=',self.hand_val)#remember that self.cards will show the strings A J K Q
        choice=input('Would you like to hit or stay?: ')
        choice=choice.lower()
        if choice=='hit':
            self.hit()
        else:#would not actually be my first choice but I'm trying to make a point
            self.compare()
##main##        
hand=(1,'K')
player='person'
Hand(hand,player)

And in the main part of the program, or another class, depending on your style and needs, assign the hand...blah blah blah.

JoshuaBurleson 23 Posting Whiz

to expand on why I'm confused let me explain my understanding of super()

class Classy(Superclass):
         super(Superclass).__init__(self):
            self.something()

that^ makes sense to me, however when the class it is calling, or if Classy's __init__ had super(Classy).init__(self), just does not make sense to me...

JoshuaBurleson 23 Posting Whiz

Gribouillis is right, using classes and creating instances would dramatically cut down on bugs like whether the variable your calling is within global scope or not as it would eliminate the need for several global variables. Just in case you're very new and not aware, to utilize a global variable within a function you need to declare that it is of global scope prior to utilizing it. i.e.

for n in xrange(N):
    global E
    rho = G(Evolve_rho1(rho))
    m = momentum(Evolve_m1(m))
    E = Energy(Evolve_E1(E))
    v_rho = rho_v(Evolve_rho_v(rho))
    v_m = m_v(Evolve_mv(m))
    v_E = E_v(Evolve_Ev(E))
JoshuaBurleson 23 Posting Whiz

In one of the books I'm using to study Python I keep seeing things like:

class Application(Frame):
           super(Application, self).__init__(master):
           self.grid()
           self.bttn_clicks=0
           self.create_widget"""which is another function in the class"""

Why is the super necessary for the class if the class it's calling is itself?

JoshuaBurleson 23 Posting Whiz

Ohhhh so my issue was that I was trying to call nothingness, I needed to define an instance of the class? i.e. K=Killer()?

JoshuaBurleson 23 Posting Whiz

Okay, here's a MUCH better example of the issue I'm having, working with instances instead of class attributes.

class Person(object):
    def __init__(self, name, health=100):
        self.name=name
        self.health=100
    def hurt(self, amount):
        self.health-=amount
        print(self.health)

class Killer(object):
    def __init__(self):
        import random
        power= random.randint(10, 21)
        self.power=power
        
    def stab(self,Person):
        Person.hurt(self.power)

James=Person('James')
Killer.stab(James)

Killer.stab(James) recieves a TypeError because "stab" takes 2 arguments and only James is given. I thought that the self argument would be ignored...I guess I'm very much missing something important here...Also, I'm just using print to see if it works, I wouldn't normally use it there.

JoshuaBurleson 23 Posting Whiz

okay so a similar issue I'm having related to the matter within a class I have the method

def takeDamage(self):
        self.hp=self
        amount=Enemy.attackpower
        self.hp-=amount
        return self.hp

However when I try to have the Class Enemy send a message 'Starship.takeDamage()' I recieve a TypeError noting that take.Damage takes 1 argument and I am supplying it none, I thought that self was automatically ignored...no? Sorry, I'm still trying to understand OOP

JoshuaBurleson 23 Posting Whiz

Just so you know, I'm also a beginner in python, and programming in general. So I used your assignment to help me with what I'm learning, Classes and methods (non-private for now). I played around a little with the idea of that and here's what I have now.

class Starship(object):
    hp=100
    fuel=100
    ammo=100
    traveled=0
    killed=0

    def __init__(self, name):
        self.name=name
        print('\nAttention Captain of Starship', self.name,'\nit\'s time to make a move!')
    def fireWeapon(self, Enemy):
        try:
            distance=int(input('\nHow far is your target?: '))
            if distance < 10:
                Enemy.hurt(50)
            elif distance > 10 and distance < 51 :
                Enemy.hurt(30)
            elif distance > 50 and distance < 76:
                Enemy.hurt(15)
            else:
                print('Lasers will not do damage at that range')
            Starship.ammo-= 1
            print('\n',Starship.ammo,'percent power left in the lasers')
            print('\nShields at',Starship.hp,'percent captain!')
        except:
            print('Invalid Entry')

    def move(self):
        try:
            lyrs=int(input('How many units would you like to travel, 1-100?: '))
            import random
            obstacle= random.randint(1,101)
            if obstacle != lyrs:
                print('Moved', lyrs,'lightyears')
            else:
                print('There is an enemy in your way!')
                Decisions.__init__()
                
            Starship.fuel-= lyrs//10
            Starship.traveled += lyrs
            return Starship.traveled, Starship.fuel
        except:
           print('\n Invalid Selection')


class Enemy(object):
    enemyhp=100
    damage1=0

    def __init__(self):
        print('I am the enemy!')
        
    def lifeCheck():
        if Enemy.enemyhp< 1:
            print('\n\nEnemy annihalated!!!\n')
            Starship.killed += 1
        else:
            print('\nEnemy shields at', Enemy.enemyhp, 'percent captain!\n')
            print('\nThe enemy is firing back!')
            import random
            chance=random.randint(1,3)
            if chance==1:
                print('\n That was close but the enemy missed!')
            else:
                import random
                attackdamage=random.randint(1,51)
                Starship.hp-=attackdamage
                print('Shit! They got us captain!')
        return Enemy.enemyhp, Starship.killed


    def hurt(damage):
        Enemy.damage1 += damage
        Enemy.enemyhp=Enemy.enemyhp-Enemy.damage1
        Enemy.lifeCheck()

    def location():
        import random
        location=random.randint(1,101)

class Decisions(object):
    def __init__(self):
        choice=input('\nenter your decisions\n1. Attack\n2. Flee\nChoice: …
TrustyTony commented: Only little bit to go: http://en.wikipedia.org/wiki/Star_Trek_%28text_game%29 +13
JoshuaBurleson 23 Posting Whiz

in case you aren't familiar with -= it is the equivalent of saying var = var - int

JoshuaBurleson 23 Posting Whiz

as this is your first post I should remind you it's polite, but not required to reply with your solution or any further questions. To hit "mark thread solved" for people with similar problems in the future. And, no one minds up voting if you find it appropriate, happy coding!

JoshuaBurleson 23 Posting Whiz

and have you tried something like:

def moveForward(fuel):
    path = input("How many feet would you like to move FOREward?")
    obstacle = input("How many feet away is your nearest obstacle?")

    if path - obstacle == path:
        print "You have moved forward",path,"feet."
        fuel-= path
        print('You have', fuel,'units of fuel left')
        return fuel

for each section or possibility?

JoshuaBurleson 23 Posting Whiz

well first of all what is going wrong when you try to run it?

JoshuaBurleson 23 Posting Whiz

I'm not so great at explaining all the nuts and bolts of classes, and probably have some bad habits, but I've fixed your code so that it at least works:

class OffSwitch:
    def __init__(self):
        self.keycheck='off'

    def turnOff(self, key):
	print key, 'hi'
        if key==self.keycheck:
            SystemExit
        else:
            print('will continue')


switchword=str(raw_input('Enter a word: ') )

foo=OffSwitch()
foo.turnOff(switchword)

First, I changed your class declaration to class Offswitch: instead of Offswitch(object). I don't know why you need to put the object there, maybe there's a good reason, but it's not necessary.

Second, I changed your switchword call so that it knew to make your input a string. Again, your syntax may be fine, but this is how I do it.

Lastly, and importantly, the code works when you initialize the class before calling its methods. I made a class instance by using:

foo=OffSwitch()

Now, the variable foo, is the instance of your class. Basically, foo is a variable just waiting around for you to run the class methods. I'm no expert, but I think you always need to first instatiate a class like this before you run its methods. To run methods, the syntax is:

foo.turnOff(switchword)

Thank you. I'm using Python3 so the raw_input wouldn't work but that's fine. The big part for me was the foo variable, can anybody confirm for sure that you must instantiate before running methods for me? I just want to be sure for future reference. Again, thank you Shoemoodoshaloo!

JoshuaBurleson 23 Posting Whiz

I'm trying to understand utilizing classes and their methods. I made a simple program to exit or print 'Will continue' given a word. however I keep getting a TypeError for self and through reading my books and searching online I'm still not quite sure why. the code is:

class OffSwitch(object):
    def __init__(self):
        self.keycheck='off'

    def turnOff(self,key):
        if key==self.keycheck:
            SystemExit
        else:
            print('will continue')


switchword=input('Enter a word: ')

OffSwitch.turnOff(switchword)

and getting the error

Traceback (most recent call last):
  File "E:/classpractice", line 14, in <module>
    OffSwitch.turnOff(switchword)
TypeError: turnOff() takes exactly 2 arguments (1 given)
JoshuaBurleson 23 Posting Whiz

is it possible to use the Fkeys, i.e. F1, F2,...F12, as input in any way?

JoshuaBurleson 23 Posting Whiz

figured it out. thanks.

JoshuaBurleson 23 Posting Whiz

Why a text file? If you simply want to preserve information from session to session, there are three ways

  1. What you suggested: Write the data to a text file
  2. Pickle , Python's object serializer module (actually: Use cPickle)
  3. Use a database

I recommend you use pickle. However if you choose to move ahead with option 1, note the "%r" formatting directive for example:

s = {'one':'uno', 2:'dos', 'cat': 'gato'}
print ("%r"%s)

You can then use the eval builtin function to recover the data. Beware of quote issues.

thank you, what does that look like in code? and where does it save the data? I'm reading over this doc, but it's not really giving me the applied knowledge I need to understand how to utilize it.

JoshuaBurleson 23 Posting Whiz

So I've finally fixed up the functionality of an address book I've been writing (not on to utilizing a GUI yet of course though.)However to save or reclaim the data from the last use of the address book I, obviously, need to write and reclaim it from a .txt file, I understand how to write and read, however I'm not sure how to write so when it is read I can make it back into a dictionary. Any ideas? here's how I'm writing so far.

for line in AB.keys():
    line=line+'\n '
    print(line,file=f)
for line in AB.values():
    for string in line:
        print(string+'\n',file=f)
f.close
JoshuaBurleson 23 Posting Whiz

@Enilicho;the method name was made by google, it's google's python class. And lol I just noticed that I said str for 'x', a bit redundant, I've never programmed with any other language before but pytony seems to think I do types too much which makes me look like a java coder. Were you able to append to result because it wasn't the list the loop was about?

JoshuaBurleson 23 Posting Whiz

so I recently wrote a function that sorted using the last value in a tuple. Obviously this couldn't be done simply say sorted(tuples, key=tuples[-1]) because that is not a "legal" call. However I did run across, while trying to figure out how to make things like this work, the utilization of lambda so the code became.

def sort_last(tuples):
    x=sorted(tuples, key=lambda tuples: tuples[-1])
    return(x)

The code runs correctly and, that's all well and good, but I don't understand why lambda tuples"or any given var for that matter":. makes this possible. Can someone explain this to me in a way I'll understand so that I can utilize the principle to its maximum potential?
p.s. I have essentially no calculus experience.

JoshuaBurleson 23 Posting Whiz

The common idiom is

thelist[:] = (x for x in thelist if not criteria(x))

# for example

thelist[:] = (x for x in thelist if not 'a' in x)

Python has some extraordinarily intuitive features I'm noticing, it's almost...English.

JoshuaBurleson 23 Posting Whiz

and more specifically, I was working on if it wasn't the first character, but I think I'll add that idiom to my personal notes. Thank you!

JoshuaBurleson 23 Posting Whiz

The common idiom is

thelist[:] = (x for x in thelist if not criteria(x))

# for example

thelist[:] = (x for x in thelist if not 'a' in x)

so it would be that simple to exclude those from the list?

JoshuaBurleson 23 Posting Whiz

never mind, I figured it out. Here's the function I was working on, suggestions on simplification?

def front_x(words):
    copy=words[:]
    for i in copy:
        if i[0]!= str('x'):
            copy.remove(i)
            copy=sorted(copy, reverse=True)
    for i in words:
        if i[0]==str('x'):
            words.remove(i)
            words=sorted(words)
    print(copy+words)
JoshuaBurleson 23 Posting Whiz

if I wanted to remove all of the strings within a given list that met a certain criteria, such as having the str'a' in them, how would I go about doing that? the only way that's intuitive to me a for/in loop, but that can't be done. any ideas? Using Python3.2

JoshuaBurleson 23 Posting Whiz

pytony, thank you. I tried your code and it didn't work for some reason, but nonetheless it was above my paygrade, but it did give me an idea and got me out of the rut I was stuck in. You're brilliant! here's the updated code and it works.

def match_ends(words):
    count=0
    words=sorted(words, key=len)
    for i in words:
        if len(i)<2:
            words=words[1:]
            for i in words[:]:
                if i[0:2]==i[-2:]:
                    count=count+1
    print(count)

I was way over complicating it by trying to put the strings that met the conditions in a new string,which I then intended to count. It's probably still over complicated, but I hope I get better over time, you've been a great help so far. I'm so glad I found this place.

JoshuaBurleson 23 Posting Whiz

in line ten is using the comparison == equivalent to saying 'only if'?

JoshuaBurleson 23 Posting Whiz

I'm doing the google code U python class and came across a problem trying the following problem, which is the commented out region, the solution needs to be a function. I'm on the second part and trying to find a way to count the values which meet the requirement,i[0:2]==i[-2:]. I running Python 3.2

# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
    words=sorted(words, key=len)
    for i in words:
        if len(i)<2:
            print(i)
            words=words[1:]
            print(words)
            for i in words:
                if i[0:2]==i[-2:]:
                    x=[]
                    x.append[i]#which I know will not work
JoshuaBurleson 23 Posting Whiz

just trying to be thorough, but if it doesn't need to be done then thank you for correcting me. I'm trying to send the result of the equation to twitter, however I'm having tons of issues with it. I tried 2to3 now, and also just running the send_to_twitter function in python 2, it's not working either way.

JoshuaBurleson 23 Posting Whiz

should it look like

import sys
from lib2to3.main import main
type_fix
sys.exit(main("lib2to3.fixes"))

?

JoshuaBurleson 23 Posting Whiz

okay, I ran your code and tweaked it a little bit, I'm not going to give you the answer, but here's a very strong hint.

import math
flip = 0
print("Lets flip a coin 100 times and count how many heads and tails we get")
while flip<=float(99):
    import random
    coin= random.randint(1, 2)
    head= 0
    tail= 0
    if coin ==+1:
        head=head+1
        print('heads')
    else:
        tail=tail+1
        print('tails')
    flip= flip+1
print("Heads", head)
print("Tails", tail)
#why do you think outside of the loop it isn't reflecting?
JoshuaBurleson 23 Posting Whiz

ignore the urllib.request, that's for later in the code.

JoshuaBurleson 23 Posting Whiz

here's a program I wrote for an equation using the same loop method a few weeks ago

import urllib.request
import math
whips=int(0)
rate=float(4)
while rate <= float(20):
    improve= rate*float(.15)+rate
    rate= improve
    whips=whips+1
print(whips)
JoshuaBurleson 23 Posting Whiz

try

flip=flip+1

and remember to hit the code button before you insert your code, it's terrible to read.

JoshuaBurleson 23 Posting Whiz
import random
print("Want to know your future?")

fortune = random.randint(1, 5)
if fortune == 1:
   print("You are gonna die today")
elif fortune == 2:
   print("You will find love")
elif fortune == 3:
   print("You will make it big today!")
elif fortune == 4:
   print("You friends will betray you!")
elif fortune == 5:
   print("They are comming to find you..")
else:
   print("**** the future...")

idk if it was just your indenting or if you have another issue, you're not really giving us anything to help you with. And why did you post it 4 times?

JoshuaBurleson 23 Posting Whiz

wrap in

JoshuaBurleson 23 Posting Whiz

sorry Tony, I'm feeling like an idiot, no matter how I try to run that in IDLE it's giving me Invalid Syntax

JoshuaBurleson 23 Posting Whiz

I'm not seeing 2to3.py and I'm not sure how to convert strings to bytes

okay sorry Pytony, I figured out the str to bytes thing, and now I'm getting bytes has no attribute data

JoshuaBurleson 23 Posting Whiz

Sounds like trying run Python2 code in Python3, did you try to run 2to3.py script for the code? Try changing strings to bytes: b''

I'm not seeing 2to3.py and I'm not sure how to convert strings to bytes

JoshuaBurleson 23 Posting Whiz

I got this snippet out of my text book but it's giving me a type error, I'll just give you the whole code, tell me if you get it too, if you would.

import urllib.request
import math
whips=int(0)
rate=float(4)
while rate <= float(20):
    improve= rate*float(.15)+rate
    rate= improve
    whips=whips+1
print(whips)
def send_to_twitter():
    msg = whips
    password_manager = urllib.request.HTTPPasswordMgr()
    password_manager.add_password("Twitter API","http://twitter.com/statuses", "jcbamm26", "~~~~~~~")
    http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
    page_opener = urllib.request.build_opener(http_handler)
    urllib.request.install_opener(page_opener)
    params = urllib.parse.urlencode( {'status': msg} )
    resp = urllib.request.urlopen('http://twitter.com/statuses/update.json', params)
    resp.read()
send_to_twitter()

the error return is

Traceback (most recent call last):
  File "C:\Python32\AB3.py", line 21, in <module>
    send_to_twitter()
  File "C:\Python32\AB3.py", line 19, in send_to_twitter
    resp = urllib.request.urlopen('http://twitter.com/statuses/update.json', params)
  File "C:\Python32\lib\urllib\request.py", line 138, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python32\lib\urllib\request.py", line 367, in open
    req = meth(req)
  File "C:\Python32\lib\urllib\request.py", line 1066, in do_request_
    raise TypeError("POST data should be bytes"
TypeError: POST data should be bytes or an iterable of bytes. It cannot be str.
JoshuaBurleson 23 Posting Whiz
#Address Book#
#Remember brackets call object from library []#
#only add dicts to dicts; add via dictname.update(var)
AB={'Joshua' : ['Email: sho0uk0m0o@gmail.com Phone: (802) 3-5-2206'],
    'Ashley' : ['Ashley: ''Email: a000@gmail.com Phone: (802) 820-0000'],}
print('Address Book: Enter x into query to exit')
print('to add a contact enter "add" in query')
query = input('Enter Search Query: ')
while query!=('x'):
    try:
        print(AB[query])
        query=input('Enter another search query or x to exit: ')
    except KeyError:
        if ('add')in query:
            new={input('Enter name: '): [input('Enter contact information: ')]}
            AB.update(new)
            query=input('Enter Search Query: ')
        else:
            print('Name not in Address Book, remember contacts are case sensitive. Please try again.')
            query=input('Enter Search Query: ')
if ('x') in query or query==('x'):
    print('Application Terminated')

So I've updated based on everybody's suggestions and here is the product so far, it's doing exactly what I wanted. Next I'm going to figure out a way to utilize Woooee's first format into it. Gribouillis, I really appreciate the help, I'm just not sure how to utilize that to its best potential right now, too busy being a noob, sorry.

JoshuaBurleson 23 Posting Whiz

Notice that I changed your input() method to raw_input(). raw_input will convert the input to a string, since that is what the user will be using as input.

Thank you, that's extremely helpful as well. However, raw_input() has been giving me syntax errors for some reason. I don't know if it's because of the OS on this computer or if it's something new in 3.x. Any ideas?

JoshuaBurleson 23 Posting Whiz

For storing a few values, like phone number and e-mail address, you can use a list which is easier to understand and use.

AB={'Joshua' : ['sho0uk0m0o@gmail.com',  '(802) 3-5-2206'],
    'Ashley':  ['a000@gmail.com', '(802) 820-0000']}
print "%s,  e-mail=%s,  phone=%s" % ("Joshua", AB["Joshua"][0], AB["Joshua"][1])

new_name = "Bill"
new_email= "bill@domain.com"
new_phone= "(802) 123-4567"

AB[new_name] = [new_phone, new_email]
print AB

thank you! that was extremely useful advice. Now, if I wanted the user of the program to be able to search for a contact they created, via entering the key as the query, how would I do that and return the value?

JoshuaBurleson 23 Posting Whiz

Sorry, I'm new to this, the address book has the names twice because the looked better when printed out to me. The later coding with if(as) in query was just me learning how to utilize the in function. But now I want to search with any given parameters from the user and print the corresponding contact (value or key:value pair)

JoshuaBurleson 23 Posting Whiz

I am having issues finding a way to have the below program search for any given string of "query" in the keys of the dictionary AB and return the value, or the key and value. Thus far I just done what I have preset in the dictionary; Ashley and Joshua, and they are retrievable via a very simple code, that is unrealistic if I wanted users to be able to create and search from their own Address Book dictionary.

#Address Book#
#Remember brackets call object from library []#
#only add dicts to dicts; add via dictname.update(var)
AB={'Joshua' : 'Joshua: ''Email: sho0uk0m0o@gmail.com Phone: (802) 3-5-2206',
    'Ashley' : 'Ashley: ''Email: a000@gmail.com Phone: (802) 820-0000',}
print('Address Book: Enter x into query to exit')
print('to add a contact enter "add" in query')
query = input('Enter Search Query: ')
##abkeys=AB.keys()
##abvals=AB.values()
while query!=('x'):
    if ('add')in query:
        new={input('Enter name: '): input('utilize the following format: Name______,:, Email,:,______, Phone,:,______ Enter contact information: ')}
        AB.update(new)
        print(AB)
        query=input('Enter Search Query: ')
##        if query in AB:
##            print(AB.keys(),AB.values())
    elif ('as') in query or ('As') in query:
        print(AB['Ashley'])
        query= input('Enter Search Query:' )
    elif ('jo') in query or ('Jo') in query:
        print(AB['Joshua'])
        query=input('Enter Search Query:' )
    elif query==('0'):
        print(AB['Joshua'])
        print(AB['Ashley'])
        query=('x')
    else:
        print('Query not found please retype your query or type "help" for more information')
        query = input('Enter Search Query: ')
if ('x') in query or query==('x'):
    print('Application Terminated')           
#Next, find a way to search based on any given input == str in key from AB and print key,value