Python 语法小例子

1、print('hello world')

2、python并没有long型,int型可以是任意大小的整数

3、string类型,单引号和双引号没区别。三引号表示多行:

'''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''
4、python并没有单独的char类型。

5、关于fromat()函数

一般这么写:

age = 20
name = 'Swaroop'

print('{0} was {1} years old when he wrote this book'.format(name, age))
print('Why is {0} playing with that python?'.format(name))
或者:

print('{} was {} years old when he wrote this book'.format(name, age))
print('Why is {} playing with that python?'.format(name))
一般不这么写:

name + ' is ' + str(age) + ' years old'
其他用法:

# decimal (.) precision of 3 for float '0.33333'
print('{0:.5f}'.format(1.0/3))
# fill with underscores (_) with the text centered
# (^) to 11 width '___hello___'
print('{0:_^11}'.format('hello'))
6、print()是自动换行的,若不自动换行,需要显示的如下使用print()函数:

print('a', end='')
print('b', end='')
注意!python 3版本以下不支持该print end用法,需要直接在首行添加:

from __future__ import print_function
7、识别转义序列用\识别

'What\'s your name?'

8、关于physical line和logical line. physical line是编辑器的一行,  logical line是python编译器所识别的一行。

如果在一行里写多个语句,用;隔开,但是一般在python代码中最好不要出现分号,所以我们不建议这么写代码:

i = 5;
print(i);
或:

i = 5; print(i);
i = 5; print(i)

最好,一个语句一行:

i = 5
print(i)

9、python中,从不用{}来对代码进行分组,只用缩进!python中标准的缩进是4个空格键

10、if语句:

number = 23
guess = int(input('Enter an integer : '))

if guess == number:
    # New block starts here
    print('Congratulations, you guessed it.')
    print('(but you do not win any prizes!)')
    # New block ends here
elif guess < number:
    # Another block
    print('No, it is a little higher than that')
    # You can do whatever you want in a block ...
else:
    print('No, it is a little lower than that')
    # you must have guessed > number to reach here

print('Done')
# This last statement is always executed,
# after the if statement is executed.
11、while语句(不同于其他编程语言,python的while语句有else子句)

number = 23
running = True

while running:
    guess = int(input('Enter an integer : '))

    if guess == number:
        print('Congratulations, you guessed it.')
        # this causes the while loop to stop
        running = False
    elif guess < number:
        print('No, it is a little higher than that.')
    else:
        print('No, it is a little lower than that.')
else:
    print('The while loop is over.')
    # Do anything else you want to do here

print('Done')
12、for语句(类似于C++的   for(int i = 0; i < 5; i++)   )

for i in range(1, 5):
    print(i)
else:
    print('The for loop is over')
13、break语句和continue语句

break语句:是跳出整个for或者while循环

continue语句:是告诉程序跳出当前循环,直接执行下一循环

while True:
    s = input('Enter something : ')
    if s == 'quit':
        break
    if len(s) < 3:
        print('Too small')
        continue
    print('Input is of sufficient length')
    # Do other kinds of processing here...
14、局部变量

x = 50

def func(x):
    print('x is', x)
    x = 2
    print('Changed local x to', x)


func(x)
print('x is still', x)  #x的值依然是50
15、全局变量

x = 50

def func():
    global x  #是全局变量

    print('x is', x)
    x = 2
    print('Changed global x to', x)


func()
print('Value of x is', x)  #x的值变为2
16、不定参数的函数:*param是指相应的参数为tuple; **param是指相应的参数为dictionary

def total(a=5, *numbers, **phonebook):
    print('a', a)

    #iterate through all the items in tuple
    for single_item in numbers:
        print('single_item', single_item)

    #iterate through all the items in dictionary    
    for first_part, second_part in phonebook.items():
        print(first_part,second_part)

print(total(10,1,2,3,Jack=1123,John=2231,Inge=1560))
输出:

a 10
single_item 1
single_item 2
single_item 3
Inge 1560
John 2231
Jack 1123
None
17、定位当前工作路径:

import os
print(os.getcwd())
18、关于import modules

一般不建议from ... import(使用的时候可以省去moduel名,所以可能会造成冲突),使用import ...更妥(不可省)

每个python module都有一个__name__属性,可以通过该属性判断,该moduel是自己在运行还是正在被import

if __name__ == '__main__':
    print('This program is being run by itself')
else:
    print('I am being imported from another module')
19、创建自己的moduel

可以这么说,每个python程序都可以看成是一个module。e.g.

mymodule.py  (该.py文件 为module)

def say_hi():
    print('Hi, this is mymodule speaking.')

__version__ = '0.1'
通过import使用:

import mymodule

mymodule.say_hi()
print('Version', mymodule.__version__)
通过from...import..使用:

from mymodule import say_hi, __version__

say_hi()
print('Version', __version__)
20、dir(module)是该module的所有属性查找函数

21、python数据结构有:List, Tuple, Dictionary, Set, Sequence, Reference. 具体用法将单独做笔记

22、类class,首先看一个简单的class的例子,了解python中的类怎么使用

class Person:
    def __init__(self, name):
        self.name = name

    def say_hi(self):
        print('Hello, my name is', self.name)

p = Person('Swaroop')
p.say_hi()
可以和C++这么类比: self~this ,  __init__~构造函数。但是并不显示的调用__inti__函数,而是通过类名来实例化,如:p = Person('Swaron')

下面详细看重点:class variable, object variable, classmethod. 还是先看例子:

class Robot:
    """Represents a robot, with a name."""

    # A class variable, counting the number of robots
    population = 0   #类变量,通过Robot.population来访问,并不是通过self.population来访问

    def __init__(self, name):
        """Initializes the data."""
        self.name = name # name是object 变量,通过self.name访问
        print("(Initializing {})".format(self.name))

        # When this person is created, the robot
        # adds to the population
        Robot.population += 1

    def die(self):
        """I am dying."""
        print("{} is being destroyed!".format(self.name))

        Robot.population -= 1

        if Robot.population == 0:
            print("{} was the last one.".format(self.name))
        else:
            print("There are still {:d} robots working.".format(
                Robot.population))

    def say_hi(self):
        """Greeting by the robot.

        Yeah, they can do that."""
        print("Greetings, my masters call me {}.".format(self.name))

    @classmethod
    def how_many(cls):  #类似于C++ 的静态函数,类的所有实例对象共享
        """Prints the current population."""
        print("We have {:d} robots.".format(cls.population))
需要注意与C++类不同的是,python类(包括类成员和类方法)都是public的,并且所有的类方法都是virtual (继承的时候可以重载……)

既然提到了类的继承,看下面一个继承的例子:

class SchoolMember:
    '''Represents any school member.'''
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print('(Initialized SchoolMember: {})'.format(self.name))

    def tell(self):
        '''Tell my details.'''
        print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")


class Teacher(SchoolMember):
    '''Represents a teacher.'''
    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age)
        self.salary = salary
        print('(Initialized Teacher: {})'.format(self.name))

    def tell(self):
        SchoolMember.tell(self)
        print('Salary: "{:d}"'.format(self.salary))


class Student(SchoolMember):
    '''Represents a student.'''
    def __init__(self, name, age, marks):
        SchoolMember.__init__(self, name, age)
        self.marks = marks
        print('(Initialized Student: {})'.format(self.name))

    def tell(self):
        SchoolMember.tell(self)
        print('Marks: "{:d}"'.format(self.marks))

t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 25, 75)

# prints a blank line
print()

members = [t, s]
for member in members:
    # Works for both Teachers and Students
    member.tell()
注意和C++类的继承的区别:python类的继承并不默认继承基类的所有,需要显示的调用基类的__init__等之类的函数。

这里的tell()函数类似于接口,但又不全是接口,可以在派生类中复写。然后统一访问

23、关于输入输出

输入:

something = input("Enter text: ")
输出:直接就是print函数

关于文件的读写:(读写的mode))

# Open for 'w'riting
f = open('poem.txt', 'w')
# Write text to file
f.write(poem)
# Close the file
f.close()
还有一种pickle方法来实现对象的持续存储

import pickle

# The name of the file where we will store the object
shoplistfile = 'shoplist.data'
# The list of things to buy
shoplist = ['apple', 'mango', 'carrot']

# Write to the file
f = open(shoplistfile, 'wb')
# Dump the object to a file
pickle.dump(shoplist, f)
f.close()

# Destroy the shoplist variable
del shoplist

# Read back from the storage
f = open(shoplistfile, 'rb')
# Load the object from the file
storedlist = pickle.load(f)
print(storedlist)
先open待存文件,然后调用pickle模块中的dump方法,即完成一次存储。

以utf-8格式读写:

# encoding=utf-8
import io

f = io.open("abc.txt", "wt", encoding="utf-8")
f.write(u"Imagine non-English language here")
f.close()

text = io.open("abc.txt", encoding="utf-8").read()
print(text)
其中,python是通过字母'u'来读取non-English语言。

24、python关于异常的处理

首先,try...except...else...:

try:
    text = input('Enter something --> ')
except EOFError:
    print('Why did you do an EOF on me?')
except KeyboardInterrupt:
    print('You cancelled the operation.')
else: #执行到这,代表没遇到异常
    print('You entered {}'.format(text))
还有,try...finally
import sys
import time

f = None
try:
    f = open("poem.txt")
    # Our usual file-reading idiom
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print(line, end='')
        sys.stdout.flush()
        print("Press ctrl+c now")
        # To make sure it runs for a while
        time.sleep(2)
except IOError:
    print("Could not find file poem.txt")
except KeyboardInterrupt:
    print("!! You cancelled the reading from the file.")
finally: #肯定被执行
    if f:
        f.close()
    print("(Cleaning up: Closed the file)")
最后,with语句:

with open("poem.txt") as f:
    for line in f:
        print(line, end='')
但是,虽然语法简单,但是并没有捕捉到error。




































猜你喜欢

转载自blog.csdn.net/liu1152239/article/details/75244477
今日推荐