python中if函数是什么意思_在if语句中调用函数

在调用函数之前,需要先定义函数。把def option1(): #and all that code below it放在if语句的上方。

抛出太多全局变量也是一种不好的做法。您不应该像现在这样使用savinginfile——而是将它作为参数传递给函数,让函数在自己的作用域中运行。在使用savinginfile之前,需要将要使用的文件名传递给函数。请改为:def option1(whattosaveinfile):

test = open("test.txt","a+") #probably better to use a with statement -- I'll comment below.

test.write(whattosaveinfile) #note that you use the parameter name, not the var you pass to it

print("Option 1 used")

test.close()

#that with statement works better for file-like objects because it automatically

#catches and handles any errors that occur, leaving you with a closed object.

#it's also a little prettier :) Use it like this:

#

# with open("test.txt","a+") as f:

# f.write(whattosaveinfile)

# print("Option 1 used")

#

#note that you didn't have to call f.close(), because the with block does that for you

#if you'd like to know more, look up the docs for contextlib

if menu == "1": #no reason to turn this to a string -- you've already defined it by such by enclosing it in quotes

savinginfile = raw_input("Please state your name: ")

option1(savinginfile) #putting the var in the parens will pass it to the function as a parameter.

elif menu == "2": #etc

#etc

#etc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值