Python入门简短实例摘录

Python入门简短实例摘录


这十个小题目是任何一门语言最基本的入门,为方便后续浏览而摘录下来。大部分实例摘自网站:http://askpython.com,英文原版短文。有想读英文原版的朋友可以浏览此站点。


1. Hello world:

#!/usr/bin/env python3

print('hello world')

2. 变量【可以不用声明,自动识别变量类型】

#!/usr/bin/python
 
x = 3              # a whole number                   
f = 3.1415926      # a floating point number              
name = "Python"    # a string
 
print(x)
print(f)
print(name)

combination = name + " " + name
print(combination)

sum = f + f
print(sum)

3. 键盘输入【Python2x可以接收字符串或者数字,但是Python3x只接收数字时需要强制转换】

#!/usr/bin/env python3

name = input('What is your name? ')
print('Hello ' + name)

num = input('Give me a number? ')
print('You said: ' + str(num))

4. 条件语句

!/usr/bin/env python3

age = int(input("Age of your cat? "))
if age < 5:
    print("Your cat is young.")
elif age > 10:
    print("Your cat is old.")
else:
    print("Your cat is adult.")

5. for循环

#!/usr/bin/env python3

city = ['Tokyo','New York','Toronto','Hong Kong']
for x in city:
    print(x)

#!/usr/bin/env python3

num = [1,2,3,4,5,6,7,8,9]
for x in num:
    y = x * x
    print(y)

5.  while循环

#!/usr/bin/python
 
x = 3                              
while x < 10:
    print(x)
    x = x + 1

#!/usr/bin/python

while True:
    if condition:
        break

6. 函数

#!/usr/bin/env python3

def f(x,y):
    print(x*y)

f(3,4)

#!/usr/bin/env python3

def sum(list):
    sum = 0
    for l in list:
        sum = sum + l
    return sum

mylist = [1,2,3,4,5]
print(sum(mylist))

7. 元组 【下标起始0,-1指示最后一个元素】

list = [1,3,4,6,4,7,8,2,3]

print(sum(list))
print(min(list))
print(max(list))
print(list[0])
print(list[-1])

8. 字典【无序存储结构】

注:使用Python3x运行如下脚本,着重注意print必须带有括号,如print(words["BMP"]),这是与Python2x中print的区别。

#!/usr/bin/python

words = {}
words["BMP"] = "Bitmap"
words["BTW"] = "By The Way"
words["BRB"] = "Be Right Back"

print words["BMP"]
print words["BRB"]


9.  读取文件:

按行读取:

#!/usr/bin/env python

filename = "file.py"

with open(filename) as f:
    content = f.readlines()

print(content)
读取文件内容到一个字符串:

#!/usr/bin/env python

filename = "file.py"

infile = open(filename, 'r')
data = infile.read()
infile.close()

print(data)

10. 写文件:

创建一个文件:

#!/usr/bin/env python

# create and open file
f = open("test.txt","w")

# write data to file 
f.write("Hello World, \n")
f.write("This data will be written to the file.")

# close file
f.close()
添加内容到文件末尾:

#!/usr/bin/env python

# create and open file
f = open("test.txt","a")

# write data to file 
f.write("Don't delete existing data \n")
f.write("Add this to the existing file.")

# close file
f.close(





你可能感兴趣的:(入门,python)