Article From:https://www.cnblogs.com/q735613050/p/9215050.html

Learning resources: a stupid method to learn python3

Contents

input() The script run process requires input parameters

from sys import argv

script, user_name = argv  # Unpack
prompt = '> '    # Prompt

print(f"Hi {user_name}, I'm the {script} script.")
print("I'd like to ask you a few question.")
print(f"Do you like me {user_name}?")
likes = input(prompt)

print(f"Where do you live {user_name}?")
lives = input(prompt)

print("What kind of computer do you have?")
computer = input(prompt)

print(f'''
Alright, so you said {likes} about liking me.
You live in {lives}. Not sure where that is.
And you have a {computer} computer. Nice.
''')
x = input('sd ffg')
sd ffgdf
type(x)
str
x
'df'
echo 'This is a text file.' > a.txt   # create a file
cat a.txt    # see file
man cat   # Look at the help document of cat

function” in the function*args

Tell Python to receive all the parameters of the function and put it in the name.args Go in the list.

def print_two(*args):
    arg1, arg2 = args
    print(f'arg1: {arg1}, arg2: {arg2}')
print_two('Zed', 'Shaw')
arg1: Zed, arg2: Shaw

import sys

script, encoding, error = sys.argv

def main(language_file, encoding, errors):
    line = language_file.readline()
    if line:
        print_line(line, encoding, errors)
        return main(language_file, encoding, errors)

def print_line(line, encoding, errors):
    next_lang = line.strip()
    raw_bytes = next_lang.encode(encoding, errors = errors)
    cooked_string = raw_bytes.decode(encoding, errors = errors)
    
    print(raw_bytes, "<===>", cooked_string)

languages = open('E:/Data/languages.txt', encoding = 'utf-8')

main(languages, encoding, error)

PowerShell:

python .\str_bytes_test.py utf-8 strict
def main(language_file, encoding, errors):
    line = language_file.readline()
    if line:
        print_line(line, encoding, errors)
        return main(language_file, encoding, errors)

def print_line(line, encoding, errors):
    next_lang = line.strip()     # Delete "\n" at the end of each line
    raw_bytes = next_lang.encode(encoding, errors = errors)
    cooked_string = raw_bytes.decode(encoding, errors = errors)

    print(raw_bytes, "<===>", cooked_string)
with open('E:/Data/languages.txt', encoding = 'utf-8') as fp:
    main(fp, 'utf-8', 'strict')
b'Afrikaans' <===> Afrikaans
b'\xe1\x8a\xa0\xe1\x88\x9b\xe1\x88\xad\xe1\x8a\x9b' <===> አማርኛ
b'\xd0\x90\xd2\xa7\xd1\x81\xd1\x88\xd3\x99\xd0\xb0' <===> Аҧсшәа
b'\xd8\xa7\xd9\x84\xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a\xd8\xa9' <===> العربية
b'Aragon\xc3\xa9s' <===> Aragonés
b'Arpetan' <===> Arpetan
b'Az\xc9\x99rbaycanca' <===> Azərbaycanca
b'Bamanankan' <===> Bamanankan
b'\xe0\xa6\xac\xe0\xa6\xbe\xe0\xa6\x82\xe0\xa6\xb2\xe0\xa6\xbe' <===> বাংলা
b'B\xc3\xa2n-l\xc3\xa2m-g\xc3\xba' <===> Bân-lâm-gú
b'\xd0\x91\xd0\xb5\xd0\xbb\xd0\xb0\xd1\x80\xd1\x83\xd1\x81\xd0\xba\xd0\xb0\xd1\x8f' <===> Беларуская
b'\xd0\x91\xd1\x8a\xd0\xbb\xd0\xb3\xd0\xb0\xd1\x80\xd1\x81\xd0\xba\xd0\xb8' <===> Български
b'Boarisch' <===> Boarisch
b'Bosanski' <===> Bosanski
b'\xd0\x91\xd1\x83\xd1\x80\xd1\x8f\xd0\xb0\xd0\xb4' <===> Буряад
b'Catal\xc3\xa0' <===> Català
b'\xd0\xa7\xd3\x91\xd0\xb2\xd0\xb0\xd1\x88\xd0\xbb\xd0\xb0' <===> Чӑвашла
b'\xc4\x8ce\xc5\xa1tina' <===> Čeština
b'Cymraeg' <===> Cymraeg
b'Dansk' <===> Dansk
b'Deutsch' <===> Deutsch
b'Eesti' <===> Eesti
b'\xce\x95\xce\xbb\xce\xbb\xce\xb7\xce\xbd\xce\xb9\xce\xba\xce\xac' <===> Ελληνικά
b'Espa\xc3\xb1ol' <===> Español
b'Esperanto' <===> Esperanto
b'\xd9\x81\xd8\xa7\xd8\xb1\xd8\xb3\xdb\x8c' <===> فارسی
b'Fran\xc3\xa7ais' <===> Français
b'Frysk' <===> Frysk
b'Gaelg' <===> Gaelg
b'G\xc3\xa0idhlig' <===> Gàidhlig
b'Galego' <===> Galego
b'\xed\x95\x9c\xea\xb5\xad\xec\x96\xb4' <===> 한국어
b'\xd5\x80\xd5\xa1\xd5\xb5\xd5\xa5\xd6\x80\xd5\xa5\xd5\xb6' <===> Հայերեն
b'\xe0\xa4\xb9\xe0\xa4\xbf\xe0\xa4\xa8\xe0\xa5\x8d\xe0\xa4\xa6\xe0\xa5\x80' <===> हिन्दी
b'Hrvatski' <===> Hrvatski
b'Ido' <===> Ido
b'Interlingua' <===> Interlingua
b'Italiano' <===> Italiano
b'\xd7\xa2\xd7\x91\xd7\xa8\xd7\x99\xd7\xaa' <===> עברית
b'\xe0\xb2\x95\xe0\xb2\xa8\xe0\xb3\x8d\xe0\xb2\xa8\xe0\xb2\xa1' <===> ಕನ್ನಡ
b'Kapampangan' <===> Kapampangan
b'\xe1\x83\xa5\xe1\x83\x90\xe1\x83\xa0\xe1\x83\x97\xe1\x83\xa3\xe1\x83\x9a\xe1\x83\x98' <===> ქართული
b'\xd2\x9a\xd0\xb0\xd0\xb7\xd0\xb0\xd2\x9b\xd1\x88\xd0\xb0' <===> Қазақша
b'Krey\xc3\xb2l ayisyen' <===> Kreyòl ayisyen
b'Latga\xc4\xbcu' <===> Latgaļu
b'Latina' <===> Latina
b'Latvie\xc5\xa1u' <===> Latviešu
b'L\xc3\xabtzebuergesch' <===> Lëtzebuergesch
b'Lietuvi\xc5\xb3' <===> Lietuvių
b'Magyar' <===> Magyar
b'\xd0\x9c\xd0\xb0\xd0\xba\xd0\xb5\xd0\xb4\xd0\xbe\xd0\xbd\xd1\x81\xd0\xba\xd0\xb8' <===> Македонски
b'Malti' <===> Malti
b'\xe0\xa4\xae\xe0\xa4\xb0\xe0\xa4\xbe\xe0\xa4\xa0\xe0\xa5\x80' <===> मराठी
b'\xe1\x83\x9b\xe1\x83\x90\xe1\x83\xa0\xe1\x83\x92\xe1\x83\x90\xe1\x83\x9a\xe1\x83\xa3\xe1\x83\xa0\xe1\x83\x98' <===> მარგალური
b'\xd9\x85\xd8\xa7\xd8\xb2\xd9\x90\xd8\xb1\xd9\x88\xd9\x86\xdb\x8c' <===> مازِرونی
b'Bahasa Melayu' <===> Bahasa Melayu
b'\xd0\x9c\xd0\xbe\xd0\xbd\xd0\xb3\xd0\xbe\xd0\xbb' <===> Монгол
b'Nederlands' <===> Nederlands
b'\xe0\xa4\xa8\xe0\xa5\x87\xe0\xa4\xaa\xe0\xa4\xbe\xe0\xa4\xb2 \xe0\xa4\xad\xe0\xa4\xbe\xe0\xa4\xb7\xe0\xa4\xbe' <===> नेपाल भाषा
b'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e' <===> Japanese languageB'Norsk bokm\xc3\xa5l'< ===> Norsk bokm LB'Nouormand'< ===> NouormandB'Occitan'&lT; ===> OccitanB'O\xca\xbbzbekcha/\xd1\x9e\xd0\xb7\xd0\xb1\xd0\xb5\xd0\xba\xd1\x87\xd0\xb0'< ===> O zbekcha/B'\xe0\xa8\xaa\xe0\xa9\xb0\xe0\xa8\x9c\xe0\xa8\xbe\xe0\xa8\xac\xe0\xa9\x80'< ===>B'\xd9\xbe\xd9\x86\xd8\xac\xd8\xa7\xd8\xa8\xdb\x8c'< ===>B'\xd9\xbE\xda\x9a\xd8\xaa\xd9\x88'< ===>B'Plattd\xc3\xbc\xc3\xbctsch'< ===> Plattd u TschB'Polski'< ===> PolskiB'Portugu\xc3\xaas'< ===> Portugu sB'Rom\xc3\xa2n\xc4\x83'< = = = ==> Rom - nB'Romani'< ===> RomaniB'\xd0\xa0\xd1\x83\xd1\x81\xd1\x81\xd0\xba\xd0\xb8\xd0\xb9< ===>B'Seeltersk'< ===> SeelterskB'Shqip'< ===> ShqipB'Simple English'< ===> Simple EnglishB'Sloven\xc4\x8dina'< ===> Sloven inaB'\xda\xa9\xd9\x88\xd8\xb1\Xd8\xaf\xdb\x8c\xdb\x8c \xd9\x86\xd8\xa7\xd9\x88\xdb\x95\xd9\x86\xd8\xaf\xdb\x8c'< ===>""B'\xd0\xa1\xd1\x80\xd0\xbf\xd1\x81\xd0\xba\xd0\xb8 / srpski'< ===> srpski / srpskiB'Suomi'< ===> SuomiB'Svenska'< ===> SvenskaB'Tagalog'< ===> TagalogB'\xe0\xae\xa4\xe0\xae\xae\xe0\xae\xbf\xe0\xae\xb4\xe0\xaf\x8d'< ===>B'\xe0\xb8\xa0\xe0\xb8\xb2\xe0\Xb8\xa9\xe0\xb8\xb2\xe0\xb9\x84\xe0\xb8\x97\xe0\xb8\xa2'< ===>B'Taqbaylit'< ===>TaqbaylitB'\xd0\xa2\xd0\xb0\xd1\x82\xd0\xb0\xd1\x80\xd1\x87\xd0\xb0/tatar\xc3\xa7a'< ===>/tatar C AB'\xe0\xb0\xa4\xe0\xb1\x86\xe0\xb0\xb2\xe0\xb1\x81\xe0\xb0\x97\xe0\xb1\x81'< ===&gTB'\xd0\xa2\xd0\xbe\xd2\xb7\xd0\xb8\xd0\xba\xd3\xa3'< ===>B'T\xc3\xbcrk\xc3\xA7e'< ===> T u rk c eB'\xd0\xa3\xd0\xba\xd1\x80\xd0\xb0\xd1\x97\xd0\xbd\xd1\x81\xd1\x8c\xd0\xba\xD0\xb0'< ===>B'\xd8\xa7\xd8\xb1\xd8\xaf\xd9\x88'< ===>B'Ti\xe1\xba\xbfNg Vi\xe1\xbb\x87t'< ===> Ti ng Vi tB'V\xc3\xb5ro'< ===> V roB'\xe6\x96\x87\xe8\xa8\x80'< ===> classical ChineseB'\xe5\x90\xb4\xe8\xaf\xad'< ===> Wu languageB'\xd7\x99\xd7\x99\xd6\xb4\xd7\x93\xd7\X99\xd7\xa9'< ===>B'\xe4\xb8\xad\xe6\x96\x87'< ===> Chinese

