search
HomeBackend DevelopmentPython TutorialPython basic learning code image collection
Python basic learning code image collectionDec 29, 2016 pm 05:18 PM
python basics

def func1():
    dict1 = {}
    dict2 = {'name':'earth','port':80}
    return dict1,dict2

def func2():
    return dict((['x',1],['y',2]))

def func3():
    adict = {}.fromkeys(['x','y'],23)
    return adict

def func4():
    alist = {'name':'earth','port':80}
    for keys in alist.keys():
        print "%s %s" % (keys,alist[keys])

def func5():
    alist = {'name':'earth','port':80}
    for keys in alist:
        print "%s %s" % (keys,alist[keys])

def func6(akey):
    alist = {'name':'earth','port':80}
    if akey in alist:
        return True
    else:
        return False

def func7(akey):
    alist = {'name':'earth','port':80}
    if alist.has_key(akey):
        return True
    else:
        return False

def func8():
    alist = {'name':'earth','port':80}
    print 'host %(name)s is running on %(port)d' % alist

def func9(akey):
    alist = {'name':'earth','port':80}
    if akey in alist:
        del alist[akey]
        return True
    else:
        return False

def func10():
    alist = {'name':'earth','port':80}
    alist.clear()
    return alist

def func11():
    alist = {'name':'earth','port':80}
    del alist

def func12(akey):
    alist = {'name':'earth','port':80}
    if akey in alist:
        return alist.pop(akey)

def func13():
    alist = {'name':'earth','a':80}
    blist = {'name':'earth','z':8080}
    return cmp(alist,blist)

def func14():
    alist = zip(('x','y'),(1,2))
    blist = dict([('xy'[i-1],i) for i in range(1,3)])
    return dict(alist),blist

def func15():
    adict = {'name':'earth','port':80}
    bdict = adict.copy()
    return bdict,len(bdict)

def func16():
    adict = {'name':'earth','port':80}
    bdict = {'name':'earth','port':8080}
    print adict.keys()
    print adict.values()
    print adict.items()
    adict.update(bdict)
    print adict

def func17():
    adict = {'name':'earth','port':80}
    for keys in sorted(adict):
        print 'adict %s has value %s' % (keys,adict[keys])

def func18(akey):
    adict = {'name':'earth','port':80}
    if adict.get(akey):
        return True
    else:
        return 'no such key!'

def func19():
    adict = {'name':'earth','port':80}
    bdict = {}.fromkeys('abc')
    print bdict
    return adict.setdefault('name','wycqhost')

import time
nowtime = time.time()
def gettime(nowtime):
    return time.strftime('%Y/%m/%d %H:%M:%S',time.localtime(nowtime))

login = {}
def newuser():
    prompt = 'login desired:'
    name = ''
    while True:
        name = raw_input(prompt)
        if login.has_key(name):
            prompt = 'name taken,try another:'
            continue
        else:
            break
    pwd = raw_input('passwd:')
    login[name] = [abs(hash(pwd))]
    login[name].append(0)
    print login

def olduser():
    nowtime = time.time()
    name = raw_input('login:')
    if name not in login:
        choose = raw_input('will you create a new user(y/n)')
        if choose.lower()[0] == 'y':
            newuser()
        else:
            pass
        showmenu()
    else:
        pwd = raw_input('passwd:')
        passwd = login.get(name)[0]
        if abs(hash(passwd)) == abs(hash(pwd)):
            if login[name][1] == 0:
                print login
                print 'welcome back',name,'you first time loggin'
            else:
                print 'welcome back',name
                if nowtime - login[name][1] <= 14400:
                    print &#39;you are already logged at time&#39;,gettime(login[name][1])
            login[name][1] = nowtime
        else:
            print &#39;login incorrect&#39;
            return

def showuser():
    print &#39;show all user:&#39;
    for user in login.keys():
        print user

