0

I have windows 8 running on my computer and I think I downloaded python 2 and 3 simultaneously or I think my computer has built in python 2 and I downloaded python 3. And now when I ran my code in IDLE, the code works fine but when I save my program and double click the save file, it will run but it doesn't worked like it used to work in IDLE.

Can someone explain the possible problem I'm currently facing?

I just want my program to run perfectly in both IDLE and when I double click the saved file.

enter image description here

I tried what Anand S. Kumar suggested but I'm not sure I know what I'm doing.

enter image description here

So here is what I inputted in the CMD adminstrator but the output is still the same as the first picture above.

enter image description here

so here is the code

the games module:

# Games
# Demonstrates module creation

class Player(object):
    """ A player for a game. """
    def __init__(self, name, score = 0):
        self.name = name
        self.score = score

    def __str__(self):
        rep = self.name + ":\t" + str(self.score)
        return rep

def ask_yes_no(question):
    """Ask a yes or no question."""
    response = None
    while response not in("y", "n"):
        response = input(question).lower()
    return response

def ask_number(question, low, high):
    """Ask for a number within a range."""
    response = None
    while response not in range(low, high):
        response = int(input(question))
    return response

if __name__ == "__main__":
    print("You ran this module directly (and did not 'import' it).")
    input("\n\nPress the enter key to exit.")

the cards module:

# Cards Module
# Basic classes for a game with playing cards

class Card(object):
    """ A playing card. """
    RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
    SUITS = ["c", "d", "h", "s"]

    def __init__(self, rank, suit, face_up = True):
        self.rank = rank
        self.suit = suit
        self.is_face_up = face_up

    def __str__(self):
        if self.is_face_up:
            rep = self.rank + self.suit
        else:
            rep = "XX"
        return rep

    def flip(self):
        self.is_face_up = not self.is_face_up

class Hand(object):
    """A hand of playing cards."""
    def __init__(self):
        self.cards = []

    def __str__(self):
        if self.cards:
            rep = ""
            for card in self.cards:
                rep += str(card) +  "\t"
        else:
            rep = "<empty>"
        return rep

    def clear(self):
        self.cards = []

    def add(self, card):
        self.cards.append(card)

    def give(self, card, other_hand):
        self.cards.remove(card)
        other_hand.add(card)

class Deck(Hand):
    """ A deck of playing card. """
    def populate(self):
        for suit in Card.SUITS:
            for rank in Card.RANKS:
                self.add(Card(rank, suit))

    def shuffle(self):
        import random
        random.shuffle(self.cards)

    def deal(self, hands, per_hand = 1):
        for rounds in range(per_hand):
            for hand in hands:
                if self.cards:
                    top_card = self.cards[0]
                    self.give(top_card, hand)
                else:
                    print("Can't continue deal. Out of cards!")

if __name__ == "__main__":
    print("This is a module with classes for playing cards.")
    input("\n\nPress the enter key to exit.")

and then the main code:

# Blackjack
# From 1 to 7 players compete against a dealer

# Daghan pakog wa nasabtan ani so balikan pa nako ni!

import cards, games

class BJ_Card(cards.Card):
    """ A Blackjack Card. """
    ACE_VALUE = 1

    @property
    def value(self):
        if self.is_face_up:
            v = BJ_Card.RANKS.index(self.rank) + 1 # unsaon pag kabalo sa self.rank xia.
            if v > 10:
                v = 10
        else:
            v = None
        return v

class BJ_Deck(cards.Deck):
    """ A Blackjack Deck. """
    def populate(self):
        for suit in BJ_Card.SUITS:
            for rank in BJ_Card.RANKS:
                self.cards.append(BJ_Card(rank, suit)) # kay naa may __init__ sa BJ_Card



