Python基本语法1

本文档提供了一份详细的 Python 2.7 版本的基础教程,包括注释、类型转换、输入输出、数学计算等核心概念,以及字符串操作、格式化输出、原始字符串的使用方法。此外还介绍了列表、字典等数据结构的操作,以及文件处理、流程控制语句的基本用法。

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

2012-3-7#使用版本:Python 2.7.2当行注释 # 多行注释 ''' 或者 """ (三个单引号或者双引号)当行多断代码隔离 ; 下段代码的开始 : 代码的连接 print "too long"\ " words"\ 相当于 print too long words1. 类型转换 int(string) float(String)chr(ASCII值到字符) ord(ASCII字符转换成值)oct(String) 八进制hex 16进制long 长整型String.atoi(num) #字符串->int2.基本输入name = raw_input('please input your name')3.使用中文第一行: #-*-coding:utf-8-*-String.decode('utf-8')String.encode('gbk')4.数学计算 import math math.sin(60) math.pimath.sqrt(9) #3math.log10(100) #2math.pow(2,8) #2565.运算符+ - * / 加减乘除** 乘方| ^ & 按位或 ,异或, 与 << >> 左移运算,右移运算6.转义符\n 换行\t 制表\r 回车\\ \' \" # \ ,' , "7.字符串string.capitalize()string.count() #获得某一子字符串的数目isidgit ,isalpha ,islower,istitle(),join,lower ,split ,len(string)String[0] #字符串第一个字符String[-1] #字符串最后一个字符String[-2] #字符串倒数第二个字符String[0:-2] #从第一个字符,到倒数第二个字符,但是不包含倒数第二个字符8.格式化输出%c %d %o %s %x %X(十六进制整数,其中字母大写)str = 'so %s day'print str % 'beautiful'9.原始字符串(Raw String)以R或r 开头的字符串,没有转义字符import os path =r'c:\test' #这里\t就不是制表符的意思了dirs =os.listdir(path)print dirs10.列表 listlist=[]list.append(1)list.count(2) #2在list里出现的次数list.extend([2,3,4,5])list.inedx(5)list.insert(2,6)list.pop(2) #弹出index是2的数list.remove(5)#移除5个数字list.reverse()list.sort()list[1:4] #返回下标1到3的数字(不包含4)list[1:-1] #返回第二个到最后一个的数,但不包含最后一个11.字典 Dictionary键值对 key:valuedic={'apple':2 ,'orange':1}dic.clear()dic.copy()dic.get(key)dic.has_key(key)dic.items()dic.keys()dic.values()dic.pop(k) #删除kdic.update()12.文件Fileopen(filename,mode,bufsize) #mode: r(读方式),w(写方式) ,b(二进制)file.read() #读入文件到字符串file.readline() #读取一行file.readlines()#读取所有行file.write() #字符串写到文件file.writelines()#列表写到文件#open file as write modefile = open('c:/Python27/test/hello.py','w')file.write('print "write python"\n')#generate list and write into filelist=[]for i in range(10)s=str(i)+'\n'list.append(s)file.writelines(list)file.close()#print out the file contentfile = open('c:/Python27/test/hello.py','r')s = file.read()print s 12.if 语句 if :else if:else :13.for 语句for in :if : breakif : continueelse: print14.rangerange(start,stop,step) #start,step可选参数for i in range(1,5+1,1) # 打印 1-5 ,步长为1print i15.while while:do loop
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值