Python基本语法

获取变量类型:

print type(42)
print type(4.2)
print type('spam')

if(type(1) == type(2.0)):
  print "equal"
else:
  print "not equal"

 

list:

start_list = [5, 888, 1, 2, 4]
square_list = []

print len(start_list) # number of items

start_list.remove(888) # remove an item by value
del start_list[0] # remove an item by index
for num in start_list:
  square_list.append(num*num) # append to tail

square_list.sort() # alphabetic order
print square_list

 

dictionary:

zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}i

del zoo_animals['Unicorn'] # remove an item
zoo_animals['Rockhopper Penguin'] = 'anything'  # change an item
print zoo_animals

for one_key  in zoo_animals:
    print zoo_animals[one_key]

 

# dictionary can hold many different types of values
inventory = {
    'gold' : 500,
    'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
    'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}

# add a key called 'packet', and set the value of this key to be a list
inventory['pocket'] = ['seashell', 'strange berry', 'lint']

# sort the list
inventory['backpack'].sort()

# remove an item from the list stored under the 'backpack' key
inventory['backpack'].remove('dagger')

# add 50 to the number stored under the 'gold' key
inventory['gold'] = inventory['gold']+50

 

 引入模块:

(1)  import math  // recommended way
print math.sqrt(4)
(2) from math import sqrt // recommended way
print sqrt(4)
(3) from math import * // NOT recommended way
print sqrt(4)

函数定义和调用:

def cube(number):
    return number**3

def by_three(number):
    if(number%3 == 0):
        return cube(number)
    else:
        return False

print by_three(3)

 

转载于:https://www.cnblogs.com/ruanchao/p/4866294.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值