ITPub博客

首页 > 应用开发 > IT综合 > Python 编程练习

Python 编程练习

原创 IT综合 作者:Michael_DD 时间:2015-07-20 10:08:33 0 删除 编辑
Python 编程练习



作一下简单学习,主要分享一下Python的学习课本,非常不错。


输出:print 'hello'
输入:input()
函数:
def sayHello():
    print 'hello'


列表:list
分割:split('.')
连接:join(list)


字符串:word
遍历
索引访问
切片
连接字符




常用的逻辑运算符包括:
>:大于
<:小于
>=:大于等于
<=:小于等于
==:等于。比较两个值是否相等。之所以用两个等号,是为了和变量赋值区分开来。
!=:不等与
not:逻辑“非”。如果x 为True,则not x 为False
and:逻辑“与”。如果x 为True,且y 为True,则x and y 为True
or:逻辑“或”。如果x、y 中至少有一个为True,则x or y 为True




for 嵌套
#python
from  random import randint


for i in range(0, 5):
       for j in range(0, i+1):
               print '*',
       print




if 嵌套:
if 条件1:
    if 条件2:
        语句1
    else:
        语句2
else:
     if 条件2:
         语句3
     else:
         语句4




文件:
打开文件:file('filename')
读文件:
f=file('data.txt')
data=f.read()
print data
f.close()


读取一行: readline()
按行读到list中:


写文件:
f = file('output.txt', 'w')
f.write('a string you want to write')


编程实例:
1.
#python
def ifEqual (num1, num2):
    if num1<num2:
         print "%d is too small"%num1
         return False;


    elif num1 > num2:
         print "%d is too big"%num1
         return False;


    else:
         print "%d is right"%num1
         return True


from random import randint
num = randint(0, 100)
print "Guess what i think?"
bingo = False


while bingo == False:
    answer = input()
    bingo = ifEqual(answer, num)


2.
#python
from random import choice


score_you = 0
score_com = 0
direction = ['left', 'center', 'right']


for i in range(5):
     print '====Round %d -You Kick!===='%(i+1)
     print 'Choose one side to shoot:'
     print 'left. center, right'
     you = raw_input()
     print 'You kicked' +you
     com = choice(direction)
     print 'Computer saved' + com
     if you != com:
            print 'Goal!'
            score_you += 1
     else:
            print 'Oops...'
     print 'Score:%d(you) - %d(com)\n' % (score_you, score_com)


     print '==== Round %d - You Save ! ====' %(i+1) 
     print 'Choose one side to save:'
     print 'left, center, right'
     you = raw_input()
     print 'Computer kicked ' + com
     if you == com:
        print 'Saved!'
     else:
        print 'Oops...'
        score_com += 1
     print 'Score:%d(you) - %d(com)\n' % (score_you, score_com)

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29500582/viewspace-1741425/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2014-02-22

  • 博文量
    326
  • 访问量
    2671972