鱼C论坛

 找回密码
 立即注册
查看: 2743|回复: 6

依旧求助关于字符串+参数

[复制链接]
发表于 2017-2-20 23:48:34 | 显示全部楼层 |阅读模式
15鱼币
本帖最后由 vincenzo0823 于 2017-2-21 23:40 编辑

题目是做一个 打开以创建写入内容的函数
  1. def text_create(name,msg):
  2.     desktop_path = r'C:\Users\Administrator\Desktop'
  3.     full_path = desktop_path + name + '.txt'
  4.     file = open(full_path,'w')
  5.     file.write (msg)
  6.     file.close()
  7.     print ('done')
复制代码


其中
1,        def text_create(a,b)报错
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    text_create(a,b)
NameError: name 'a' is not defined
2,def text_create(1,2)报错
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    text_create(1,2)
  File "C:\Users\Administrator\Desktop\PYTHON 课后练习\11.py", line 4, in text_create
    full_path = str(desktop_path + name + '.txt')
TypeError: Can't convert 'int' object to str implicitly
3,我参数的值是name 为什么下面说找不到name呢?
4,说我不能讲整数 与字符串想家,那应该如何操作才能完成这个内容呢?



那么各位我换个问题,如何创建一个 创建,读取,写入的函数呢?
例如def text_create(name.msg)
这个text_create()调用的时候 name是文件名,msg是内容。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-2-21 09:13:16 | 显示全部楼层
实际上所有的问题都是函数的参数应该是字符串。
你尝试一下这样使用:
text_create('readme', 'This is my first file.')
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-2-21 09:57:09 | 显示全部楼层
传送的参数是int型或者float型的怎么处理
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-2-21 11:17:27 From FishC Mobile | 显示全部楼层
3,传入的参数带引号,除非参数是变量就不带
4,str(name)
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-2-21 13:42:37 | 显示全部楼层
aqiang159 发表于 2017-2-21 09:57
传送的参数是int型或者float型的怎么处理

在函数里 通过 type() 函数判断 参数类型,if (类型是 int or float) :
                                                                        print('请输入正确的参数类型:')
                                                                else:
                                                                       ......................
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-2-21 16:57:10 | 显示全部楼层
使用str()函数将整数转为字符串,就可以与字符串相连接了
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-2-21 21:58:35 | 显示全部楼层
感觉你这个实参 -形参处理是有问题,name字符型
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-25 12:10

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表