Python入门

Life is short, I use Python.

版本:3.6
文档:The Python Language Reference
入门:廖雪峰Python教程
环境:Win 10 / Linux
安装:sudo apt install python

基础

hello,world!

print('hello,world!')

Python之禅

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

指定解释器,对Linux

#!/usr/bin/python3

输入输出

a = input()
print(a)

数据类型:整数,浮点数,字符串
格式化输入输出(与C语言一致):%d %f %s %x
整数浮点运算:* / // %

print(10/3)
print(10//3)
print(10%3)

字符串与编码
指定编码格式,确保编辑器使用UTF-8 without BOM编码

# -*- coding: utf-8 -*-

list(可变) & tuple(不可变对象) & dict(可变)& set(可变)

A = [1, 2, 'hello', 'world']
B = (1,23,5,'shit')
C = {
  1:10, 'hello':'world'}
D = {
  1,2,3}

条件分支

a = 5
if a > 10:
    print('a > 10')
elif a > 5:
    print('5 < a <= 10')
else:
    print('a <= 5')

循环

A = [1,2,3]
for a in A:
    print(a)
n = 1
while n < 10:
    print(n)
    n = n+1

缩进控制代码块层次,推荐使用空格而不是制表符。

函数

内建函数
函数定义

def power2(x):
    return x*x
print(power2(10))

默认参数,从后往前添加(与C++类似)

def power(x, n = 2):
    res = 1
    while n > 0:
        res *= x
        n = n-1
    return res

可变参数

# variable arguments, pass arguments as a tuple
def calc(*numbers):
    sum  = 0
    for n in numbers:
        sum = sum + n*n
    return sum

print(calc(1,2,3,4))
print(calc(*[1,2,3,4]))
# use * to change elements of a tuple or list into variable arguments
nums = [
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值