class BJ_Hand(cards.Hand):
    """ A Blackjack Hand. """
    def __init__(self, name):
        super(BJ_Hand, self).__init__()
        self.name = name

    def __str__(self):
        rep = self.name + ":\t" + super(BJ_Hand, self).__str__()
        if self.total:
            rep += "(" + str(self.total) + ")"
        return rep

    @property
    def total(self):
        # if a card in the hand has value of None, then total is None
        for card in self.cards: 
            if not card.value:
                return None

        # add up card values, treat each ACE as 1
        t= 0
        for card in self.cards:
            t += card.value #-->? tungod sa @ property pwede na xa .value ra
                            #--> Libog  ning diri dapita, unsaon pag kabalo nga self.rank xia


        # determine if hand contains an ACE
        contains_ace = False
        for card in self.cards:
            if card.value == BJ_Card.ACE_VALUE:
                contains_ace = True

        # if hand contains Ace and total is low enough, treat Ace as 11
        if contains_ace and t <= 11:
            # add only 10 since we've already added 1 for the Ace
            t += 10

        return t

    def is_busted(self):
        return self.total > 21

class BJ_Player(BJ_Hand):
    """ A Blackjack Player. """
    def is_hitting(self):
        response = games.ask_yes_no("\n" + self.name + ", do you want a hit? (Y/N): ")
        return response == "y"

    def bust(self):
        print(self.name, "busts.")
        self.lose()

    def lose(self):
        print(self.name, "losses.")

    def win(self):
        print(self.name, "wins.")

    def push(self):
        print(self.name, "pushes.")

class BJ_Dealer(BJ_Hand):
    """ A Blackjack Dealer. """
    def is_hitting(self):
        return self.total < 17

    def bust(self):
        print(self.name, "busts.")

    def flip_first_card(self):
        first_card = self.cards[0]
        first_card.flip()


class BJ_Game(object):
    """ A Blackjack Game. """
    def __init__(self, names):
        self.players = []
        for name in names:
            player = BJ_Player(name)
            self.players.append(player)

        self.dealer = BJ_Dealer("Dealer")

        self.deck = BJ_Deck()
        self.deck.populate()
        self.deck.shuffle()

    @property
    def still_playing(self):
        sp = []
        for player in self.players:
            if not player.is_busted():
                sp.append(player)
        return sp

    def __additional_cards(self, player):
        while not player.is_busted() and player.is_hitting():
            self.deck.deal([player])
            print(player)
            if player.is_busted():
                player.bust()

    def play(self):
        # deal initial 2 cards to everyone
        self.deck.deal(self.players + [self.dealer], per_hand =2)
        self.dealer.flip_first_card()   # hide dealer's first card
        for player in self.players:
            print(player)
        print(self.dealer)

        # deal additional cards to playeres
        for player in self.players:
            self.__additional_cards(player)

        self.dealer.flip_first_card()   # reveal dealer's first

        if not self.still_playing:
            # since all players have busted, just show the dealer's hand
            print(self.dealer)

        else:
            # deal additional cards to dealer
            print(self.dealer)
            self.__additional_cards(self.dealer)

            if self.dealer.is_busted():
                # everyone still playing wins
                for player in self.still_playing:
                    player.win()
            else:
                # compare each player still playing to dealer
                for player in self.still_playing:
                    if player.total > self.dealer.total:
                        player.win()
                    elif player.total < self.dealer.total:
                        player.lose()
                    else:
                        player.push()

    # remove everyone's cards
        for player in self.players: # dapat inside ra xia sa class kay kung dili. self is not defined.
            player.clear()
        self.dealer.clear()

def main():
    print("\t\tWelcome to Blackjack!\n")

    names = []
    number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8)
    for i in range(number):
        name = input("Enter player name: ")
        names.append(name)

    print()

    game = BJ_Game(names)

    again = None
    while again != "n":
        game.play()
        again = games.ask_yes_no("\nDo you want to play again?: ")

main()
input("\n\nPress the enter key to exit.")

Please don't mind the comments if you don't understand. That is my first language by the way.

John Cruz
  • 127
  • 8
  • How did you install python 3 ? – Anand S Kumar Jul 29 '15 at 05:54
  • Why don't you share your code here? – niyasc Jul 29 '15 at 05:56
  • Now your reputation is 10 post the picture :) – The6thSense Jul 29 '15 at 05:57
  • This might be file association. Windows does not read the `#!` line, the shell has to lookup the file extension in the registry. Could be that you have the wrong python associated with `.py`. Several solutions, but first type `python -V` on the command-line, together with `assoc` and `ftype` commands, to see if that is the problem. – cdarke Jul 29 '15 at 06:01
  • Note that Windows does *not* come with any version of Python "built in," and installing 2.x and 3.x side-by-side is generally fine as well. The only issues I can think of with doing so is the possibility of conflicting file associations and having multiple `python.exe`s on `PATH`. (This is part of the reason I never have the install put Python on `PATH` or set up file associations.) – jpmc26 Jul 29 '15 at 06:03
  • 1
    You need to use an [elevated prompt](http://windows.microsoft.com/en-us/windows/command-prompt-faq#1TC=windows-7) to run the commands posted. – Burhan Khalid Jul 29 '15 at 06:26
  • I edited my question above. – John Cruz Jul 29 '15 at 06:44

3 Answers3

1

Most probably, the default program associated with .py files is the Python 2.x's executable . That could be the reason it is not running correctly, when you double-click the python file.

Because when you double click a file (or run it in command prompt without giving an executable ) , windows picks up the default program that is associated with .py files and runs the file using that executable.

In your case, even though you installed Python 3, this may still be pointing to Python 2.

From python installation doc, to change the default executable for Python files , use -

You can also make all .py scripts execute with pythonw.exe, setting this through the usual facilities, for example (might require administrative rights):

  1. Launch a command prompt.

  2. Associate the correct file group with .py scripts:

    assoc .py=Python.File 
    
  3. Redirect all Python files to the new executable:

    ftype Python.File=C:\Path\to\python3.exe "%1" %*
    

Use the above to redirect .py files to Python 3.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • I tried it Sir, and the output is in the edited version of my question, What did I do wrong Sir? I recently installed a new version of python which is Python 3.4 to solve the problem and when installation, I did not choose the default but I change the default installation process and change the path. – John Cruz Jul 29 '15 at 06:26
  • Run command prompt with option `Run as administrator` and then try it. Please note the part in the answer - `(might require administrative rights)` . – Anand S Kumar Jul 29 '15 at 06:28
  • So I followed your answer sir and run the cmd as administrator but the output is still the same – John Cruz Jul 29 '15 at 06:35
  • @JohnCruz are you sure you run the `cmd` with administrator option? Is the user you are using not having those privileges? – Anand S Kumar Jul 29 '15 at 06:36
  • yes I ran it with administrator option, I've edited my question above. Is that correct? – John Cruz Jul 29 '15 at 06:38
  • Yes it is correct, it should be working now. Is it still not working? – Anand S Kumar Jul 29 '15 at 06:39
  • It's still not working, the output is still the same as the first picture on the left above. Sorry for my bad english – John Cruz Jul 29 '15 at 06:41
  • Did you restart the command prompt in which you were trying that? If you did, can you try creating a script with the code as - `import sys; print(sys.version)` . And then double click and run that script, and check the output – Anand S Kumar Jul 29 '15 at 06:48
  • when I double click the file, this will be the output sir. 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] – John Cruz Jul 29 '15 at 06:59
  • @JohnCruz hmm, does this even happen after restart of your computer? – Anand S Kumar Jul 29 '15 at 11:54
  • Thanks for the help sir, I will just start from scratch, I'm just gonna install the python 2.7 and start from there, – John Cruz Jul 31 '15 at 06:48
0

You could try to to change the assosiation to:

python.file="C:\Windows\py.exe" "%L" %*

or set the "C:\Windows" part to where-ever Python3.exe is.

The Python installer (for Python3 at least) seems to specify that the filename should be on the wide-character form; Hence the %L modifier.

BTW. You can use ftype in your cmd-shell too (instead of poking around in Explorer). Untested, so beware:

   ftype python.file=="C:\Windows\py.exe" "%L" %*
G.Vanem
  • 111
  • 1
  • 5
0

I have never tried to run a Python program by double clicking the save file, but I can point you in the direction that tells you how to run a program in the Command Line or Python Shell.

First off, Windows does not come with Python 2 or 3. You can check which version you have by simply going to wherever the Python files were installed. By default, they will be in the C drive. Once you have your enviornment path set up, you can also check which version of Python you have via the Python shell.

Here is where you can find the steps to set up your environment to run Python from the Command Line. This also will help you set up your enviornment. Essentially what you are doing is telling Windows where to find the Python libraries when you type 'python' into the Command Line. Once you have your environment set up, you can run your files in the Command Line or in the Python Shell. Look at Escualo's answer for how to do this.

Community
  • 1
  • 1
Joe
  • 80
  • 7