search
HomeBackend DevelopmentPython TutorialPython basics learning code conditions and loops

Python basics learning code conditions and loops

Dec 29, 2016 pm 05:19 PM
python basics

def func1():
    alist = ['Cathy','Terry','Joe','Health','Lucy']
    for i in  range(-1,-len(alist)-1,-1):
        print i,alist[i]
def func2():
    alist = ['Cathy','Terry','Joe','Health','Lucy']
    for i,name in enumerate(alist):
        print '%d %s' % (i,name)
import random
def func3():
    alist = ['Cathy','Terry','Joe','Health','Lucy']
    blist = [random.randint(i,10) for i in range(5)]
    for a,b in zip(alist,blist):
        print a,b
def func4():
    num = 4
    count = num / 2
    while count > 0:
        if num % count == 0:
            print count,'is the largest factor of',num
            break
        count -= 1
def showmaxfactor(num):
    count = num / 2
    while count > 1:
        if num % count == 0:
            print num,'largest factor is',count
            break
        count -= 1
        return True
    else:
        print num,'is prime'
        return False
def func5():
    for eachnum in range(10,60):
        showmaxfactor(eachnum)
def func6():
    alist = range(5)
    return map(lambda x: x ** 2,alist)
def func7():
    alist = [x ** 2 for x in range(5)]
    return alist
def func8():
    return filter(lambda x:x % 2,range(10))
def func9():
    return [x for x in range(10) if x % 2]
def func10():
    return [(x+1,y+1) for x in range(3) for y in range(5)]
import os
def func11():
    f = open('Client.py','r')
    print os.stat('Client.py').st_size
    print len([word for line in f for word in line.split(' ')])
    f.seek(0)
    print sum([len(word) for line in f for word in line.split(' ')])
def cols():
    yield 3
    yield 5
def func12():
    alist = [1,2,4,6]
    x = ((i,j) for i in alist for j in cols())
    for a in x:
        print a
def func13():
    f = open('Client.py','r')
    longest = 0
    alllines = f.readlines()
    f.close()
    for line in alllines:
        linelen = len(line.strip())
        if linelen > longest:
            longest = linelen
    return longest
def func14():
    f = open('Client.py','r')
    alllinelen = [len(x.strip()) for x in f]
    f.close()
    return max(alllinelen)
def func15():
    return max(len(x.strip()) for x in open('Client.py','r'))
def func16(x,y,z):
    alist = []
    for i in range(x,y+1,z):
        alist.append(i)
    return alist
def getfactors(num):
    for i in range(1,num+1):
        if num % i == 0:
            print i
def isperfect(num):
    sum = 0
    count = num / 2
    while count > 0:
        for i in range(1,count+1):
            if num % i == 0:
                sum += i
            count -= 1
    if sum == num:
        return True
    else:
        return False
def fibonacci(num):
    if num == 1:
        return [1]
    if num == 2:
        return [1,1]
    list = [1,1]
    if num > 2:
        for i in  range(3,num+1):
            list.append(list[-1]+list[-2])
        return list
def convert():
    start = int(raw_input(u'请输入起始值:'))
    end = int(raw_input(u'请输入结束值:'))
    for i in range(start,end+1):
        print "dec  bin  oct   hex"
        print '-' * 20
        print "%d  %s  %s  %s" % (i,bin(i),oct(i),hex(i))

The above is the content of the conditions and loops 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
Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

Python List Concatenation Performance: Speed ComparisonPython List Concatenation Performance: Speed ComparisonMay 08, 2025 am 12:09 AM

ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

How do you insert elements into a Python list?How do you insert elements into a Python list?May 08, 2025 am 12:07 AM

ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool