现在的位置: 首页 > 综合 > 正文

Python入门

2013年09月05日 ⁄ 综合 ⁄ 共 6305字 ⁄ 字号 评论关闭

开始学习python,懒得手动记笔记,写在博客里作为我的学习记录吧!新的一年很快就要来了,2010经历了很多事以至于我现在心里都很压抑。

新的一年希望工作有更好的发展!废话不多说了,开始学习!

我的学习资料来自于:http://www.tutorialspoint.com/python/python_quick_guide.htm

  • Python is Interpreted

  • Python is Interactive

  • Python is Object-Oriented

  • Python's feature highlights include:

  • Easy-to-learn

  • Easy-to-read

  • Easy-to-maintain

  • A broad standard library

  • Interactive Mode

  • Portable

  • Extendable

  • Databases

  • GUI Programming

  • Scalable

    以上说的这些我还不能全部领会。王婆卖瓜,还是回过头来看吧!

先来个简单的hello world:

Microsoft Windows XP [Version 5.1.2600]

(C) Copyright 1985-2001 Microsoft Corp.

C:/Documents and Settings/Administrator>python print "hello world";

python: can't open file 'print': [Errno 2] No such file or directory

C:/Documents and Settings/Administrator>python

Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on

win32

Type "help", "copyright", "credits" or "license" for more information.

>>> print "hello world!";

  File "<stdin>", line 1

    print "hello world!";

                       ^
SyntaxError: invalid syntax

>>>

>>>

明白什么叫出师不利吧,第一个hello world 居然不行,google下原来是版本的问题,我装的是3.1.2而在3版本必须写成这样

print ("hello world");

 

Python中的保留字(先留着,回头看):

and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

 

Python : there are no braces to indicate blocks of code
for class and function definitions or flow control. Blocks of code are
denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount

.

貌似python是用强制性的空格来进行缩进和分段的,而且位于同一段的缩进空格数必须相同。

 

感觉这是个问题,估计有的人会不习惯,不知道我能否习惯不。先过,等会回头看。

 

Multi-Line Statements:

/:

allow the use of the line continuation character (/)

to denote that the line should continue.

total = item_one + /
item_two + /
item_three

但是申明中如果含有:[], {}, or () 则不需要。

Quotation in Python:

single ('), double (") and triple (''' or """)

都是合法的,但是必须同一个结尾,可以配对。

 

Comments in Python:

# 这个好理解,不多说,多段注释就每行都#;

 

补充: 刚查了下资料,发现python还是有多行注释的:

具体方法就是用:

"""

sads

sdsd

sads

"""

 

或者三个单引号

’''

'''

 

Multiple Statements on a Single Line:  

这个好理解,;;;;


Multiple Statement Groups as Suites:

Groups of individual statements making up a single code block are called suites
in Python.

Compound or complex statements, such as if, while, def, and class, are those which require a header line and a suite.

Header lines begin the statement (with the keyword) and terminate
with a colon ( : ) and are followed by one or more lines which make up
the suite.

Example:

if expression : 
suite
elif expression :
suite
else :
suite

Python 的标准数据类型:

Python has five standard data types:

  • Numbers

  • String

  • List

  • Tuple

  • Dictionary

Python Strings:

Strings in Python are identified as a contiguous set of characters in between quotation marks.

Example:

#!/usr/bin/python

str = 'Hello World!'

print  (str)# Prints complete string

print (str[0]) # Prints first character of the string print

print (str[2:5]) # Prints characters starting from 3rd to 6th print

print (str[2:]) # Prints string starting from 3rd character

print (str * 2) # Prints string two times

print (str + "TEST") # Prints concatenated string 

 

python3.0版本中加括号的非常烦人!!!

 

输出为:

D:/>python test.py
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

这个比较方便,就是字符数组,字符串连接的话直接用+就可以。

话说python 的line后面结尾加不加;都是可以接受的,python是大小写敏感的。

 

 

Python List:

Lists are the most versatile of Python's compound data types. A list
contains items separated by commas and enclosed within square brackets
([]).

D:/>type test.py
#! /usr/bin/python
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ];
tinylist = [123, 'john'];

print (list);          # Prints complete list
print (list[0]);       # Prints first element of the list
print (list[1:3]);     # Prints elements starting from 2nd to 4th
print (list[2:]);     # Prints elements starting from 3rd element
print (tinylist * 2); # Prints list two times
print (list + tinylist); # Prints concatenated lists

D:/>python test.py
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

 

Python的元组:

和list比较:

(1)tuples are enclosed within parentheses.用原括号申明

(2)Tuples can be thought of as read-only
lists.

 

tuple = (
'abcd', 786 , 2.23, 'john', 70.2  )

tinytuple = (
123, 'john')

 

Python的字典:

Python Dictionary:

Python 's dictionaries are hash table type. They work like
associative arrays or hashes found in Perl and consist of key-value
pairs.

 

几个需要注意的点:{}申明,键值对用 key: value


tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (tinydict['name']) # Prints value for 'one' key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values

D:/>python test.py
john
{'dept': 'sales', 'code': 6734, 'name': 'john'}
dict_keys(['dept', 'code', 'name'])
dict_values(['sales', 6734, 'john'])

 

以上的都是比较浅显的。以后会进一步学习

 

如果想获取更多python更多的执行信息,可以使用python -h 参看:

C:/Documents and Settings/Administrator>python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
-B     : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d     : debug output from parser; also PYTHONDEBUG=x
-E     : ignore PYTHON* environment variables (such as PYTHONPATH)
-h     : print this help message and exit (also --help)
-i     : inspect interactively after running script; forces a prompt even
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-m mod : run library module as a script (terminates option list)
-O     : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x
-OO    : remove doc-strings in addition to the -O optimizations
-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S     : don't imply 'import site' on initialization
-u     : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x
         see man page for details on internal buffering relating to '-u'
-v     : verbose (trace import statements); also PYTHONVERBOSE=x
         can be supplied multiple times to increase verbosity
-V     : print the Python version number and exit (also --version)
-W arg : warning control; arg is action:message:category:module:lineno
-x     : skip first line of source, allowing use of non-Unix forms of #!cmd
file   : program read from script file
-      : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]

Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH   : ';'-separated list of directories prefixed to the
               default module search path.  The result is sys.path.
PYTHONHOME   : alternate <prefix> directory (or <prefix>;<exec_prefix>).
               The default module search path uses <prefix>/lib.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.

 

 

python中几个需要注意的地方:

python符号_表示最后一个表达式的值。

>> 'hello'

hello

>>_

hello

 

 

 

抱歉!评论已关闭.