11月28日-python语法学习

1、输入输出

// 输出,,会自动被替换成拼接字符串的空格
print'hello world'
print "this is a beautiful sky","and we all love it"
print(300)
print '100+200=',100+200

2、python变量

#python中的变量不需要声明,直接定义即可,在初始化的时候决定变量的类型,使用"="来进行初始化和赋值操作
count=0
miles=1000.0
name="Bob"
kilometers=12*13
n=10
n1=n*10
n*=10
print count,miles ,name ,kilometers,n,n1
  • List item

使用type可以产看变量的类型

>>> a = 1
>>> type(a)
<type 'int'>
>>> a = 1.0
>>> type(a)
<type 'float'>

3、字符串

>>> a = 'My name is "wangyinna"'
>>> print a
My name is "wangyinna"
  • List item

数组&切片

>>> pystr = 'hehe'
>>> pystr[0]
'h'
>>> pystr[-1]
'e'
>>> pystr[1:3]
'eh'
>>> pystr[1:-1]
'eh'
>>> pystr[1:]
'ehe'
>>> pystr[:2]
'he'
>>> pystr[:]
'hehe'
  • List item

使用len函数获取字符串长度

 >>> a = 'hehe'
>>> print(len(a))
4
  • List item

格式化字符串

 a=100
 print("a = %d" % a)
a = 100

4、认识bool类型
Python中用True和False来表示布尔值(第一个字母大写)

 >>> a = True
>>> print a
True
>>> print(type(a))
<type 'bool'>

5、列表、元组、字典
使用 [] 来表示列表, 使用 () 来表示元组.使用{}来表示字典
#列表和元组能保存任意数量, 任意类型的Python对象
#可以使用下标来访问元素
#使用贴片操作获得子集[:]
#列表中的元素可以修改,元组中的元素不能修改

 >>> alist = [1, 2, 3, 4]
>>> alist
[1, 2, 3, 4]
>>> atuple = (1, 2, 3, 4)
>>> atuple
(1, 2, 3, 4)
>>> a = { 'ip' : '127.0.0.1'}     # 创建字典
>>> a['ip']      # 取字典中的元素
'127.0.0.1'
>>> a['port'] = 80   # 插入新键值对
>>> a
{'ip': '127.0.0.1', 'port': 80}

使用id函数查看变量的地址

a=100
print id(a)
>>>140439875256064

6、if语句

a=1
b=2
if a>b:
    print 'hehe'
else:
    print 'haha'

7、while语句

i=0
while  i<4:
    i+=1
    print 'hehe'

8、for循环

#for循环的三种写法
a='hehe'
for c in a:
    print c

a={'ip':'127.0.0.1','port':80}
for key in a:
    print key,a[key]


for i in range(0,3):
    print 'loop %d'% i

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值