Python full stack learning--Day30 (card game, exceptions and errors, exception handling)

1. Assignment Game

Let's review what happened yesterday

1. importing a module is equivalent to executing the py file

2. Modules will not be imported repeatedly

3. The imported modules are stored in sysmodules

4. What happens after importing the module:

  First see if the module is in sys.modules, if not:

  Generate a namespace that belongs to the module

  execute py file

  Create a variable with the same name as the py file to reference the name in this space

  Put the imported module in sys.modules

5.from ...import....

6. Absolute and relative imports

7. Software Development Specifications

 

draw

from collections import namedtuple

Card = namedtuple('Card', ['rand', 'suit']) # Define 2 attributes, card face and suit

class FranchDeck:
    ranks = [str(n) for n in range(2, 11)] + list('JQKA') # list comprehension + list, combined into 13 cards
    suits = ['heart', 'square board', 'club', 'spade'] # 4 suits

    def __init__(self):
        self._cards = [Card(rank, suit) for rank in FranchDeck.ranks
                       for suit in FranchDeck.suits] # ​​Take out 52 cards and return a list.
        # [Card(rand='2', suit='red heart'), Card(rand='2', suit='square board')...]

    def __len__(self):
        return len(self._cards) # Get the length of the list

    def __getitem__(self, item):
        return self._cards[item] # Take a card


deck = FranchDeck()
print(deck[0]) # take the first card
from random import choice

print(choice(deck)) # randomly choose a card
print(choice(deck))

  

The above code relies on __len__ and __getitem__ to draw cards, and the cards you get are different each time.

 

describe a card

from collections import namedtuple
Card = namedtuple('Card',['rand','suit']) #Define 2 attributes, card face and suit
print(Card('2','Red Heart'))

  

from collections import namedtuple

Card = namedtuple('Card', ['rand', 'suit']) # Define 2 attributes, card face and suit


class FranchDeck:
    ranks = [str(n) for n in range(2, 11)] + list('JQKA')
    suits = ['Hearts', 'Square', 'Clubs', 'Spades']

    def __init__(self):
        self._cards = [Card(rank, suit) for rank in FranchDeck.ranks
                       for suit in FranchDeck.suits]

    def __len__(self):
        return len(self._cards)

    def __getitem__(self, item):
        return self._cards[item]

    def __setitem__(self, key, value):
        self._cards[key] = value


deck = FranchDeck()
# print(deck[0]) #Draw the first card
from random import choice
# print(choice(deck))
# print(choice(deck))

from random import shuffle

shuffle(deck) # shuffle the order, shuffle
# print(deck[:5]) # Draw 5 cards
print(deck[:]) # , 52 cards are different each time.

 

 

 Second, exceptions and errors

Errors are inevitable in the program, and errors are divided into two minutes

 1. Syntax error (this kind of error cannot pass the syntax detection of the python interpreter and must be corrected before the program is executed)

if name = 10

#2. Logic Error

num = 0
100/num

  

This blue link information is made by Pycharm, it can jump to the specified code location

ZeroDivisionError is reported by the python interpreter

 

what is an exception

An exception is a signal that an error occurs when the program is running. In python, the wrong exception is as follows

An exception is a signal that an error occurs when the program is running. In python, the exception triggered by the error is as follows

Types of exceptions in python                                                                                                      

Different exceptions in python can be identified by different types (classes and types are unified in python, and types are classes), different class objects identify different exceptions, and an exception identifies an error

 trigger IndexError

1
2
l = [ 'egon' , 'aa' ]
l[ 3 ]

trigger KeyError

1
2
dic = { 'name' : 'egon' }
dic[ 'age' ]

trigger ValueError

1
2
s = 'hello'
int (s)

Common exception

copy code
AttributeError attempting to access a tree that an object does not have, such as foo.x, but foo has no attribute x
IOError input/output exception; basically the file cannot be opened
ImportError cannot import module or package; basically path problem or wrong name
IndentationError syntax error (subclass of); code is not properly aligned
IndexError The subscript index exceeds the sequence boundary, such as trying to access x[5] when x has only three elements
KeyError attempting to access a key that does not exist in the dictionary
KeyboardInterrupt Ctrl+C is pressed
NameError using a variable that has not been assigned to an object
SyntaxError Python code is illegal, the code cannot be compiled (personally think this is a syntax error, written wrong)
TypeError The incoming object type does not meet the requirements
UnboundLocalError attempts to access a local variable that has not been set, basically because there is another global variable with the same name,
cause you to think you are accessing it
ValueError passes in a value not expected by the caller, even if the value is of the correct type
copy code

more exceptions

copy code
ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError
copy code
 
 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325128312&siteId=291194637