The modern computer is essentially a huge switch array. The computer uses electricity to trigger these switches to turn on or off. These switches are used1 To open, to have electricity, to connect, to use0 It is closed, without electricity and cut off. We call these1 and0 It is “bit”.

We use “bytes” (byte) to represent one\(8\) Position (0 and1)The sequence.

The American Standard Code for information interchange (ASCII) corresponds numbers to letters.

0b1011010   # Binary 90
90
ord('Z')  # The corresponding numbers of the letter Z
90
chr(90) 
'Z'

With the ASCII agreement, we can use it\(8\) The position (that is)\(1\) Bytes encode a character, and then you can string characters together to synthesize a word. For example:'Zed A. Shaw' We can use a set of byte sequences.[90, 101, 100, 32, 65, 46, 32, 83, 104, 97, 119],The code is as follows:

[ord(name) for name in 'Zed A. Shaw']
[90, 101, 100, 32, 65, 46, 32, 83, 104, 97, 119]

Again, a sequence similar to the Convention will eventually be converted to the on-off of the switch.

One byte can be stored\(256\)(That is,\(2 ^ 8\))A number:
\[
0 \sim 255 \; \text{Or}; 00000000 \sim 11111111\]

In order to unify the encoding mode, Unicode (Universal encoding) appears.

UTF-8(Unicode Transformation Format 8 Bits):Use most of the commonly used characters\(8\) Bit encoding, if you need to encode more characters, use “escape” to use a larger number; this encoding saves a lot of storage space.

