Python学习(一):入门

 因为具有Java编程经验,所以Python上手相对比较容易。通过几个小示例程序来熟悉Python编程,所有程序均在Python3上完成。

1.输入并打印输出

# coding=utf-8 

str=input("Input string:")
print("您输入的字符串为,%s" % str)
  知识点:

  • input("某字符串")函数:显示"某字符串",并等待用户输入http://write.blog.csdn.net/postedit
  • print()函数:打印
  • 中文使用:coding=utf-8

2.字符串和数字连接http://write.blog.csdn.net/postedit

a=2
b="test"
c=str(a)+b #运用str()内置字符串转换
d="1111"
e=a+int(d) #运用<span style="color:#8000;">int</span>()内置<span style="color:#8000;">整型</span>转换
print ("c is %s,e is %i" % (c,e))
  知识点:

  • 内置函数转换:str(),int()等
  • 单行注释使用#
  • 多个输出打印方式

3.列表

#this is my shopping  List
shoplist=['apple','mango','carrot','banana']
print('I have',len(shoplist),'items to purchase.')
print('These items are:',end=' ')
for item in shoplist:
    print(item,end=' ')
print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now',shoplist)
print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list is',shoplist)
print('The first item I will buy is',shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I bought the',olditem)
print('My shopping list is now',shoplist)
知识点:

        * 列表长度是可变的,支持添加、删除和搜索

        * 可以用索引方式访问列表元素,返回子列表

        * for循环语句的使用

4.字典

ab = {'Swaroop':'swaroop@swaroopch.com',
      'Larry':'larry@wall.org',
      'Matsumoto':'matz@ruy-lang.org',
      'Spammer':'spammer@hotmail.com'
      }
print("Swaroop's address is ",ab['Swaroop'])
#删除一个键值对
del ab['Spammer']
print('\nThere are {0} contacts in the address-book\n'.format(len(ab)))
for name,address in ab.items():
    print('Contact {0} at {1}'.format(name, address))
#添加 一个键值对
ab['Guido'] = 'guido@python.org'
if 'Guido' in ab: # or ab.has_key('Guido')
    print("\nGuido's address is ",ab['Guido'])
知识点:

       *  字典可以理解成Java中的Map,元素以键值对的形式存在

       * 字典同样支持添加、删除和搜索

5.元组 和 序列

#tuple元组
zoo = ('python','elephant','penguin')
print('Number of aninals in the zoo is ',len(zoo))
new_zoo = ('monkey','camel',zoo)
print('Number of cages in the new zoo is ',len(new_zoo))
print('All animals in new zoo are',new_zoo)
print('Aninals brought from old zoo are',new_zoo[2])
print('Last animal brought from old zoo is',new_zoo[2][2])
print('Number of animals in the new zoo is',len(new_zoo)-1+len(new_zoo[2]))


# 序列
shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'swaroop'
# Indexing or 'Subscription' operation
print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])
print('Character 0 is', name[0])
# Slicing on a list
print('Item 1 to 3 is', shoplist[1:3])
print('Item 2 to end is', shoplist[2:])
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:])
# Slicing on a string
print('characters 1 to 3 is', name[1:3])
print('characters 2 to end is', name[2:])
print('characters 1 to -1 is', name[1:-1])
print('characters start to end is', name[:])

知识点:

      * 元组采用圆括号()包含元素,序列采用方括号[ ]包含元素

      * 元组和序列中的元素支持索引查找

6. 条件语句

#打印成绩
score =input('请输入成绩:')
score = int(score)
print(type(score))
if 90<=score<=100:
    print('A')
elif 70<=score<=79:
    print('B')
elif 60<=score<=69:
    print('C')
elif 0<=score<=59:
    print('D')
else:
    print('Invalid score')

知识点:

       * Python用缩进控制程序

       * Python不等式的写法,例如 2< x < 5 等价于 x > 2 && x < 5 或  x > 2 and x < 5

7. 函数

def sum(a,b):
    return a+b

func = sum
r = func(3,4)
print (r)  # 7

# 提供默认值
def add(a,b=2):
    return a+b
r=add(1) 
print (r)  # 3
r=add(1,5) 
print (r) # 6
知识点:

       * 函数定义,以及形参有无默认值

8. 异常处理

s = input('Input your age:')
if s=="":
    raise Exception('Input must no be empty')
try:
    i = int(s)
except Exception as err:
        print(err)
finally:
    print('Finish!')
知识点:

       * 捕获异常,并将异常打印输出

       * 若无异常,执行finally语句

9. 文件处理:写和读

spath = "D:/b.txt"
f = open(spath,'w') #open file for writing.Create this file doesn't exit
f.write("First line 1.\n")
f.writelines("First line2.\n")
f.writelines(['a','b','c'])
f.close()
f = open(spath,'r') #open file for reading
for line in f:
    print('每行数据是:%s'%line)
f.close()
知识点:

      *  open参数:w表示写,r表示读,a表示追加

      *  write的参数是字符串,即直接写入文件的内容;writelines的参数是序列,可以迭代写入文件

      *  打开文件完成任务后必须关闭

10.类、对象、属性和方法

class people:
    def __init__(self,name,age,sex):
        self.Name = name
        self.Age = age
        self.Sex = sex
    def speak(self):
        print("my name "+self.Name+" my age "+str(self.Age)+" my sex "+self.Sex)
lucy = people('lucy',23,'f') #创建Lucy实例,并初始化
print(lucy.Age)
lucy.speak()


class peo:
    def __init__(self,name,age,sex):
        self.Name = name
        self.Age = age
        self.Sex = sex
    def speak(self):
        print ("my name" + self.Name)
    def __str__(self):
        msg='my name is: ' +self.Name+ ","+ "my age is: " + self.Age +','+ "my sex is:" +self.Sex
        # msg='my name is: ' +self.Name+ ","+ "my age is: " + str(self.Age) +','+ "my sex is:" +self.Sex
        return msg
jack=peo('jack','23','man')
print(jack)  # my name is: jack ,my age is: 23,my sex is:man
知识点:

    *  people是定义的一个类,speak()是定义的方法,Lucy是people类的一个实例,Lucy可以调用people类下的方法

    * _init_()方法是创建类时创建的一个特定方法,只要创建这个类的实例就会运行这个方法

    * _str_()方法是打印显示具体内容,即直接print(实例对象)就可以打印出_str_()方法中的内容






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值