bool
t, f = True, False
print type(t) # Prints "<type 'bool'>"
 
字符串
hello = 'hello'   # 实在想不出的时候就用hello world
world = "world"
print hello, len(hello) # 字符串长度
 
 
列表,注意,python的容器可以容纳不同的数据类型,[ ] 中括号是列表
xs = [3, 1, 2]   # 建一个列表
print xs, xs[2]
print xs[-1]     # 用-1表示最后一个元素,输出来
 
[3, 1, 2] 2

2
 
xs.append('happy') # 可以用append在尾部添加元素
print xs
[3, 1, 'Hanxiaoyang', 'happy']
 
x = xs.pop()     # 也可以把最后一个元素“弹射”出来
print x, xs
 
happy [3, 1, 'Hanxiaoyang']
 
 
列表切片
 
nums = range(5)    # 0-4
print nums         # 输出 "[0, 1, 2, 3, 4]"
print nums[2:4]    # 下标2到4(不包括)的元素,注意下标从0开始
print nums[2:]     # 下标2到结尾的元素; prints "[2, 3, 4]"
print nums[:2]     # 直到下标2的元素; prints "[0, 1]"
print nums[:]      # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]"
print nums[:-1]    # 直到倒数第一个元素; prints ["0, 1, 2, 3]"
nums[2:4] = [8, 9] # 也可以直接这么赋值
print nums         # Prints "[0, 1, 8, 8, 4]"
 
[0, 1, 2, 3, 4]
[2, 3]
[2, 3, 4]
[0, 1]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]

[0, 1, 8, 9, 4]
 
 
animals = ['喵星人', '汪星人', '火星人']
for animal in animals:
    print animal
 
喵星人
汪星人

火星人
 
又要输出元素,又要输出下标怎么办,用 enumerate 函数:
animals = ['喵星人', '汪星人', '火星人']
for idx, animal in enumerate(animals):
    print '#%d: %s' % (idx + 1, animal)
 
#1: 喵星人
#2: 汪星人

#3: 火星人
 
 
List comprehensions:
 
如果对list里面的元素都做一样的操作,然后生成一个list,用它最快了,这绝对会成为你最爱的python操作之一:
 
# 求一个list里面的元素的平方,然后输出,很out的for循环写法
nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
    squares.append(x ** 2)
print squares
[0, 1, 4, 9, 16]
 
nums = [0, 1, 2, 3, 4]
# 对每个x完成一个操作以后返回来,组成新的list
squares = [x ** 2 for x in nums]
print squares
[0, 1, 4, 9, 16]
 
 
nums = [0, 1, 2, 3, 4]
# 把所有的偶数取出来,平方后返回
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print even_squares
 
 
字典 { }是字典
 
d = {'cat': 'cute', 'dog': 'furry'}  # 建立字典
print d['cat']       # 根据key取value
print 'cat' in d     # 查一个元素是否在字典中
cute

True
 
d['fish'] = 'wet'    # 设定键值对
print d['fish']      # 这时候肯定是输出修改后的内容
wet
 
print d['monkey']  # 不是d的键,肯定输不出东西
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-6-f37735e1a686> in <module>()
----> 1 print d['monkey']  # 不是d的键,肯定输不出东西

KeyError: 'monkey'
 
print d.get('monkey', 'N/A')  # 可以默认输出'N/A'(取不到key对应的value值的时候)
print d.get('fish', 'N/A')
N/A

N/A
 
del d['fish']        # 删除字典中的键值对
print d.get('fish', 'N/A') # 这会儿就没有了
 
N/A
 
你可以这样循环python字典取出你想要的内容:
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
    legs = d[animal]
    print 'A %s has %d legs' % (animal, legs)
 
A person has 2 legs
A spider has 8 legs

A cat has 4 legs
 
用iteritems函数可以同时取出键值对:
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.iteritems():
    print 'A %s has %d legs' % (animal, legs)
 
A person has 2 legs
A spider has 8 legs

A cat has 4 legs
 
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print even_num_to_square
even_list = [ x ** 2 for x in nums if x % 2 == 0]
print even_list
{0: 0, 2: 4, 4: 16}

[0, 4, 16]
 
Set:不包含相同的元素,没有value,只有key,用{}表示
 
元组(tuple):元组可以作为字典的key或者set的元素出现,但是list不可以作为字典的key或者set的元素。
 
