码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础

时间:2018-09-16 18:40:46      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:解释   编码   运算   put   访问   oat   实现   let   cal   

1、Python语言特点

优点:
①.丰富的库
②.简单、开源
③.支持面向对象编程
④.解释性语言,无需编译
⑤.高层语言,不用考虑内存问题
⑥.可移植性好,不依赖于操作系统


缺点:
①.运行效率较低
②.构架选择过多
③.中文资源较少

2、注释

单行注释:# hello python
多行注释:"""hello python"""

3、中文编码问题

中文编码解决方法:
①  #coding=utf-8
②  #-*- coding:utf-8 -*-

4、多行语句

Python 通常是一行写完一条语句,但如果语句很长,可以使用反斜杠()来实现多行语句,示例:

total = ‘item_one‘ +             ‘item_two‘ +            ‘item_three‘
print(total) 

执行结果:
item_oneitem_twoitem_three

在 [], {}, 或 () 中的多行语句,不需要使用反斜杠(),示例:

total = [‘item_one‘, ‘item_two‘, ‘item_three‘,
            ‘item_four‘, ‘item_five‘]
print(total)

执行结果:
[‘item_one‘, ‘item_two‘, ‘item_three‘, ‘item_four‘, ‘item_five‘]

5、标识符

标识符: 由字母、数字、下划线组成,但不能以数字开头(标识符是区分大小写的

  特殊标识符:

  • 以下划线开头的标识符是有特殊意义的。以单下划线开头 _foo 的代表不能直接访问的类属性,需通过提供的接口进行访问,不能用 from xxx import * 而导入;
  • 以双下划线开头的__foo代表类的私有成员;以双下划线开头和结尾的__foo__代表 Python 里特殊方法专用的标识,如__init__()代表类的构造函数。

  Python保留字: 保留字即关键字,不能用作任何标识符名称。Python 的标准库提供了一个 keyword 模块:

>>> import keyword
>>> keyword.kwlist
[False, None, True, and, as, assert, break, class, continue, 
def, del, elif, else, except, finally, for, from, global, 
import, in, is, lambda, nonlocal, not, or, pass, raise, if,
return,try, while, with, yield]

6、format格式化函数

  • 格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

  • 基本语法是通过 {} 和 : 来代替以前的 % 

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
>>>‘hello world‘


>>> "{0} {1}".format("hello", "world")  # 设置指定位置
>>>‘hello world‘


>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
>>>‘world hello world‘


>>> print("网站名:{name}, 地址 {url}".format(name="百度", url="www.baidu.com")) #指定参数名
>>>‘网站名:百度, 地址 www.baidu.com‘


>>>site = {"name": "百度", "url": "www.baidu.com"}
>>>print("网站名:{name}, 地址 {url}".format(**site)) # 通过字典设置参数
>>>‘网站名:百度, 地址 www.baidu.com‘


>>>my_list = [‘百度‘, ‘www.baidu.com‘]
>>>print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的 通过列表索引设置参数
>>>‘网站名:百度, 地址 www.baidu.com‘

 
>>> print("{:.2f}".format(3.1415926)); #数字格式化
>>>3.14

7、输入和输出

输入:input()

#!/usr/bin/python3

str = input("请输入:");
print ("你输入的内容是: ", str)

 
>>>程序执行结果:
请输入:Hello Python!
你输入的内容是:  Hello Python! 

#-*- coding:utf-8 -*-
# 注意:
# input()返回的是字符串
# 必须通过int()将字符串转换为整数
# 才能用于数值比较:

a = int(input("input:"))
b = int(input("input:"))
c = input("input:")
print(type(c))
print(type(a))

print(‘%d*%d=%d‘%(a,b,a*b))

输入:
input:3
input:3
input:2

执行结果:
<class ‘str‘>
<class ‘int‘>
3*3=9

输出:print()

#!/usr/bin/python3

x="a"
y="b"
 
# 换行输出
print( x )
print( y )

# 不换行输出
print( x, end=" " )
print( y, end=" " )

# 同时输出多个变量
print(x,y)

# 打印值
print ("hello")

# 打印变量
age = 18
print("age变量值是:%d",%age)

8、变量

①.什么是变量:
    变量是指没有固定的值,可以改变的数,功能是存储数据

 ②.变量的定义:

    等号(=)运算符左边是一个变量名,等号(=)运算符右边是存储在变量中的值

    示例:
    counter = 100 # 整型变量
    miles = 1000.0 # 浮点型变量
    name = "demo" # 字符串

 ③.多个变量赋值:

    # 创建一个整型对象,值为1,三个变量被分配到相同的内存空间上
    a = b = c = 1

    # 两个整型对象 1 和 2 的分配给变量 a 和 b,字符串对象 "demo" 分配给变量 c
    a, b, c = 1, 2, "demo"

④.变量类型转换

  a = 1
  b = float(a)
  print(b)

  >>>1.0

9、分支结构(if...else)

多项分支结构:

#!/usr/bin/python3

age = int(input("请输入你家狗狗的年龄: "))
print("")

if age < 0:

    print("你是在逗我吧!")

elif age == 1:

    print("相当于 14 岁的人。")

elif age == 2:

    print("相当于 22 岁的人。")

elif age > 2:

    human = 22 + (age -2)*5

    print("对应人类年龄: ", human)

 ### 退出提示

input("点击 enter 键退出")

嵌套分支结构:

# !/usr/bin/python3

num=int(input("输入一个数字:"))
if num%2==0:
    if num%3==0:
        print ("你输入的数字可以整除 2 和 3")
    else:
        print ("你输入的数字可以整除 2,但不能整除 3")

else:
    if num%3==0:
        print ("你输入的数字可以整除 3,但不能整除 2")
    else:
        print  ("你输入的数字不能整除 2 和 3")

10、循环结构

# while循环

格式1:
    while 条件表达式:
        循环的内容
        [变量的变化] 

格式2:
    while 条件表达式:
        循环的内容
        [变量的变化]
    else:
        python语句..

# for训话
# for...in 循环用于遍历容器类的数据(字符串,列表,元组,字典,集合)

格式1: 
    for  变量  in  容器:
        python代码,可以在此使用变量
 
格式2:
    for 变量1,变量2 in 容器:
        python代码,可以在此使用变量1和变量2

11、else子句、break子句、continue子句、pass子句

# else子句

格式:
    for  变量  in  容器:
        python代码,可以在此使用变量
    else:
        循环结束是执行的代码!


# break子句
# break作用:终止当前循环结构的后续操作
# !/usr/bin/python3

for letter in ‘Runoob‘:     # 第一个实例
   if letter == ‘b‘:
      break
   print (‘当前字母为 :‘, letter)

var = 10                    # 第二个实例
while var > 0:              
   print (‘当期变量值为 :‘, var)
   var = var -1
   if var == 5:
      break
print ("Good bye!")


# continue子句
# continue作用:跳过当前循环块中的剩余语句,然后继续进行下一轮循环
#!/usr/bin/python3

for letter in ‘Runoob‘:     # 第一个实例
   if letter == ‘o‘:        # 字母为 o 时跳过输出
      continue
   print (‘当前字母 :‘, letter)

var = 10                    # 第二个实例
while var > 0:              
   var = var -1
   if var == 5:             # 变量为 5 时跳过输出
      continue
   print (‘当前变量值 :‘, var)
print ("Good bye!")

# pass语句
# pass是空语句,是为了保持程序结构的完整性,pass 不做任何事情,一般用做占位语句

def spide():
    pass

if __name__ == "__main__":
    spider()

  

  

 

 

 

 

 

  

 

Python基础

标签:解释   编码   运算   put   访问   oat   实现   let   cal   

原文地址:https://www.cnblogs.com/Iceredtea/p/9656869.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!