search
HomeBackend DevelopmentPython TutorialIntroduction to conditions, loops, etc. in python

Get any key-value pair in the dictionary

>>> x={'a':1,'b':2}
>>> key,value=x.popitem()
>>> key,value
('a', 1)
>>> del x[key]

Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    del x[key]
KeyError: &#39;a&#39;
>>> x
{&#39;b&#39;: 2}
>>> x[key]=value
>>> x
{&#39;a&#39;: 1, &#39;b&#39;: 2}
>>> del x[key]

Incremental assignment

>>> x=2
>>> x+=1
>>> x*=2
>>> x
>>> fnord=&#39;foo&#39;
>>> fnord+=&#39;bar&#39;
>>> fnord*=2
>>> fnord
&#39;foobarfoobar&#39;

Conditional execution if statement

>>> name=raw_input(&#39;?&#39;)
?Yq Z
>>> if name.endswith(&#39;Z&#39;):  \
   print &#39;Hello,Mr.Z&#39;

Hello,Mr.Z

else clause

>>> name=raw_input(&#39;what is your name?&#39;)
what is your name?Yq Z
>>> if name.endswith(&#39;Z&#39;):
    print &#39;Hello,Mr.Z&#39;
else:
    print &#39;Hello,stranger&#39;

    
Hello,Mr.Z

elif clause

>>> num=input(&#39;Enter a number: &#39;)
Enter a number: 5
>>> if num>0:
    print &#39;The number is position&#39;
elif num<0:
    print &#39;The number is negative&#39;
else:
    print &#39;The number is zero&#39;

    
The number is position

Conditional nested statement

>>> name=raw_input(&#39;What is your name?&#39;)
What is your name?Yq Z
>>> if name.endswith(&#39;Yq&#39;):
    if name.startswith(&#39;Z&#39;):
        print &#39;Hello,Yq Z&#39;
    elif name.startswith(&#39;K&#39;):
        print &#39;Hello,Zyq&#39;
    else:
        print &#39;Hello,Yq&#39;
else:
    print &#39;Hello,stranger&#39;

    
Hello,stranger
>>> number=input(&#39;Enter a number between 1 and 10:&#39;)
Enter a number between 1 and 10:6
>>> if number<=10 and number>=1:
    print &#39;Great!&#39;
else:
    print &#39;Wrong!&#39;

    
Great!
>>> age=10
>>> assert 0<age<100
>>> age=-1
>>> assert 0<age<100

Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    assert 0<age<100
AssertionError

while loop

>>> x=1
>>> while x<=100:
    print x
    x+=1
>>> while not name:
    name=raw_input(&#39;Please enter your name:&#39;)
    print &#39;Hello,%s !&#39; % name

    
Please enter your name:zyq
Hello,zyq !

for loop

>>> words=[&#39;this&#39;,&#39;is&#39;,&#39;an&#39;,&#39;ex&#39;,&#39;parrot&#39;]
>>> for word in words:
    print word

    
this
is
an
ex
parrot
>>> range(0,10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in range(1,8):
    print i
2
4
6

Dictionary loop (iteration)

>>> d={&#39;x&#39;:1,&#39;y&#39;:2,&#39;z&#39;:3}
>>> for key in d:
    print key,&#39;corresponds to&#39;,d[key]

    
y corresponds to 2
x corresponds to 1
z corresponds to 3

Parallel iteration

>>> names=[&#39;Anne&#39;,&#39;Beth&#39;,&#39;George&#39;,&#39;Damon&#39;]
  >>> ages=[12,19,18,20]
>>> for i in range(len(names)):
    print names[i],&#39;is&#39;,ages[i],&#39;years old&#39;

    
Anne is 12 years old
Beth is 19 years old
George is 18 years old
Damon is 20 years old
>>> zip(names,ages)
[(&#39;Anne&#39;, 12), (&#39;Beth&#39;, 19), (&#39;George&#39;, 18), (&#39;Damon&#39;, 20)]
>>> for name,age in zip(names,ages):
    print name,&#39;is&#39;,age,&#39;years old&#39;

    
Anne is 12 years old
Beth is 19 years old
George is 18 years old
Damon is 20 years old
>>> zip(range(5),xrange(100))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

Numbered iteration

>>> d
[1, 2, 4, 4]
>>> for x in d:
    if x==4:
        d[d.index(x)]=6

        
>>> d
[1, 2, 6, 6]
>>> S=[&#39;skj&#39;,&#39;kiu&#39;,&#39;olm&#39;,&#39;piy&#39;]
>>> index=0>>> for s1 in S:
    if &#39;k&#39; in s1:
        S[index]=&#39;HH&#39;
    index+=1

    
>>> S
[&#39;HH&#39;, &#39;HH&#39;, &#39;olm&#39;, &#39;piy&#39;]>>> for index,s2 in enumerate(S): #enumerate函数提供索引-值对
    if &#39;H&#39; in s2:
        S[index]=&#39;DF&#39;

        
>>> S
[&#39;DF&#39;, &#39;DF&#39;, &#39;olm&#39;, &#39;piy&#39;]

Flip, sort iteration

>>> sorted([4,3,6,8,3])
[3, 3, 4, 6, 8]
>>> sorted(&#39;Hello,world!&#39;)
[&#39;!&#39;, &#39;,&#39;, &#39;H&#39;, &#39;d&#39;, &#39;e&#39;, &#39;l&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;, &#39;o&#39;, &#39;r&#39;, &#39;w&#39;]
>>> list(reversed(&#39;Hello,world!&#39;))
[&#39;!&#39;, &#39;d&#39;, &#39;l&#39;, &#39;r&#39;, &#39;o&#39;, &#39;w&#39;, &#39;,&#39;, &#39;o&#39;, &#39;l&#39;, &#39;l&#39;, &#39;e&#39;, &#39;H&#39;]
>>> &#39;&#39;.join(reversed(&#39;Hello,world!&#39;))
&#39;!dlrow,olleH&#39;

break out of the loop

>>> for n in range(99,0,-1):
    m=sqrt(n)
    if m==int(m):
        print n
        break

while True/break

>>> while True:
    word=raw_input(&#39;Please enter a word:&#39;)
    if not word:break
    print &#39;The word was &#39;+word

    
Please enter a word:f
The word was f
Please enter a word:

else statement in loop

>>> for n in range(99,81,-1):
    m=sqrt(n)
    if m==int(m):
        print m
        break
else:
    print &#39;h&#39;

    
h

List comprehension-lightweight loop

>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x*x for x in range(10) if x%3==0]
[0, 9, 36, 81]
>>> [(x,y) for x in range(3) for y in range (3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
>>> result=[]
>>> for x in range(3):
    for y in range(3):
        result.append((x,y))
>>> result
 [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
>>> girls=[&#39;Alice&#39;,&#39;Bernice&#39;,&#39;Clarice&#39;]
>>> boys=[&#39;Chris&#39;,&#39;Arnold&#39;,&#39;Bob&#39;]
>>> [b+&#39;+&#39;+g for b in boys for g in girls if b[0]==g[0]]
[&#39;Chris+Clarice&#39;, &#39;Arnold+Alice&#39;, &#39;Bob+Bernice&#39;]

pass

>>> if name==&#39;Nsds&#39;:
    print &#39;Welcome!&#39;
elif name==&#39;UK&#39;:
    #还没完
    pass
elif name==&#39;Bill&#39;:
    print &#39;Access Denied&#39;
else:
    print &#39;Nobody!&#39;

del x and y point to a list at the same time, but deleting x does not will affect y. Only the name is deleted, not the list itself (value)

>>> x=[&#39;Hello&#39;,&#39;world&#39;]
>>> y=x
>>> y[1]=&#39;Python&#39;
>>> x
[&#39;Hello&#39;, &#39;Python&#39;]
>>> del x
>>> y
[&#39;Hello&#39;, &#39;Python&#39;]

exec

>>> exec "print &#39;Hello,world!&#39;"
Hello,world!
>>> from math import sqrt
>>> exec "sqrt=1"
>>> sqrt(4)

Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    sqrt(4)
TypeError: &#39;int&#39; object is not callable

#增加一个字典,起到命名空间的作用
>>> from math import sqrt
>>> scope={}
>>> exec &#39;sqrt=1&#39; in scope
>>> sqrt(4)
2.0
>>> scope[&#39;sqrt&#39;]

Note: The namespace is called a scope. Think of it as a place to hold variables, similar to an invisible dictionary. When executing an assignment statement such as x=1, the key x and value 1 are placed in the current namespace. This namespace is generally the global namespace.

>>> len(scope)2
>>> scope.keys()
[&#39;__builtins__&#39;, &#39;sqrt&#39;]

eval evaluation

>>> scope={}
>>> scope[&#39;x&#39;]=2
>>> scope[&#39;y&#39;]=3
>>> eval(&#39;x*y&#39;,scope)
>>> scope={}
>>> exec &#39;x=2&#39; in scope
>>> eval(&#39;x*x&#39;,scope)

Introduction to conditions, loops, etc. in python


The above is the detailed content of Introduction to conditions, loops, etc. in python. For more information, please follow other related articles on the PHP Chinese website!

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之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

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 Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools