Python入门-基本操作

基础操作

  • 输出 print

使用双引号输出:

print("hello world!")

使用单引号输出:

print('hello world!')
  • 转义字符——
    \t:TAB
print("tab\t输出")

\n:换行输出

print("换行\n输出")

':输出单引号

print("单引号输出\'")

":输出双引号

print('双引号输出\"')
  • 创建变量
x=5
print(x)
  • 输出大小写 lower、upper、title
y='HEllo WORld'
print(y.lower())  #小写输出
print(y.upper())  #大写输出
print(y.title())  #标题输出 大写第一个字母
  • 查看使用方法
y.upper?
  • 使用帮助
help(y.lower)
  • 分离 split()
y='HEllo WORld'
y.split("E")

结果:['H', 'llo WORld']
  • 连接 join()
str = "-"; 
seq = ("a", "b", "c"); # 字符串序列 
print str.join( seq );

结果:a-b-c
  • 输出
print("1"+"3")
结果:13
  • 合并字符
"Hello"+"World"
结果:'HelloWorld'

**

基础数学

1+1   #加法
2
130-2.0   #如果有其一是浮点数,则输出结果为浮点数
128.0
130/2    #除法
65.0
130.0/2
65.0
2*3    #乘法
6
2**3   #乘方
8
9%3   #取余
0
  • if语句:检查某些东西是否为True,如果是,则执行此操作。如果它不是True(False),则不执行
num = 3
if num = 3:
    print(num)
结果:3
  • 逻辑操作符:
    • and:如果两个操作数均为True,则状态变为True

    • or:如果两个操作数中的任何一个为True,则状态变为True

    • not:用于反转逻辑(不是False变成True,而是True变成Flase)

if False or False: 
    print('Nothing will print out')        #两者均为False时不输出
num = 10
not num < 20      #not的作用只是把True变成False,而不是把False变成True
结果:False
  • else语句: 必须在if或elif语句之后。最多可以有一个其他声明。仅当上面的所有“if”和“elif”语句都为False时才会执行
num = 1
if num > 3 :
    print("Hi")
else:
    print("number is not greater than 3")

结果:number is not greater than 3
  • elif语句:必须在if语句之后。 elif语句语句允许您检查True的多个表达式,并在其中一个条件求值为True时立即执行代码块。
    *与else类似,elif语句是可选的。但是,与其他情况不同,最多只能有一个语句,if后面可以有任意数量的elif语句。
dice_value = 1 
if dice_value == 1: 
    print('You rolled a {}. Great job!'.format(dice_value)) 
elif dice_value == 2:
    print('You rolled a {}. Great job!'.format(dice_value)) 
elif dice_value == 3: 
    print('You rolled a {}. Great job!'.format(dice_value)) 
elif dice_value == 4: 
    print('You rolled a {}. Great job!'.format(dice_value)) 
elif dice_value == 5: 
    print('You rolled a {}. Great job!'.format(dice_value)) 
elif dice_value == 6: 
    print('You rolled a {}. Great job!'.format(dice_value)) 
else: 
    print('None of the conditions above (if elif) were evaluated as True')

结果:You rolled a 1. Great job!
  • 格式化函数:format()

*Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 : 来代替以前的 % 。
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.runoob.com"))   # 通过字典设置参数 
>>>site = {"name": "菜鸟教程", "url": "www.runoob.com"} 
print("网站名:{name}, 地址 {url}".format(**site))   # 通过列表索引设置参数 
>>>my_list = ['菜鸟教程', 'www.runoob.com'] 
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的
  • 列表:列表后面要加上方括号
z=[0,5,6,2]          #创建列表
  • 访问列表里的值
z[0]             #输出单个元素
0
z[0:2]           #输出的元素是z[0]、z[1],不包含z[2]、z[3]。即包含最前的索引,不包含最后的索引。
[0, 5, 6]
z[:3]            #输出直到下标前为止的所有值。
[0, 5, 6]
z[2:]            #输出从下标开始直到列表结束的所有值。
[6,2]
  • 取列表的最大值,最小值,长度以及总和
