打印
print("I love python") #I love python
python语句不用分号,注释用#
print("I love python\n" * 8)
#I love python
#I love python
#I love python
#I love python
#I love python
#I love python
#I love python
#I love python
print("hello " + "python") #hello python
小实例
print("-------------hello python-------------")
temp = input("请输入:")
guess = int(temp)
if guess == 8:
print("猜对了")
else:
print("猜错了")
print("游戏结束了")
#BIF=Built-in functions 内置函数
#缩进是python的灵魂
dir(__builtins__) 内置函数dir可以查看python所有的内置函数(纯小写的才是内置函数)
help(input) 介绍input函数的作用
python变量
teacher = "good"
print(teacher) #good
first = 9
second = 90
third = first + second
print(third) #99 使用变量前,变量必须赋值
命名规范:
1、变量名可以包括:字母,数字,下划线,不能以数字开头
2、python区分大小写
字符串
原始字符串:
str = r'c:\a\b\c' #在字符串前面加上r即可,也可以使用转义字符
str
# 'c:\\a\\b\\c'
print(str)
# c:\a\b\c
三重引号字符串:
str = """我爱
python,python
如此完美"""
str
# '我爱\npython,python\n如此完美'
print(str)
# 我爱
# python,python
# 如此完美
逻辑运算符
and 和 or
python的模块思想
import random
random模块中有一个randint()函数,返回一个随机整数
import random
secret = random.randint(1, 10)
print("-------------hello python-------------")
guess = -1
while guess != secret:
temp = input("请输入:")
guess = int(temp)
if guess == secret:
print("猜对了")
else:
if guess > secret:
print("猜大了")
else:
print("猜小了")
print("游戏结束了")
python的数据类型
- 整形
- 浮点型
- 布尔值
True + True
# 2
True + False
# 1
- e记法
1e10
# 10000000000.0
0.00000000000001
# 1e-14
类型转换:
a = '88'
b = int(a)
b
# 88
str(b)
# '88'
float(b)
# 88.0
float(a)
# 88.0
int(float(b))
# 88
str("5e10")
# '5e10'
str = "hello"
str
# 'hello'
str("5e10")
# str是内置函数,在被赋值以后str变为一个变量
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
str("5e10")
TypeError: 'str' object is not callable
type(True)
# <class 'bool'>
type(5.12)
# <class 'float'>
a = 'hello'
isinstance(a, str)
# True
isinstance(a, int)
# False
常用操作符
- 算术运算符(+,-,*,/,%,**,//)
c = 10 / 8
c
# 1.25
10 // 8
# 1
10.0 // 8
# 1.0
10 ** 8
# 100000000 10的8次方
-3 ** 2
# -9
3 ** -2
# 0.1111111111111111 #**符号比左侧的运算符优先级高,比右侧的运算符优先级低
- 比较操作符
- 逻辑操作符(and, or, not)
唯一一个三元运算符
断言
assert 3 > 4
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
assert 3 > 4
AssertionError
#当assert后面的条件为假的时候,程序自动崩溃,抛出AssertionError异常
for循环
member = ['A', 'B', 'C', 'Def'] #列表
for j in member:
print(j, len(j)) #len内置函数求字符串的长度
# A 1
# B 1
# C 1
# Def 3
for i in range(5): #生成从0到end-1的数字序列
print(i)
#0
#1
#2
#3
#4
for i in range(1, 5): #生成从start到end-1的数字序列
print(i)
#1
#2
#3
#4
for i in range(2, 9, 3): #生成从start开始,以step==3递增的序列,最后一个数<end
print(i)
#2
#5
#8
for i in range(9,3,-1): #生成从start开始,以step==-1递减的序列,最后一个数>end
print(i)
#9
#8
#7
#6
#5
#4
break和continue
bingo = "exit"
answer = input("请输入exit退出:")
while True:
if answer == bingo:
break
answer = input("请输入exit:")
print("终于退出了")
for i in range(10):
if i % 2 != 0:
print(i)
continue
i += 2
print(i)
# 2
# 1
# 4
# 3
# 6
# 5
# 8
# 7
# 10
# 9