06 -Python入门- Lesson6 脚本

本篇教程介绍了Python脚本中的原始输入、格式化字符串方法,包括print的使用、format的对齐和精度控制。同时,讲解了错误处理、读写文件、导入模块、第三方库的使用以及在线资源的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

06 Python入门 Lesson6 脚本

9.在脚本中接受原始输入

这里出现了个有点奇怪的print函数,就是上节讲到

name = input("Enter your name: ")
print("Hello there, {}!".format(name.title()))

Plus.格式化字符串

课程中初次见面

有点奇怪啊,不就是让用户输入个名字,不是应该这样的么?

name = input("Enter your name: ")
print("Hello there, ", name, "!")

对的,实际上输出是一样的,后面这个我们比较熟悉,把字符和变量串在一起输出。但是观察下上下对比,是不是上面的这个比较简单呢?这种新的方法叫做:**print格式化字符串。**大家对比观察一下,其实就是在print里面放了个{},并在后面加了个.format(name.title)。这个语句的意思是,打印到{}的时候,把后面这个.format()里的东西打印出来,name.title就是把输入的name的第一个字母改为大写。默认{} {} {}…会按照后面.format(a, b, c)来替换,但也可以指定。比如{0}指定的是a,{1}指定的是b,以此类推。举个例子就知道了:

##format methord
print('---test1:---')
print('I am lucky to eat {} {} {} {}!'.format(4,'eggs', 1, 'spam'))
print('---test2:---')
print('I am lucky to eat {2} {1} {3} {0}!'.format(4,'eggs', 1, 'spam'))
print('---test3:(option)---')
print('I am lucky to eat {2:.2f} {1} {3} {0}!'.format(4,'eggs', 1, 'spam'))
print('---test4:(option)---')
print('I am lucky to eat {2:.2f} {1:#^20} {3} {0}!'.format(4,'eggs', 1, 'spam'))

输出是这样的:其中test3,4是更为复杂的应用,感兴趣的话看这两个链接:https://blog.youkuaiyun.com/i_chaoren/article/details/77922939
https://www.cnblogs.com/wilber2013/p/4641616.html

---test1:---
I am lucky to eat 4 eggs 1 spam!
---test2:---
I am lucky to eat 1 eggs spam 4!
---test3:(option)---
I am lucky to eat 1.00 eggs spam 4!
---test4:(option)---
I am lucky to eat 1.00 ########eggs######## spam 4!

print中输出变量的简单方法

print再扩展一点,如果看到这样的家伙 + variable + ,是一种在字符串中加变量的方法,其实和逗号分隔是等价的:

print('hi ' + name + ' !')
print("hi " + name + " !")
print('hi', name, '!')
print("hi", name, "!")
#这4个的输出都是一样的:(注意下代码前后的空格是不一样的,所以前面的也会用到)
hi handsome !

需要处理复杂的就print(“xxx{}” .format()) (ps:还有一种写法是print(“xx%zz” % ())大家知道就可以了)。详细的带入列表和字符串的方法:https://stackoverflow.com/questions/17153779/how-can-i-print-variable-and-string-on-same-line-in-python

这一节后面还有个eval是把用户输入的内容当作python代码处理。扩展下也可以这样使用,把str字符转化为相应的内容(>>>是输入的代码),大家注意a和b的type是不一样的:

>>> a = "{1: 'a', 2: 'b'}"
>>> type(a)
<type 'str'>
 
>>> b = eval(a)
>>> print(b)
{1: 'a', 2: 'b'}
>>> type(b)
 <type 'dict'>

format中的对齐

(本部分和下部分参考了这个非常详细的format说明)

填充常跟对齐一起使用,^ 、<、>分别是居中、左对齐、右对齐,后面带宽度
:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
比如:

In [15]: '{:>8}'.format('189')
Out[15]: '   189'
In [16]: '{:0>8}'.format('189')
Out[16]: '00000189'
In [17]: '{:a>8}'.format('189')
Out[17]: 'aaaaa189'

精度常跟类型f一起使用

精度的设定:注意这里的format对象要是具体的,不能是ndarray或者dataframe这样的输出,这两个的现实方式再后面会讲解。

In [44]: '{:.2f}'.format(321.33345)
Out[44]: '321.33'
# 其中.2表示长度为2的精度,f表示float类型
In [47]: '{:,}'.format(1234567890)
Out[47]: '1,234,567,890'
# 其中,是分隔符(为了看着方便)

其他进制的转换:主要就是进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制。

In [54]: '{:b}'.format(17)
Out[54]: '10001'
In [55]: '{:d}'.format(17)
Out[55]: '17'
In [56]: '{:o}'.format(17)
Out[56]: '21'
In [57]: '{:x}'.format(17)
Out[57]: '11'