print(min(z), max(z), len(z), sum(z))
  • 对列表中对象出现次数进行统计
random_list = [4, 1, 5, 4, 10, 4] 
random_list.count(4)

结果:3
  • 返回列表第一个指针:List index()
    index() 函数用于从列表中找出某个值第一个匹配项的索引位置。

    • 参数:
      x-- 查找的对象。
      start-- 可选,查找的起始位置。
      end-- 可选,查找的结束位置。

格式:random_list.index(value, [start, stop])
*value:要寻找的值;start:起始位置(从0开始);stop:结束的位置

aList = [123, 'xyz', 'runoob', 'abc']
print "xyz 索引位置: ", aList.index( 'xyz' )
print "runoob 索引位置 : ", aList.index( 'runoob', 1, 3 )

结果:xyz 索引位置:  1
runoob 索引位置 :  2
random_list = [4, 1, 5, 4, 10, 4]
random_list.index(4, 5, 6)

结果:5
  • 对列表进行排序

sort()语法:list.sort( key=None, reverse=False)

参数:
key – 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse – 排序规则,reverse = True 降序, reverse = False 升序(默认)。

x = [3, 7, 2, 11, 8, 10, 4] 
y = ['Steve', 'Rachel', 'Michael', 'Adam', 'Monica', 'Jessica', 'Lester']
x.sort()
print(x)

结果:[2, 3, 4, 7, 8, 10, 11]
x.sort(reverse = True)
print(x)

结果:[11, 10, 8, 7, 4, 3, 2]
new_list = sorted(y)
new_list

结果:['Adam', 'Jessica', 'Lester', 'Michael', 'Monica', 'Rachel', 'Steve']

以下实例演示了通过指定列表中的元素排序来输出列表:

  • 获取列表的第二个元素
def takeSecond(elem): 
    return elem[1] 

列表

random = [(2, 2), (3, 4), (4, 1), (1, 3)] 
  • 指定第二个元素排序
random.sort(key=takeSecond) 
  • 输出类别
print ('排序列表:', random)


结果:排序列表:[(4, 1), (2, 2), (1, 3), (3, 4)]
  • 在列尾添加一个对象:append()
x=[11, 10, 8, 7, 4, 3, 2]

x.append(3)
print(x)
结果:[11, 10, 8, 7, 4, 3, 2, 3]
  • 删除列表中的一个对象:remove()
x.remove(10)
print(x)

结果:[11, 8, 7, 4, 3, 2, 3]
  • 删除指定位置的对象:.pop()

格式:pop(key[,default])

  • 参数
    key: 要删除的键值
    default: 如果没有 key,返回 default 值
x.pop(3)                    #x.pop()方法会返回被删除的值
4

print(x)
结果:[11, 8, 7, 3, 2, 3]
  • 合并列表:通过在末尾续加的方式来延长列表
x.extend([4, 5])
x

结果:[11, 8, 7, 3, 2, 3, 4, 5]
x=[11, 8, 7, 3, 2, 3, 4, 5]
y=['Steve', 'Rachel', 'Monica', 'Michael', 'Lester', 'Jessica', 'Adam']           #不同类型的列表也能连接

结果:x+y= [11, 8, 7, 3, 2, 3, 4, 5, 'Steve', 'Rachel', 'Monica', 'Michael', 'Lester', 'Jessica', 'Adam']
  • 在列表指定位置前插入对象

list.insert(index, obj) #是在需要插入的索引位置之前插入对象参数
index – 对象 obj 需要插入的索引位置。
obj – 要插入列表中的对象。

x=[11, 8, 7, 3, 2, 3, 4, 5]
x.insert(4, [4, 5])
x

结果:[11, 8, 7, 3, [4, 5], 2, 3, 4, 5]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值