专业编程基础技术教程

网站首页 > 基础教程 正文

Python基础命令入门 python的基本命令

ccvgpt 2024-11-01 11:33:38 基础教程 10 ℃

Content

  1. 打印字符串

  2. 变量赋值

    Python基础命令入门 python的基本命令

  3. 运算符

  4. 流程控制

  5. 自定义函数

  6. 全局变量

  7. 接收输入数据

  8. 常用内置函数

  9. 导入常用模块

  10. 文件操作

1、打印字符串

print 'hello world!'

print "hello world!"

print "hello 'wor'ld!"

2、变量赋值

变量直接赋值,无需声明类型

a = 1

type(a) #a的类型是int

b = 3.1415

type(b) #b的类型是float

c = 'hello world!'

type(c) #c的类型是str

d = [1, 2, 3, 4, 5]

type(d) #d的类型是list

3、运算符

a = 2 + 3; print 'a =', a

b = 2 ** 3 ; print 'b =', b #**代表幂,2的3次方

c = float(a)/b; print 'c =', c #除法

d = a//b; print 'd =', d #取整除,返回商的整数部分

e = a%b; print 'e =', e #取模,返回余数

4、流程控制

4.1、条件执行

love = 0.5

if love == 1:

print 'I love you'

elif love > 0:

print 'Who are you'

else:

print 'I hate you'

4.2、for 循环

for i in range(3): #range(起始值,终止值,步长)

print i

4.3、while 循环

a = 1

while a < 6:

print a

a += 1

5、自定义函数

def sayhello(count):

for i in range(count):

print 'hello', i+1

sayhello(3)

6、全局变量

id = 1

def addprint():

global id

id += 1

print 'id =', id

addprint()

addprint()

7、接收输入数据

a = raw_input('please input a number: ')

if int(a) > 10:

print 'a =', a

else:

print 'a < 10'

8、常用内置函数

len():计算字符串、列表的长度

str():将对象转化为字符串

int():将对象转化为整型

float():将对象转化为浮点型

a.append(元素):添加元素到列表a最后

a.insert(位置,元素):在指定位置插入元素,其他元素往后排

a.remove(元素):从0开始索引,删除匹配到的第一个元素

a.index(元素,开始,结束):返回匹配到的第一个元素的索引

9、导入常用模块

import 模块名:使用模块提供的对象时需加上模块名

import time

time.sleep(n):休息n秒,可以是小数

time.time():返回一个浮点数,是8位小数,从1970-1-1,0:0:0到当前绝对时间的秒数

import random

random.random():random float x,0.0 <= x <=1.0

random.uniform(1, 10):random float x,1.0 <= x <= 10

random.randint(1, 10):random integer x,1 <= x <=10

random.randrange(0, 101, 2):even integer x,0 <= x <= 100

random.choice('abcdefg'):choose a random element

a = [1,2,3]; random.shuffle(a):random shuffle a

random.sample([1,2,3,4,5], 3):random choose 3 elements

10、文件操作

file = open(文件名,mode):返回一个文件对象

mode:‘r’读;‘w’写;‘r+’读写

file.read(size):读取文件size个字节,返回一个string对象。如果小于size,则读取整个文件

file.readline():读取一行,返回一个string对象

file.readlines():读取所有行,返回一个list

file.write(buffer):写buffer的内容到文件

file.close():关闭文件

例子:读取‘num.txt’的两列数据,分别保存到a,b

num.txt第一列是[1.1, 1.2, 1.3];第二列是[4, 5, 6]

filename = 'num.txt'

a = [float(f.split()[0]) for f in open(filename)]

b = [int(f.split()[1]) for f in open(filename)]

print 'a =', a

print 'b =', b

Tags:

最近发表
标签列表