format对于可迭代对象的处理方式

在项目中遇到需要对dataframe的元素输出(ndarray也是类似)时,当前版本报错:TypeError: unsupported format string passed to Series.format

原因是format不能处理这种输出,要想输出dataframe的内容,需要用循环依次输出,举个例子(需要项目数据,请参考,无法复现,后续补充):

14.处理错误

大家理解try、except、else、finally4个语句的执行条件就好了。

  • try:这是 try 语句中的唯一必需子句。该块中的代码是 Python 在 try 语句中首先运行的代码。
  • except:如果 Python 在运行 try 块时遇到异常,它将跳到处理该异常的 except 块。
  • else:如果 Python 在运行 try 块时没有遇到异常,它将在运行 try 块后运行该块中的代码。
  • finally:在 Python 离开此 try 语句之前,在任何情形下它都将运行此 finally 块中的代码,即使要结束程序,例如:如果 Python 在运行 except 或 else 块中的代码时遇到错误,在停止程序之前,依然会执行此finally 块。
  • 对于15的例子做个简单的说明(以注释方式):
def create_groups(items, num_groups):
    #定义函数,2个输入items(多少个东西),分成num_groups(分成多少个组)
    try:
        size = len(items) // num_groups
    #上来是计算每组大小
    except ZeroDivisionError:
        print("WARNING: Returning empty list. Please use a nonzero number.")
        return []
    #但是当发生ZeroDivisionError时(除数为0的时候的错误),就显示错误并返回空值
    else:
        groups = []
        for i in range(0, len(items), size):
        #是说从0到items的最大数(就是len(items)这个的结果),按照size(在try语句中得出的每组大小)进行循环
            groups.append(items[i:i + size])
            #每一个循环,把当前的组存追加存放到groups里面
        return groups
    #如果没报错,就是按照上面这一段把每组都有什么写到groups里面
    finally:
        print("{} groups returned.".format(num_groups))
    #无论怎么处理的,都打印一行提示,使用的是格式化字符串的方式
    
print("Creating 6 groups...")
for group in create_groups(range(32), 6):
    print(list(group))
print("\nCreating 0 groups...")
for group in create_groups(range(32), 0):
    print(list(group))

输出是这样的:

