python学习笔记:python编程基础

1、python的包的种类

自带的包(built-in)package和外部(external)package

1.1 自带package,举例os、os.getwd().

 

3、环境变量中配置easy_install,pip

没有提供参数,需要设置参数

easy_install --help 证明环境变量配置正确

 

4、使用easy_install,pip安装package举例

import os
import requests
print(os.getcwd())

r=requests.get("http://www.baidu.com")
print(r.url)
print(r.encoding)
print(r.text)

 

pip 可以用pip安装额外的包

 

用pip尝试安装request

pip install requests

 

2.2 _Part2 字符串(String),变量(Variable)

Format字符串

age=3
name="Tom"
print("{0} waw {1} years old".format(name,age))

 

4、#注释

#单行注释

多行注释:三引号,或者双引号

 

5、缩进(identation)

缩进格式,使用缩进的时候会和程序的流程结合起来。

每行顶格写,否则会出错

 

第6课

 

例子:

a=3
b=4

c=5.66
d=8.0

e=complex(c,d)
f=complex(float(a),float(b))

print("a is type:",type(a))
print("c is type:",type(c))
print("e is type:",type(e))

 

print(a+b)
print(d/c)

print(b/a)
print(b//a) #约为整型

print(e)
print(e+f)

print(sys.float_info)

 

运行结果:

a is type: <class 'int'>

c is type: <class 'float'>

e is type: <class 'complex'>

7

1.4134275618374559

1.3333333333333333

1

(5.66+8j)

(8.66+12j)

sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

 

3.1 数据结构:列表(List)

 

创建List

#创建List
number_list=[1,3,5,7,9]
print("number_list:"+str(number_list))

运行结果:

number_list:[1, 3, 5, 7, 9]

 

字符串类型的 列表

string_list=["abc","bbc","python"]
print("string_list:"+str(string_list))

运行结果:
string_list:['abc', 'bbc', 'python']

 

数据类型和字符串类型混合的列表

mixed_list=["python","java",3,12]
print("mixed_list:"+str(mixed_list))

运行结果:

mixed_list:['python', 'java', 3, 12]

 

访问列表元素

#访问列表中的元素
second_num=number_list[1]
third_string=string_list[2]
fourth_mixed=mixed_list[3]

print("second_num:{0} \nthird_string:{1}\nfourth_mixed:{2}".format(second_num,third_string,fourth_mixed))

运行结果:

second_num:3

third_string:python

fourth_mixed:12

 

更新元素

number_list[1]=30

print("number_list after:"+str(number_list))

运行结果:

number_list after:[1, 30, 5, 7, 9]

 

#删除元素

del number_list[1]
print("number_list after:",number_list)

运行结果:

[1, 5, 7, 9]

 

#Python脚本语言
print(len([1,2,3])) #长度
print([1,2,3]+[4,5,6]) #组合
print(['Hello']*4) #重复
print(3 in [1,2,3]) #判断元素是否在列表中
运行结果:

3

[1, 2, 3, 4, 5, 6]

['Hello', 'Hello', 'Hello', 'Hello']

True


#列表的截取
abcd_list=['a','b','c','d']
print(abcd_list[1]) #从左边起,列表的第二位
print(abcd_list[-2]) #从右边起,列表的第二位
print(abcd_list[1:]) #从左边第二位开始截取到所有剩下的元素

运行结果:

b

c

['b', 'c', 'd']

 

3.2 数据结构:元组(Tuple)

元祖一旦创建之后不可更改

#创建
number_tuple=(1,3,5,7,9)
# print("number_tuple:"+str(number_tuple))

string_tuple=("abc","bbc","python")
# print("string_tuple:"+str(string_tuple))

mixed_tuple=("python","java",3,12)
# print("mixed_tuple:"+str(mixed_tuple))

#访问元组中的元素
second_num=number_tuple[1]
third_string=string_tuple[2]
fourth_mixed=mixed_tuple[3]

print("second_num:{0} \nthird_string:{1}\nfourth_mixed:{2}".format(second_num,third_string,fourth_mixed))

#更新元素,tuple不能被更改,所以程序会运行报错
# number_tuple[1]=30
# print("number_tuple after:"+str(number_tuple))

#删除元素,tuple不能被更改,所以程序会运行报错
# del number_tuple[1]
# print("number_tuple after:",number_tuple)

#Python脚本语言
print(len((1,2,3))) #长度
print((1,2,3)+(4,5,6)) #组合
print(('Hello')*4) #重复
print(3 in (1,2,3)) #判断元素是否在列表中

#元组的截取
abcd_tuple=('a','b','c','d')
print(abcd_tuple[1]) #从左边起,列表的第二位
print(abcd_tuple[-2]) #从右边起,列表的第二位
print(abcd_tuple[1:]) #从左边第二位开始截取

 

运行结果:

second_num:3

third_string:python

fourth_mixed:12

3

(1, 2, 3, 4, 5, 6)

HelloHelloHelloHello

True

b

c

('b', 'c', 'd')

 

tuple里面的元素不能更改,但是能更改tuple里面的list的元素

#创建只包含一个元素的tuple
a_tuple=(2,)

#创建tuple中的list
mixed_tuple=(1,2,['a','b'])

print("mixed_tuple:"+str(mixed_tuple))

#读取tuple,更改tuple

mixed_tuple[2][0]='c'
mixed_tuple[2][1]='d'

print("mixed_tuple after:"+str(mixed_tuple))

运行结果:

mixed_tuple:(1, 2, ['a', 'b'])

3.3 字典(Dictionary)

数据类型如下

#创建字典,同一个字典里可以出现多种不同的数据类型的元素
phone_book={'Tom':123,'Jerry':456,'Kim':789}
mixed_dict={'Tom':'boy',11:23.5}

#访问字典中的值
print("Tom has phone number:"+str(phone_book['Tom']))

#修改字典中的值
phone_book['Tom']=999
print("Tom has phone number:"+str(phone_book['Tom']))

#添加
phone_book['Heath']=888
print('The added book is:'+str(phone_book))

#删除字典中的元素
del phone_book['Tom']
print("The book after del is:"+str(phone_book))

#清空字典里的数据
phone_book.clear()
print("The book after clear is:"+str(phone_book))

#删掉整个字典
del phone_book
# print("The book after del all is:"+str(phone_book))

#特性
#一个字典里面不允许出现两个key相同的元素
rep_test={'Name':'aa',"age":5,"Name":'bb'}
print("rep_test:",rep_test)

#键是不可变的,可以用数字、字符串、或者元组充当键,但是不可能用列表
#list_dict={['Name']:'John','Age':13} #运行时会报错,因为不能用列表作为字典的键
list_dict={('Name'):'John','Age':13}
print("list_dict is:"+str(list_dict))

 

运行结果:

Tom has phone number:123

Tom has phone number:999

The added book is:{'Tom': 999, 'Jerry': 456, 'Kim': 789, 'Heath': 888}

The book after del is:{'Jerry': 456, 'Kim': 789, 'Heath': 888}

The book after clear is:{}

rep_test: {'Name': 'bb', 'age': 5}

list_dict is:{'Name': 'John', 'Age': 13}

 

 

3.4 函数(Function)Part1

#默认参数
def repeat_str(s,times=1):
    repeated_strs=s*times
    return repeated_strs

repeated_strings=repeat_str("happy Birthday! ")
print(repeated_strings)

repeat_strings_2=repeat_str(" Happy Birthday ! ",4)
print(repeat_strings_2)

运行结果:

happy Birthday!

 Happy Birthday !  Happy Birthday !  Happy Birthday !  Happy Birthday !

 

 

3.4 函数(Function)Part2

 

def func(a,b=4,c=8):
    print('a is ',a,'and b is',b,'and c is',c)
func(13,17)
func(125,c=24)
func(c=40,a=80)

def print_paras(fpara,*nums,**words):
   print("fpara:"+str(fpara))
   print("num:"+str(nums))
   print("words:"+str(words))

print_paras("hello",1,3,5,7,word="python",another_word="java")

 

运行结果:

a is  13 and b is 17 and c is 8

a is  125 and b is 4 and c is 24

a is  80 and b is 4 and c is 40

fpara:hello

num:(1, 3, 5, 7)

words:{'word': 'python', 'another_word': 'java'}

 

 

4.1 控制流1:if & for 语句

 

if 语句例子:

number=59
guess=int(input('Enter an integer:'))
print('guess is :'+str(guess))

if guess== number:
    print('Bingo! you guessed it right.')
    print('(but you do not win any prizes!)')
elif guess < number:
    print('No,the number is Higher than that')
else:
    print('No,the number is a lower than that')

print('Done')

 

for 语句例子:

for i in range(1,10):
    print(i)
else:
    print('the for loop is over')

 

for 例子2,遍历列表

a_list=[1,3,5,7,9]
for i in a_list:
    print(i)

 

for 例子3,遍历元组

a_tuple=(1,3,5,7,9)
for i in a_tuple:
    print(i)

 

For例子4

#遍历字典
a_dict={'Tom':'111','Jerry':'222','Cathy':'333'}
for el in a_dict:
    print(el,':',a_dict[el])

 

For例子5

#用key和值,对字典进行遍历
for key,elem in a_dict.items():
    print(key,":",elem)

 

 

 

4.2 控制流2:while& range 语句

import random

number=random.randint(0,1000)
print(number)
guess_flag=False
while guess_flag==False:
    print("==================================")
    guess=int(input('请输入一个整数(0-1000):\n'))
    if guess==number:
        guess_flag=True
        print("恭喜您猜对了,但是没有奖品,哈哈哈!!!")
    elif guess<number:
        print('错了,您输入的数字小于正确值。')
        print('正确值为:',number)
    elif guess>number:
         print('错了,您输入的数字大于正确值。')
         print('正确值为:',number)
    else:
         print("您输入的数字不正确")
    print("==================================\n")

print("Done!!!")

 

固定次数循环

 

import random

num_change=5
number=random.randint(0,1000)
print(number)

for i in range(1,num_change+1):
    print("==================================")
    guess=int(input('请输入一个整数(0-1000):\n'))
    if guess==number:
        print("恭喜您猜对了,但是没有奖品,哈哈哈!!!")
        break
    elif guess<number:
        print('错了,您输入的数字小于正确值。')
        print("您还有"+str(num_change-i)+"次机会")
    elif guess>number:
         print('错了,您输入的数字大于正确值。')
         print( "\n您还有" + str(num_change-i) + "次机会")
    else:
         print("您输入的数字不正确")
         print( + "\n您还有" + str(num_change-i) + "次机会")
    print("==================================\n")
print('正确值为:' + str(number) )

print("Done!!!")

 

4.3 Break、Continue、Pass

import random

 

number=random.randint(0,1000)

print(number)

guess_flag=False

while True:

    print("==================================")

    guess=int(input('请输入一个整数(0-1000):\n'))

    if guess==number:

        print("恭喜您猜对了,但是没有奖品,哈哈哈!!!")

        break

    elif guess<number:

        print('错了,您输入的数字小于正确值。')

        print('正确值为:',number)

        continue

    elif guess>number:

         print('错了,您输入的数字大于正确值。')

         print('正确值为:',number)

         continue

    else:

         print("您输入的数字不正确")

         continue

print("==================================\n")

print("Done!!!")

 

#continue和Pass的例子

a_list=[0,1,2]

print("使用continue:")
for i in a_list:
        if not i:
            continue
        print(i)

print("使用Pass:")
for i in a_list:
      if not i:
          pass
      print(i)

5.1 输入输出方式介绍(Output  /  Format)

#take input from user
str_1=input("Enter a string:")
str_2=input("Enter another string:")

#ouput the strings
print("str_1 is :"+str_1+",str_2 is"+str_2)
print("str_1 is {},str_2 is {}".format(str_1,str_2))

 

 

5.2 读写文件(FileIO)

1、读入文件

2、写入文件

some_sentences='''
I love leearing python
because python is fun
and also easy to use'''

#open for 'w'riting
f=open('sentence.txt','w')

#write text to file
f.write(some_sentences)
f.close()

#如果不是特殊mode,不用声明'r'模式
f=open('sentence.txt')
while True:
    line=f.readline()
    if len(line)==0:
        break
    print(line)
#close the file
f.close()

 

6.1 异常处理

try:
    f=open('sentence.txt')
    s=f.readline()
    i=int(s.strip())
except OSError as err:
    print("OS error:{0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")

 

 

7.2 面想对象编程(Object-Oriented)和装饰器(decorator)

class Student:
    def __init__(self,name,grade):
        self.name=name
        self.grade=grade

    def introduce(self):
        print("hi! I am "+self.name)
        print("my grade is {}".format(self.grade))

    def improve(self,amount):
        self.grade=self.grade+amount


jim=Student("jim",86)
jim.introduce()
jim.improve(10)
jim.introduce()

 

 

#装饰器

'''
def add_candles(cake_func):
    def insert_candles():
        return cake_func()+" and candles"
    return insert_candles

def make_cake():
    return "cake"
gift_func=add_candles(make_cake)

print(make_cake())
print(gift_func())
'''

'''
def add_candles(cake_func):
    def insert_candles():
        return cake_func()+" and candles"
    return insert_candles

def make_cake():
    return "cake"

make_cake=add_candles(make_cake)

print(make_cake())
'''

def add_candles(cake_func):
    def insert_candles():
        return cake_func()+" and candles"
    return insert_candles

@add_candles  #装饰器标识
def make_cake():
    return "cake"

print(make_cake())

 

 

 

8.1 图形界面(GUI)和猜数字游戏

 

import random
from tkinter import *

import tkinter.simpledialog as dl
import tkinter.messagebox as mb

#GUI
root=Tk()
w=Label(root,text="猜数字游戏")
w.pack()

number=random.randint(0,1000)
guess_flag=False
num_change=5
mb.showinfo("欢迎","欢迎来到猜数字游戏界面\n您只有"+str(num_change)+"次猜数字机会")
while True:
    if num_change==0:
        mb.showinfo("结束", "您的猜数字机会已经用完\n正确数字为"+str(number))
        break
    guess = dl.askinteger("数子", "请输入一个数字:")
    num_change=num_change-1
    if guess==number:
           output = '恭喜您猜对了\n但是没有奖品,哈哈哈!!!'
           mb.showinfo("Output:", output)
           break
    elif guess<number:
        output = '错了\n您输入的数字小于正确值。\n您还剩'+str(num_change)+"次猜数字机会"
        mb.showinfo("Output:", output)
        continue
    elif guess>number:
         output = '错了\n您输入的数字大于正确值。\n您还剩'+str(num_change)+"次猜数字机会"
         mb.showinfo("Output:", output)
         continue
    else:
        output = '错了\n您输入的数字格式不正确。\n您还剩'+str(num_change)+"次猜数字机会"
        mb.showinfo("Output:", output)
        continue

 

 

9 创建一个网页

# -*- Coding:utf-8 -*-

import web

 

urls=(

    '/','index'

)

 

app=web.application(urls,globals())

 

class index:

    def GET(self):

         greeting ='Hello World'

         return greeting

 

if __name__=="__main__":

    app.run()

猜你喜欢

转载自blog.csdn.net/jingyueshi2009/article/details/83717400