1.从键盘输入两个数,并计算A的B次幂:
number1=raw_input(‘input number1:‘)
number2=raw_input(‘input number2:‘)
print ‘number1 ** number2 is:%d‘ %(int(number1) ** int(number2))
2.格式说明符%d,%s,%f
i=int (raw_input("请输入当月利润(万元):") )
if (i <= 10):
reward= i* 0.1
elif (i>10 and i<=20):
reward=10* 0.1+(i - 10) * (7.5 *0.01)
elif (i>20 and i<=40):
reward=10* 0.1 +(20-10)*7.5 *0.01+(i - 20) * (5 *0.01)
else:
reward=10* 0.1+10*7.5*0.01+20*5*0.01+(i - 40) *( 1 *0.01)
print "应放奖金:%.3f" %(reward)
3.重定向到标准输出:
import sys
print >> sys.stderr, "In fact,I‘m a Geek"
4.让python支持中文
#coding:utf-8
5.用while循环遍历字符串:
#coding:utf-8
str=raw_input("input a String :")
a=0
print ‘while result:‘
while a<len(str):
print str[a],
a+=1 #注意缩进
6.for循环遍历字符串:
str=raw_input("input a String :")
print ‘\nfor result:‘
for c in str:
print c,
print ‘\nOK‘
7.for循环打印0-99内的数字:
for i in range(0,100):
print i,
range(1,5,2)表示从1到5(不包含5),间隔2.
8.古典的兔子问题
def rabbit(n):
if n==1 or n==2 :
return 1
else :
return rabbit(n-1)+rabbit(n-2)
print "第一年有%d对兔子" %rabbit(1)
print "第二年有%d对兔子" %rabbit(2)
print "第六年有%d对兔子" %rabbit(6)
9.打开文件,读取每一行的数据
filename=raw_input(‘Enter file name:‘)
fobj=open(filename,‘r‘)
for eachLine in fobj:
print eachLine,
fobj.close()
10.生成随机数
import random #这个是注释,引入模块
rnd = random.randint(1,500)#生成1-500之间的随机数
11.字符串操作
#encoding=utf-8
a="123456"
print a[::-1], #翻转序列
print a[::2], # 隔一个取一个的操作
print a[::-2]
12.读文件
f = open("c:\\1.txt","r")
lines = f.readlines()#读取全部内容
for line in lines
print line
13.写文件
f = open("c:\\1.txt","r+")#可读可写模式
f.write("123")#写入字符串