Creating 6 groups...
6 groups returned.
[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[10, 11, 12, 13, 14]
[15, 16, 17, 18, 19]
[20, 21, 22, 23, 24]
[25, 26, 27, 28, 29]
[30, 31]

Creating 0 groups...
WARNING: Returning empty list. Please use a nonzero number.
0 groups returned.

因为函数输出的是一个嵌套的列表,所以要用上面的方式把列表的每一组元素显示出来,我们加一句print就能看明白了:

print(create_groups(range(38),3))

输出是这样的:

3 groups returned.
[range(0, 12), range(12, 24), range(24, 36), range(36, 38)]

另外,即是except有报错输出,也是可以通except as的方式访问并输出的,这一块知道就行了。

注意append和write区别,和with的用法

  • 追加文件是用f.append(),使用f.write()将会覆盖文件
  • 为了避免忘记f.close()关闭一个文件,可以使用with的方式:
with open('my_path/my_file.txt', 'r') as f:
    file_data = f.read()
#和下面的语句是一样的
f = open('my_path/my_file.txt', 'w')
file_data = f.read()
f.close()

19.读写文件

注意这个地方有个新的.split(’,’)方法,用处是把line里面的内容用,split开,关于readline相关的用法,总结为以下几个例子:

print('{0:-^30}'.format('print read'))
#print函数会在结尾自动加入换行
with open('print.format.py') as song:
    print(song.read(1))
    print(song.read(8))
    print(song.read(8))
    #print(song.read())

print('{0:-^30}'.format('print read end none'))
with open('print.format.py') as song:
    print(song.read(1), end = '')
    print(song.read(8), end = '')
    print(song.read(8))
    #print(song.read())

print('{0:-^30}'.format('print readline'))
with open('print.format.py') as song:
    print(song.readline())
    print(song.readline())
    print(song.readline(1), end = '\n\n')
    #可以看出readlline()是每次读取一行(/n换行跟随上一行,不会算成下一行)
    #如果readline(x),就是读出这行的x个字符
    #这种方式时结尾的/n不会打印
    #结尾\n\n 才会换行,一个的话会追加到x个字符后面

print('{0:-^30}'.format('print readlines'))
with open('print.format.py') as song:
    print(song.readlines(), end = '\n\n')
    #readlines是把所有行读入到一个列表中

print('{0:-^30}'.format('for line in file'))
test_lines = []
with open('print.format.py') as song:
#line可以替换成i,只不过line比较明确
#这里重点是,对于open的文件,for 循环是每次循环一行
    for line in song:
        test_lines.append(line.strip())
    print(test_lines,end = '\n\n')

print('{0:-^30}'.format('split lines'))
def create_cast_list(filename):
    cast_list = []
    #use with to open the file filename
    with open("circus.csv") as f:
        for line in f:
            name=line.split(',')[0]
            cast_list.append(name.strip())
        #下面的是最后一个循环的输出,输出做对比就明白很多了:
        print('{0:-^30}'.format('under is split testing'))
        print('originial: {0:#^20}'.format(line), end = '')
        nameall = line.split(',')
        nameallfirst = line.split(',')[0]
        print(name)
        print(nameall)
        print(nameallfirst)
    #use the for loop syntax to process each line
    #and add the actor name to cast_list

    return cast_list

cast_list = create_cast_list('circus.csv')
for actor in cast_list:
    print(actor)

结果如下,感兴趣的可以自己研究下:

----------print read----------
#
#format 
methord

-----print read end none------
##format methord

--------print readline--------
##format methord

print('---test1:---')

p

-------print readlines--------
['##format methord\n', "print('---test1:---')\n", "print('I am lucky to eat {} {} {} {}!'.format(4,'eggs', 1, 'spam'))\n", '\n', "print('---test2:---')\n", "print('I am lucky to eat {2} {1} {3} {0}!'.format(4,'eggs', 1, 'spam'))\n", '\n', "print('---test3:(option)---')\n", "print('I am lucky to eat {2:.2f} {1} {3} {0}!'.format(4,'eggs', 1, 'spam'))\n", '\n', "print('---test4:(option)---')\n", "print('I am lucky to eat {2:.2f} {1:#^20} {3} {0}!'.format(4,'eggs', 1, 'spam'))\n"]

-------for line in file-------
['##format methord', "print('---test1:---')", "print('I am lucky to eat {} {} {} {}!'.format(4,'eggs', 1, 'spam'))", '', "print('---test2:---')", "print('I am lucky to eat {2} {1} {3} {0}!'.format(4,'eggs', 1, 'spam'))", '', "print('---test3:(option)---')", "print('I am lucky to eat {2:.2f} {1} {3} {0}!'.format(4,'eggs', 1, 'spam'))", '', "print('---test4:(option)---')", "print('I am lucky to eat {2:.2f} {1:#^20} {3} {0}!'.format(4,'eggs', 1, 'spam'))"]

---------split lines----------
----under is split testing----
originial: The Fred Tomlinson Singers,  Amantillado Chorus / ... (7 episodes, 1969-1973)
The Fred Tomlinson Singers
['The Fred Tomlinson Singers', '  Amantillado Chorus / ... (7 episodes', ' 1969-1973)\n']
The Fred Tomlinson Singers
Graham Chapman
Eric Idle
Terry Jones
Michael Palin
Terry Gilliam
John Cleese
Carol Cleveland
Ian Davidson
John Hughman
The Fred Tomlinson Singers

21.导入本地模块

接下来讲解下if main这一块:

  • if name == ‘main’ 简单的理解就是: 如果模块是被直接运行的,则代码块被运行,如果模块是被导入的,则代码块不被运行
  • 是为了在导入时候不运行(被调用才运行)的限制
  • 详细说明:http://blog.konghy.cn/2017/04/24/python-entry-program/
  • 23标准库
  • 这里介绍了random标准库的两个用法,总结如下:
import random
word_list = ['tatoo', 'happy', 'apple', 'ios', 4]

def generate_password():
    return str(random.choice(word_list)) + str(random.choice(word_list)) + str(random.choice(word_list))
    #增加了str确保如果wordlist里面有4这样的数字可以转化为字符
print(generate_password())

def generate_password2():
    return ''.join(random.sample(word_list,5))
    #join方式就不能加str,要求wordlist都是字符,但是既然是wordlist就应该都保证是字符
    #而不是在写处理代码时候再额外处理不推进str的方式
print(generate_password2())

27.第三方库

在安装python或者ananconda后,可以使用:pip install package_name 来安装需要的包。推荐的一些安装包很实用,/链接归档/。当然也可以将需要的包放在一个文件中,批量安装 pip install -r requirements.txt ,requeirement.txt文件示例如下:

beautifulsoup4==4.5.1
bs4==0.0.1
pytz==2016.7
requests==2.11.1

29.在线资源

有空要看!提升软能力!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值