Getting started with iPython+Notebook

Getting started with Python

Create some variables in Python

i = 4  # int
type(i)
int
f = 4.1  # float
type(f)
float
b = True  # boolean variable
s = "This is a string!"
print s
This is a string!

Advanced python types

l = [3,1,2]  # list
print 'Hello World!'
Hello World!
print l
[3, 1, 2]
d = {'foo':1, 'bar':2.3, 's':'my first dictionary'}  # dictionary
print d
{'s': 'my first dictionary', 'foo': 1, 'bar': 2.3}
print d['foo']  # element of a dictionary
1
n = None  # Python's null type
type(n)
NoneType

Advanced printing

print "Our float value is %s. Our int value is %s." % (f,i)  # Python is pretty good with strings
Our float value is 4.1. Our int value is 4.

Conditional statements in python

if i == 1 and f > 4:
    print "The value of i is 1 and f is greater than 4."
elif i > 4 or f > 4:
    print "i or f are both greater than 4."
else:
    print "both i and f are less than or equal to 4"
i or f are both greater than 4.

Conditional loops

print l
[3, 1, 2]
for e in l:
    print e
3
1
2

Note that in Python, we don’t use {} or other markers to indicate the part of the loop that gets iterated. Instead, we just indent and align each of the iterated statements with spaces or tabs. (You can use as many as you want, as long as the lines are aligned.)

counter = 6
while counter < 10:
    print counter
    counter += 1
6
7
8
9

Creating functions in Python

Again, we don’t use {}, but just indent the lines that are part of the function.

def add2(x):
    y = x + 2
    return y
i = 5
add2(i)
7

We can also define simple functions with lambdas:

square = lambda x: x*x
square(i)
25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值