Python基础笔记

本文深入讲解Python编程的基础特性,包括动态类型、大小写敏感、变量赋值、流程控制(如if...else、while、for)、常见数据类型如列表、元组、字典的使用及操作。同时,介绍了如何使用Python标准库进行网络请求、文件操作等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#Python特性,强类型(即强制要求变量类型),dynamic,capital sensitive,隐士类型(不需要声明)and objective.

#compile with python3

  1.  common libs
# -*- coding: utf-8 -*-
import os
import sys
import urllib
import json
import re
import getopt
import socket
import time
import urllib2
import urllib
import cookielib
import json
import httplib

2. #index with tabs

#inverse indentations mean end of block of codes.

3.  #interpretation

#This is a comment with # for single line

'''

Single quotes for multi-line comments

Single quotes for multi-line comments

Single quotes for multi-line comments

'''

"""

Double quotes for multi-line comments

Double quotes for multi-line comments

Double quotes for multi-line comments

"""

4.  #set variables with = or -= or +=

>>> myint=2 
>>> myint+=3
>>> myint
5

>>> mystring="Today is"
>>> mystring+=" Sunny."
>>> print(mystring)
Today is Sunny.

5. process control 

(1) if ……else 

if ACTION=="online":

    weight=100

elif ACTION=="offline":

    weight=0

elif ACTION=="get":

    http_method="GET"

else:

    usage()

(2) while

 while 1:
        try:
            request=urllib2.Request(url,headers=headers)
            response=urllib2.urlopen(request,timeout=1)
        except urllib2.URLError, err:                
            print("Failed to GET "+url)    
        else:
            str1=response.read().decode('utf-8')
            str=json.loads(str1)
            code=str["code"]
            if code == 0:
                break
            time.sleep(3)
            i=i+1
            if i >= max_retry:
                print("soa-console API Operate Failed. Check if http://xxx.hostname.com available!")
                exit(1)

(3) for

for key,value in options:
	if key in ("-h","--help"):
		usage()
	if key in ("-t","-run"):
		RUN=True
	if  key in ("-n","--name"):
		if value:
			VALUE=value
	if  key in ("-a","--action"):
		ACTION=value
	if key in ("-A","--appname"):
		APPLICATION=value

6、数据类型

(1)list

>>> list = []  #空列表
>>> list.append('Google')  # 使用append() 添加元素
>>> list.append('Honkong')
>>> print list
['Google', 'Honkong']
>>> print list[0]
Google
>>> del list[0]
>>> print list
['Honkong']

(2)tuple

>>> tup1=() #空元组
>>> tup2=('a','b','c','d')
>>> tup3=('A','B','C','a','b','c')

>>> dir(tuple) #查看元组支持的方法
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

>>> tup2.count('a') #元素a出现的次数

>>> tup2.index('b') #元素b第一次出现的位置
1

>>> tup_sum=tup2+tup3 #元组合并
>>> print tup_sum
('a', 'b', 'c', 'd', 'A', 'B', 'C', 'a', 'b', 'c')

>>> tup_multi=tup3*2 #保留元组tup3不变情况下,复制2次,生成新元组tup_multi
>>> print tup_multi
('A', 'B', 'C', 'a', 'b', 'c', 'A', 'B', 'C', 'a', 'b', 'c')

#元组切片操作
>>> print tup_multi[:] #取所有元组
('A', 'B', 'C', 'a', 'b', 'c', 'A', 'B', 'C', 'a', 'b', 'c')
>>>
>>> print tup_multi[2:] # 从2至末尾元素
('C', 'a', 'b', 'c', 'A', 'B', 'C', 'a', 'b', 'c')
>>> print tup_multi[2:5] #从2至5的元素
('C', 'a', 'b')
>>> print tup_multi[2:7:2] #语法:T[start [, stop[, step]]] ,取从2开始至7结束,每隔1个位置的元素
('C', 'b', 'A')

列表和元组的区别:

列表使用[],用于在不确定元素个数情况;元组使用(),元素不能修改。

(3)dictionaries(hash tables)

字典由多个<key,value>对组成,key是索引字段(如果重复,后者会覆盖前者)。 例如:

dict = {key1 : value1, key2 : value2 }

>>> dict = {'Name': 'kk','Age':5,'gender':'Male'}
>>> print(dict['Name'])
kk

修改value:

>>> dict['gender']='Female'
>>> print(dict['gender'])
Female

删除<key,value>:
 

>>> del dict['gender']
>>> print(dict['gender'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'gender'

删除后找不到对应的key,所以报错了。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值