x = int(input('请输入一个整数:'))
if x == 0:
print('%d ==0' % x)
elif x < 0:
print('%d <0' % x)
else:
print('%d >0' % x)
输出结果:
请输入一个整数:12
12 >0
list:
print('for 测试.....')
words = ['good', 'good', 'study']
for word in words:
print(word, len(word))
输出结果:
for 测试…
good 4
good 4
study 5
range: 左闭右开,(左,右,间隔)
print('range.....')
a = range(5)
b = range(2, 5)
c = range(2, 5, 2)
print("a: ", a)
print("b: ", b)
for i in c:
print("value is", i)
输出结果:
range…
a: range(0, 5)
b: range(2, 5)
value is 2
value is 4
b = range(2, 5)
for i in b:
print("value is", i)
输出结果:
value is 2
value is 3
value is 4
# while
print('while.....')
count = 0
while (count < 9):
print('the index is:', count)
count += 1
输出结果:
while…
the index is: 0
the index is: 1
the index is: 2
the index is: 3
the index is: 4
the index is: 5
the index is: 6
the index is: 7
the index is: 8
print('break.....')
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
print(n, 'is a prime number')
//:取整除 - 返回商的整数部分(向下取整)
输出结果:
break…
3 is a prime number
4 equals 2 * 2
5 is a prime number
5 is a prime number
5 is a prime number
6 equals 2 * 3
7 is a prime number
7 is a prime number
7 is a prime number
7 is a prime number
7 is a prime number
8 equals 2 * 4
9 is a prime number
9 equals 3 * 3
# continue
print('continue.....')
for num in range(2, 10):
if (num % 2 == 0):
continue
print("num: ", num)
输出结果:
continue…
num: 3
num: 5
num: 7
num: 9
def funcname(parameter_list):
pass
class classname(object):
pass
pass语句,不执行任何内容
def sayHello():
print('Hello life!')
sayHello() # 函数调用
输出结果:
Hello life!
def printMax(a, b):
if a > b:
print(a, 'is maximum')
else:
print(b, 'is maximum')
printMax(3, 4)
x = 5
y = 7
print('参数传递')
printMax(x, y)
输出结果:
4 is maximum
参数传递
7 is maximum
def func(x):
print('x is', x)
x = 2 # 此处x是局部变量
print('Changed local x to', x)
print('局部变量')
x = 50
func(x)
print('x is still', x)
输出结果:
局部变量
x is 50
Changed local x to 2
x is still 50
def func2():
global x # 表示使用外部变量,使用函数外面的x
print('x is', x)
x = 2
print('Changed local x to', x)
print('访问外部变量:')
x = 50
func2()
print('Value of x is', x) # 函数外面x的值改变了
输出结果:
访问外部变量:
x is 50
Changed local x to 2
Value of x is 2
def say(message, times=1):
print(message * times)
print('默认参数:')
say('Hello')
say('World', 5)
输出结果:
默认参数:
Hello
WorldWorldWorldWorldWorld
def func3(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
print('关键字传参:')
func3(3, 7)
func3(25, c=24)
func3(c=50, a=100)
输出结果:
关键字传参:
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
def maximum(x, y):
if x > y:
return x
else:
return y
print('return:')
print(maximum(2, 3))
输出结果:
return:
3