d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys
t = (5, 6)       # Create a tuple
print type(t)
print d[t]       
print d[(1, 2)]
<type 'tuple'>
5
1
 
 
函数
def sign(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'
 
for x in [-1, 0, 1]:
    print sign(x)
negative
zero

positive
 
函数名字后面接的括号里,可以有多个参数,你自己可以试试:
def hello(name, loud=False):
    if loud:
        print 'HELLO, %s' % name.upper()
    else:
        print 'Hello, %s!' % name
 
hello('Bob')
hello('Fred', loud=True)
Hello, Bob!
HELLO, FRED
 
class Greeter:
 
    # 构造函数
    def __init__(self, name):
        self.name = name  # Create an instance variable
 
    # 类的成员函数
    def greet(self, loud=False):
        if loud:
            print 'HELLO, %s!' % self.name.upper()
        else:
            print 'Hello, %s' % self.name
 
def hello(name, loud=False):
    if loud:
        print 'HELLO, %s' % name.upper()
    else:
        print 'Hello, %s!' % name
 
 
g = Greeter('Fred')  # 构造一个类
g.greet()            # 调用函数; prints "Hello, Fred"
g.greet(loud=True)   # 调用函数; prints "HELLO, FRED!"
g.greet(True)
 
Hello, Fred
HELLO, FRED!
HELLO, FRED!
 
 
 
 

python 入门的更多相关文章

  1. python入门简介

    Python前世今生 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC ...

  2. python入门学习课程推荐

    最近在学习自动化,学习过程中,越来越发现coding能力的重要性,不会coding,基本不能开展自动化测试(自动化工具只是辅助). 故:痛定思痛,先花2个星期将python基础知识学习后,再进入自动化 ...

  3. Python运算符,python入门到精通[五]

    运算符用于执行程序代码运算,会针对一个以上操作数项目来进行运算.例如:2+3,其操作数是2和3,而运算符则是“+”.在计算器语言中运算符大致可以分为5种类型:算术运算符.连接运算符.关系运算符.赋值运 ...

  4. Python基本语法[二],python入门到精通[四]

    在上一篇博客Python基本语法,python入门到精通[二]已经为大家简单介绍了一下python的基本语法,上一篇博客的基本语法只是一个预览版的,目的是让大家对python的基本语法有个大概的了解. ...

  5. Python基本语法,python入门到精通[二]

    在上一篇博客Windows搭建python开发环境,python入门到精通[一]我们已经在自己的windows电脑上搭建好了python的开发环境,这篇博客呢我就开始学习一下Python的基本语法.现 ...

  6. visual studio 2015 搭建python开发环境,python入门到精通[三]

    在上一篇博客Windows搭建python开发环境,python入门到精通[一]很多园友提到希望使用visual studio 2013/visual studio 2015 python做demo, ...

  7. python入门教程链接

    python安装 选择 2.7及以上版本 linux: 一般都自带 windows: https://www.python.org/downloads/windows/ mac os: https:/ ...

  8. Python学习【第二篇】Python入门

    Python入门 Hello World程序 在linux下创建一个叫hello.py,并输入 print("Hello World!") 然后执行命令:python hello. ...

  9. python入门练习题1

    常见python入门练习题 1.执行python脚本的两种方法 第一种:给python脚本一个可执行的权限,进入到当前存放python程序的目录,给一个x可执行权限,如:有一个homework.py文 ...

  10. Python入门版

    一.前言 陆陆续续学习Python已经近半年时间了,感觉到Python的强大之外,也深刻体会到Python的艺术.哲学.曾经的约定,到现在才兑现,其中不乏有很多懈怠,狼狈. Python入门关于Pyt ...

随机推荐

  1. Android Edittext点击全选输入框内容

  2. Eclipse系列:如何断点调试web项目

    一直不知道如何在Eclipse中断点调试跟踪问题,今天试了一把,大致的步骤如下: 1)事先在需要断点跟踪的代码行左侧空白处双击处设置断点: 2)在工程列表中选中要调试的工程,然后点击Debug on ...

  3. [CareerCup] 4.2 Route between Two Nodes in Directed Graph 有向图中两点的路径

    4.2 Given a directed graph, design an algorithm to find out whether there is a route between two nod ...

  4. LeetCode 笔记27 Two Sum III - Data structure design

    Design and implement a TwoSum class. It should support the following operations: add and find. add - ...

  5. Java并发之:生产者消费者问题

    生产者消费者问题是Java并发中的常见问题之一,在实现时,一般可以考虑使用juc包下的BlockingQueue接口,至于具体使用哪个类,则就需要根据具体的使用场景具体分析了.本文主要实现一个生产者消 ...

  6. windows API 开发飞机订票系统 图形化界面 (一)

    去年数据结构课程设计的作品,c语言实现,图形化界面使用windows API实现. 首发在我csdn博客:http://blog.csdn.net/u013805360/article/details ...

  7. [bzoj 2005][NOI 2010]能量采集(容斥原理+递推)

    题目:http://www.lydsy.com/JudgeOnline/problem.php?id=2005 分析:首先易得ans=∑gcd(x,y)*2+1 然后我就布吉岛了…… 上网搜了下题解, ...

  8. DOM系列---DOM操作样式

    发文不易,若转载传播,请亲注明出处,谢谢! 一.操作样式 CSS作为(X)HTML的辅助,可以增强页面的显示效果.但不是每个浏览器都能支持最新的CSS能力.CSS的能力和DOM级别密切相关,所以我们有 ...

  9. Spring aop的实现原理

    简介 前段时间写的java设计模式--代理模式,最近在看Spring Aop的时候,觉得于代理模式应该有密切的联系,于是决定了解下Spring Aop的实现原理. 说起AOP就不得不说下OOP了,OO ...

  10. JS模式:策略模式,感觉就是一个闭包存储信息,然后是加一些验证方法--还看了老半天

    <!DOCTYPE html> <html> <head> <title></title> </head> <body&g ...