In Python,string It is a sequence of characters encoded by UTF-8, and is the basis for displaying and processing text.bytes Python is the original byte sequence used to store UTF-8 strings.b"" ExpressByte string

Therefore, if you want to deal with the original byte string (bytes), then you need to pass..decode() To get the string (string). The original byte string does not contain encoding methods. They are byte sequences and a bunch of numbers, so you have to tell python.Decode it into a UTF string。That is,

Decode the byte string, the encoding string
(decode bytes, encode strings)

short circuit logic”

  • WhateverFalse initialand Statements are dealt with directlyFalse,The following statements are not continued.
  • Any inclusionTrue Aor Statements, as long as they are handledTrue,It will not continue to calculate down, but to return directly.True That’s right.
  • Python It runs only what it meets isTrue The first block,So if there are more than oneelif Block, only the first oneTrue The block will run.
from sys import exit
def glod_room():
    print("This room is full of gold. How much do you take?")
    
    choice = input('> ')
    if '0' in choice or '1' in choice:
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")
        
    if how_much < 50:
        print("Nice, you're not greedy, you win!")
        exit(0)
    else:
        dead("You greedy bastard!")
        

def dead(why):
    print(why, "Good Job!")
    exit(0)
glod_room()
This room is full of gold. How much do you take?
> 7
Man, learn to type a number. Good Job!



An exception has occurred, use %tb to see the full traceback.


SystemExit: 0



C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py:2971: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

exit(0) A program can be aborted, and the numeric parameter is used to indicate whether the program has been stopped due to an error.exit(0) The presentation of the program is normal.

if The rules of the statement

  1. Eachif The statement must contain oneelse。(In order to prevent the emergence of conditions that are not considered.
  2. If this is thiselse It should never be carried out because it does not have any meaning in itself, it must beelse After the statement, use a calldie Function, let it print out the error message and “die” to show you.
  3. if Nesting of sentences should not exceed two levels.
  4. takeif The statement is treated as a paragraph, every one of themif-elif-else The combination is the same as the sentence of a paragraph. Leave a blank line for the distinction between the front and the last sides of this combination.
  5. Your Boolean tests should be simple, if they are complex, you need to put their operations in a variable in the function and take a name for the variable.

.join() & .split()

ten_things = 'Apples Oranges Crows Telephone Light Sugar'
stuff = ten_things.split(' ')
stuff
['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar']
' & '.join(stuff)
'Apples & Oranges & Crows & Telephone & Light & Sugar'

import random
from urllib.request import urlopen
import sys

WORD_URL = 'http://learncodethehardway.org/words.txt'
WORDS = []

PHRASES = {
    'class %%%(%%%):':
    "Make a class named %%% that is-a %%%.",
    'class %%%(object):\n\tdef __init__(self, ***)':
    'class %%% has-a __init__ that takes self and *** params.',
    'class %%%(object):\n\tdef ***(self, @@@)':
    'class %%% has-a function *** that takes self ang @@@ params.',
    '*** = %%%()':
    'Set *** to an instance of class %%%',
    "***.***(@@@)":
    'From *** get *** function, call it with params self, @@@.',
    "***.*** = '***'":
    "From *** get the attribute and set it to '***'."
    
}

# do they want to drill phrases(Phrase) first
if len(sys.argv) == 2 and sys.argv[1] == 'english':
    PHRASES_FIRST = True
else:
    PHRASES_FIRST = False
    
# load up the words from website
for word in urlopen(WORD_URL).readlines():
    WORDS.append(str(word.strip(), encoding = 'utf-8'))
    

def convert(snippet, phrase):
    class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))]
    other_names = random.sample(WORDS, snippet.count("***"))
    results = []
    param_names = []
    
    for i in range(0, snippet.count('@@@')):
        param_count = random.randint(1, 3)
        param_names.append(', '.join(random.sample(WORDS, param_count)))
        
    for sentence in snippet, phrase:
        result = sentence[:]
        
        # fake class names
        for word in class_names:
            result = result.replace("%%%", word, 1)
            
        # fake other names
        for word in other_names:
            result = result.replace("***", word, 1)
            
        # fake parameter lists
        for word in param_names:
            result = result.replace("@@@", word, 1)
            
        results.append(result)
        
    return results


# keep going until they hit CTRAL-D
try:
    while True:
        snippets = list(PHRASES.keys())
        random.shuffle(snippets)
        
        for snippet in snippets:
            phrase = PHRASES[snippet]
            question, answer = convert(snippet, phrase)
            if PHRASES_FIRST:
                question, answer = question, answer
            
            print(question)
            
            input("> ")
            print(f"ANSWER: {answer}\n\n")
except EOFError:
    print('\nBye')