def deleteuser():
    duser = raw_input(&#39;delete user:&#39;).lower()
    if duser in login.keys():
        del login[duser]
    else:
        print &#39;user %s is not exists&#39; % duser
        showmenu()

def showmenu():
    prompt = &#39;&#39;&#39;
(n)ew user login
(o)ld user login
(s)how all user
(d)elete user
(q)uit
enter choice:
&#39;&#39;&#39;
    done = False
    while not done:
        chosen = False
        while not chosen:
            try:
                choice = raw_input(prompt).strip()[0].lower()
            except (EOFError,KeyboardInterrupt):
                choice = &#39;q&#39;
            print &#39;you picked %s&#39; % choice
            if choice not in &#39;noqds&#39;:
                print &#39;invalid option,try again&#39;
            else:
                chosen = True
            if choice == &#39;q&#39;:
                done = True
            if choice == &#39;n&#39;:
                newuser()
            if choice == &#39;o&#39;:
                olduser()
            if choice == &#39;d&#39;:
                deleteuser()
            if choice == &#39;s&#39;:
                showuser()
#if __name__ == &#39;__main__&#39;:
 #   showmenu()

def func20():
    str1 = &#39;093keffeoelgn&#39;
    t = set(str1)
    s = frozenset(str1)
    return t == s

def func21():
    aset = set(&#39;xiewenbin&#39;)
    if &#39;x&#39; in aset:
        print "x in aset"

def func22():
    aset = set(&#39;strings&#39;)
    aset.add(&#39;http&#39;)
    aset.update(&#39;httpx&#39;)
    aset.remove(&#39;http&#39;)
    aset -= set(&#39;x&#39;)
    for i in aset:
        print i
    del aset

def func23():
    aset = set(&#39;abc&#39;)
    bset = set(&#39;abcedf&#39;)
    return aset <= bset

def func24():
    aset = set(&#39;markshop&#39;)
    bset = frozenset(&#39;earthshop&#39;)
    print aset | bset
    print bset & aset
    print aset ^ bset
    print aset - bset

def func25():
    s = set(&#39;cheeseshop&#39;)
    u = frozenset(s)
    s |= set(&#39;xie&#39;)
    print s
    s = set(u)
    s &= set(&#39;shop&#39;)
    print s
    s = set(u)
    s -= set(&#39;shop&#39;)
    print s
    s = set(u)
    t = frozenset(&#39;bookshop&#39;)
    s ^= t
    print s
    print len(s)
import os
def func26():
    frozenset([&#39;a&#39;,&#39;b&#39;,&#39;c&#39;])
    f = open(&#39;test.txt&#39;,&#39;w&#39;)
    for i in range(5):
        f.write(&#39;%d\n&#39;%i)
    f.close()
    f = open(&#39;test.txt&#39;,&#39;r&#39;)
    print set(f)
    f.close()
    os.remove(&#39;test.txt&#39;)

def func27():
    alist = [&#39;a&#39;,&#39;b&#39;]
    blist = [1,2]
    print dict(zip(alist,blist))

def func28():
    adict = {&#39;a&#39;:1,&#39;b&#39;:2,&#39;c&#39;:3}
    bdict = {}
    for keys in adict.keys():
        bdict[adict[keys]] = keys
    return bdict

def func29(sstr,dstr,string,casemap=True):
    assert len(sstr) >= len(dstr)
    table = dict(zip(sstr,dstr))
    print table
    if len(sstr) > len(dstr):
        temp = {}.fromkeys(sstr[len(dstr)])
        table.update(temp)
        print table
    ls = []
    for ch in string:
        if not casemap:
            if ch.lower() in table:
                ls.append(table[ch.lower()])
            elif ch.upper() in table:
                ls.append(table[ch.upper()])
            else:
                ls.append(ch)
                continue
        if ch in table:
            ls.append(table[ch])
        else:
            ls.append(ch)
    ls = [ch for ch in ls if ch]
    print ls
    return " ".join(ls)

def func30(sstr):
    alist = [chr((num + 13) % 26 + ord(&#39;a&#39;)) for num in range(26)]
    blist = [chr(num + ord(&#39;a&#39;)) for num in range(26)]
    table = dict(zip(blist,alist))
    astr = "".join(alist).upper()
    bstr = "".join(blist).upper()
    table.update(dict(zip(bstr,astr)))
    ls = []
    for ch in sstr:
        if ch in table:
            ls.append(table[ch])
        else:
            ls.append(ch)
    return " ".join(ls)

import random
def func31():
    alist = [random.randint(i,10) for i in range(10)]
    blist = [random.randint(i,10) for i in range(10)]
    aset = set(alist)
    bset = set(blist)
    print aset | bset
    print aset & bset

The above is the content of the image collection of Python basic learning code. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Use Python to Find the Zipf Distribution of a Text FileHow to Use Python to Find the Zipf Distribution of a Text FileMar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

How to Download Files in PythonHow to Download Files in PythonMar 01, 2025 am 10:03 AM

Python provides a variety of ways to download files from the Internet, which can be downloaded over HTTP using the urllib package or the requests library. This tutorial will explain how to use these libraries to download files from URLs from Python. requests library requests is one of the most popular libraries in Python. It allows sending HTTP/1.1 requests without manually adding query strings to URLs or form encoding of POST data. The requests library can perform many functions, including: Add form data Add multi-part file Access Python response data Make a request head

How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Image Filtering in PythonImage Filtering in PythonMar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How to Work With PDF Documents Using PythonHow to Work With PDF Documents Using PythonMar 02, 2025 am 09:54 AM

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

How to Cache Using Redis in Django ApplicationsHow to Cache Using Redis in Django ApplicationsMar 02, 2025 am 10:10 AM

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

Introducing the Natural Language Toolkit (NLTK)Introducing the Natural Language Toolkit (NLTK)Mar 01, 2025 am 10:05 AM

Natural language processing (NLP) is the automatic or semi-automatic processing of human language. NLP is closely related to linguistics and has links to research in cognitive science, psychology, physiology, and mathematics. In the computer science

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.