Python是一种面向对象、解释型的高级程序设计语言。
解释型就代表:Python的开发过程中没有了编译的环节。
变量类型和运算符
变量
就是存储在内存中的值,它可以指定不同的数据类型,因此这些变量可以存储字符,整数或者小数等
Python包含五个标准的数据类型
- Numbers(数字)
- String(字符串)
- List(列表)
- Tuple(元组)
- Dictionary(字典)
变量赋值
Python中的变量赋值无需声明类型,但是变量在使用前都必须赋值,因为只有变量赋值以后这个变量才会被创建
变量名=储存在该变量中的值
age=23 #整型
height=1.65 #浮点型
name=“Harry” #字符串
Python还可以同时为多个变量赋值a,b,c=23,1.65,"Harry"
字符串str='Welcome to my world!'
print str #输出完整字符串
print str[0] #输出第一个字符
print str[1:4] #输出第2至4之间的字符
print str[5:] #输出第六个字符开始后的字符
print str*3 #输出字符串三次
print str+"Python"#输出拼接后的字符串
运行结果
Welcome to my world!
W
elc
me to my world!
Welcome to my world!Welcome to my world!Welcome to my world!
Welcome to my world!Python
运算符
- 算术运算符
加减乘,符号分别是+、-、*
%是取模,也就是得出除法的余数
//相反取的是商的整数部分
- 比较运算符
- 赋值运算符
- 逻辑运算符
- 位运算符
条件语句
python程序中要遵循严格的缩进,没有缩进或缩进错误,程序都无法正确运行。
一般判断语句后要使用缩进,4个空格或是敲一下tab键,大部分编辑器也已经替我们做了这个工作
num1=5
if num1==1:
print '是1'
elif num1>=2 and num1<4:
print '2到4之间'
elif num1>=4 and num1<=10:
print '4到10之间'
else:
print 'other'
条件中有用()括起来的,则优先执行
循环语句
num=0
while(num<=10):
print('this number is',num)
num=num+1
输出
this number is 0
this number is 1
this number is 2
this number is 3
this number is 4
this number is 5
this number is 6
this number is 7
this number is 8
this number is 9
this number is 10
continue用于跳过本次循环,break则是用于退出整个循环
num=0
while(num<=10):
num=num+1
if num%2==0:
continue
print(num)
输出1
3
5
7
9
11
添加一行num=0
while(num<=10):
num=num+1
if num%2==0:
continue
print(num)
if num>6:
break
输出
1
3
5
7
小例子import random
answer = int(random.uniform(1,10)) #产生一个随机数字
number=int(input('猜猜数字:'))#表示设置一个输入框,把输入的数字赋值给变量number
if answer==number:
print('第一次就正确!')
while(number!=answer):
if(number<answer):
print('猜小啦')
number=int(input('再猜一次:'))
if(number>answer):
print('猜大啦')
number=int(input('再猜一次:'))
if(number==answer):
print('猜对啦')
结果猜猜数字:5
猜大啦
再猜一次:4
猜大啦
再猜一次:2
猜大啦
再猜一次:1
猜对啦
for letter in'Harry Potter':
print('字母有',letter)
animals=['dog','fish','cat','monkey']
for animal in animals:
print('动物有',animal)
#通过序列索引迭代
for index in range(len(animals)):
print('动物有',animals[index])
#函数len()返回列表的长度,也就是列表中元素的个数,
#range()用于返回一个序列的数。
运行结果
字母有 H
字母有 a
字母有 r
字母有 r
字母有 y
字母有
字母有 P
字母有 o
字母有 t
字母有 t
字母有 e
字母有 r
动物有 dog
动物有 fish
动物有 cat
动物有 monkey
动物有 dog
动物有 fish
动物有 cat
动物有 monkey