1.安装python环境
略
2.编写python程序
2.1注释
单行注释:
# 这是单行注释
print("这是单行注释")
多行注释:
'''
print("这是多行注释")
print("这是多行注释")
print("这是多行注释")
'''
中文注释:
若在程序中用到了中文,直接运行输出,程序会出错。需在程序的开头写入如下代码:
# -*- coding=utf-8 -*-
2.2变量类型及关键字
-
变量可以是任意的数据类型,在程序中用一个变量名表示
-
变量名必须是大小写英文 数字 下划线 的组合,不能以数字开头
-
关键字
具有特殊功能的标识符,python已经使用,不允许定义与关键字相同名字的标识符 -
查看关键字
import keyword
print(keyword.kwlist)
结果:
[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
2.3输出
- 普通输出
# 这是普通输出
print("普通输出")
- 格式化输出
# 格式化输出
year = 2020
month = 11
day = 28
print("今年是%d年" % year)
print("今天是%d年%d月%d日" % (year, month, day))
- 换行输出 \n
# 换行输出
print("今年是%d年\n今天是%d年%d月%d日" % (year, year, month, day))
条件判断语句
if True:
print("true")
else:
print("false")
- 石头剪刀布小游戏
import random
while True:
player_in = int(input("--石头剪刀布小游戏--\n请出拳 [剪刀(0)石头(1)布(2)]\n"))
while player_in not in range(0, 3):
print('输入错误,请重新输入!')
player_in = int(input())
computer_in = random.randint(0, 2)
if computer_in == 0:
computer = '剪刀'
elif computer_in == 1:
computer = '石头'
else:
computer = '布'
print('计算机出的为 %s'%computer)
if player_in == computer_in:
print('tie break')
elif (player_in == 0 and computer_in == 2) or (player_in == 1 and computer_in == 0) or (player_in == 2 and computer_in == 1):
print('you won!')
else:
print('you lost!')
4.循环语句
- for in 语句
for i in range(0, 10):
print(i)
- while 循环
count = 10
while count<5:
print(count, '小于5')
count+=1
else:
print(count, '大于或等于5')
- break continue pass
break与continue与其它语言相同,break跳出for和while循环体,continue跳过当前循环,直接进行下一轮循环
pass语句是空语句,用来占位,不做任何事情
九九乘法表的实现:
for i in range(1, 10):
for j in range(1, i + 1):
print("%d*%d=%d" % (i, j, i * j), end='\t')
j += 1
print('\n')
未完。。