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
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