语句简介
:在python中语句后面的冒号不能省略,代码块的缩进十分重要
- if语句
基本组成:if+条件+冒号+if子句
name='bob'
if name=='bob':
print("hello,bob")
输出结果:hello,bob
- else 语句
else + 冒号+else子句
name='cat'
if name=='bob':
print("hello,bob")
else :
print('hello,alice')
输出结果:hello,alice
- elif语句
elif+条件+ 冒号+elif子句
name='bob'
if name=='alice':
print('hi,alice')
elif name=='bob':
print('hi,bob')
输出结果:
hi,bob
- while循环语句
while+条件+ 冒号+while子句
spam=1
while spam<5:
print(spam)
输出结果:
1
2
3
4
- break语句
用来跳出循环语句
while True:
print('enter your name')
name=input()
if name=='bob':
break
输出结果:
enter your name
alice
enter your name
mike
enter your name
bob
#遇到bob结束while循环
- continue语句
遇到continue语句,跳回到循环开始处
while True:
print('please input your username')
name=input()
if name!='bob':
continue
print('please input your password')
password=input()
if password =='nice':
break
输出结果:
please input your username
mary
please input your username
bob
please input your password
god
please input your username
bob
please input your password
nice
- for语句
for+变量名+in +range()方法+ 冒号+for子句
>>> total=0
>>> for i in range(101):
... total=total+i
...
>>> print(total)
5050
- import 导入语句
import +模块名称
import的简单使用
#random模块中的randint求值为传递给他的2个整数之间的随机数
>>> import random
>>> for i in range(5):
... print(random.randint(1,10))
...
3
6
10
2
10
return语句
函数调用求值的结果为函数的返回值 :return +函数返回的值和表达式
def语句
定义一个函数:def+函数名(参数)+冒号+函数体
>>> import random
>>> def getnum(number):
... if number==1:
... return 'a'
... if number==2:
... return 'b'
... else :
... return 'c'
>>> print(getnum(random.randint(1,2)))
a
- global语句
global+变量名表明该变量为全局变量
>>> def s():
... global eggs
... eggs=1
... print(eggs)
...
>>> eggs=2
>>> s()
1
>>> print(eggs)
1
>>>
最后附上神奇代码——collatz序列
def c(number):
if number%2==0:
number=number//2
print(number)
return number
if number%2!=0:
number=3*number+1
print(number)
return number
number=int(input())
while number!=1:
number=c(number)