简体   繁体   English

我认为我的计算机已内置python 2,并且安装了python 3

[英]I think my computer has built in python 2 and I installed python 3

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. 我的计算机上运行的是Windows 8,我想我同时下载了python 2和3,或者我认为我的计算机已内置python 2,并且下载了python3。现在当我在IDLE中运行代码时,代码可以正常工作,但是当我保存了程序,然后双击保存文件,该文件将运行,但无法像以前在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. 我只希望我的程序在IDLE和双击保存的文件中都能完美运行。

在此处输入图片说明

I tried what Anand S. Kumar suggested but I'm not sure I know what I'm doing. 我尝试了Anand S. Kumar的建议,但不确定我知道我在做什么。

在此处输入图片说明

So here is what I inputted in the CMD adminstrator but the output is still the same as the first picture above. 所以这是我在CMD管理员中输入的内容,但输出仍然与上面的第一张图片相同。

在此处输入图片说明

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. 顺便说一句,这是我的第一语言。

Most probably, the default program associated with .py files is the Python 2.x's executable . .py文件关联的默认程序很可能是Python 2.x的可执行文件。 That could be the reason it is not running correctly, when you double-click the python file. 双击python文件时,这可能是它无法正常运行的原因。

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. 因为双击文件(或在命令提示符下运行文件而不提供可执行文件)时,Windows会选择与.py文件关联的默认程序,并使用该可执行文件运行文件。

In your case, even though you installed Python 3, this may still be pointing to Python 2. 就您而言,即使您安装了Python 3,它仍可能指向Python 2。

From python installation doc , to change the default executable for Python files , use - 在python 安装文档中 ,要更改Python文件的默认可执行文件,请使用-

You can also make all .py scripts execute with pythonw.exe, setting this through the usual facilities, for example (might require administrative rights): 您还可以使用pythonw.exe使所有.py脚本执行,例如通过常规功能进行设置(可能需要管理权限):

  1. Launch a command prompt. 启动命令提示符。

  2. Associate the correct file group with .py scripts: 将正确的文件组与.py脚本相关联:

     assoc .py=Python.File 
  3. Redirect all Python files to the new executable: 将所有Python文件重定向到新的可执行文件:

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

Use the above to redirect .py files to Python 3. 使用上面的命令将.py文件重定向到Python 3。

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. 或将“ C:\\ Windows ”部分设置为Python3.exe所在的位置。

The Python installer (for Python3 at least) seems to specify that the filename should be on the wide-character form; Python安装程序(至少适用于Python3)似乎指定文件名应使用宽字符格式; Hence the %L modifier. 因此, %L修饰符。

BTW. 顺便说一句。 You can use ftype in your cmd-shell too (instead of poking around in Explorer ). 您也可以在cmd-shell中使用ftype (而不是在Explorer中戳戳)。 Untested, so beware: 未经测试,请当心:

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

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. 我从未尝试过通过双击保存文件来运行Python程序,但是我可以为您指明如何在命令行或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. 首先,Windows不附带Python 2或3。您可以通过简单地转到Python文件的安装位置来检查所使用的版本。 By default, they will be in the C drive. 默认情况下,它们将位于C驱动器中。 Once you have your enviornment path set up, you can also check which version of Python you have via the Python shell. 设置好环境路径后,您还可以通过Python shell检查所使用的Python版本。

Here is where you can find the steps to set up your environment to run Python from the Command Line. 在这里 ,您可以找到设置环境以从命令行运行Python的步骤。 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. 本质上,您正在做的就是告诉Windows在命令行中键入“ python”时在哪里可以找到Python库。 Once you have your environment set up, you can run your files in the Command Line or in the Python Shell. 设置好环境后,您可以在命令行或Python Shell中运行文件。 Look at Escualo's answer for how to do this. 查看Escualo的答案,了解如何执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的计算机上安装了两个版本的python,但一个没有响应 - I have two version of python installed on my computer but one is not responding 我认为 Python 查询 - Python inquiry I think 如何从 VS Code 的 Python Extension 切换到我电脑上安装的 Python? - How do I switch from VS Code's Python Extention to the Python installed on my computer? 如何告诉我的 Mac 使用安装在我的计算机上的最新版本的 Python? - How do I tell my Mac to use the latest version of Python installed on my computer? 新手,但是我在Mac上安装了python 2.7.5,如何“定位”该目标而不是内置2.7.2? - noob, but I installed python 2.7.5 on my mac, how to I “target” that one rather than the built in 2.7.2? (python GUI)我认为这是一个有效的代码,但是存在语法错误 - (python GUI)I think This is an efficient code, but there has a grammatical error 我想我的python脚本中有内存泄漏 - I think I have a memory leak in my python script 我认为已经有论点的sa书。 Python /终端 - Osascript requiring argument I think it already has. Python/Terminal 我想我在使用python中的statsmodel包构建的回归模型中获得了不同的AIC和BIC值 - I think I am getting different AIC & BIC values in a regression model built using statsmodel package in Python Python-变量未定义,但我认为是 - Python - variable not defined but I think it is
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM