GVKun编程网logo

在Python中写入(而非写入)全局变量(python输入内容必须为整数)

28

对于在Python中写入感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍而非写入全局变量,并为您提供关于python中全局变量和局部变量、python中全局变量的修改、python中全局变量的问

对于在Python中写入感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍而非写入全局变量,并为您提供关于python中全局变量和局部变量、python中全局变量的修改、python中全局变量的问题、python中写入txt文件需要换行,以及\r 和\n的有用信息。

本文目录一览:

在Python中写入(而非写入)全局变量(python输入内容必须为整数)

在Python中写入(而非写入)全局变量(python输入内容必须为整数)

来自不太动态的C ++,我在理解此Python(2.7)代码的行为时遇到了一些麻烦。

注意: 我知道这是不好的编程风格/邪恶,但我希望对此有所了解。

vals = [1,2,3]

def f():
    vals[0] = 5
    print 'inside',vals

print 'outside',vals
f()
print 'outside',vals

此代码运行无误,并f操纵(看似)全局列表。这与我先前的理解相反,必须将要在函数中操作(且不仅要读取)的全局变量声明为global ...

另一方面,如果我替换vals[0] = 5vals += [5,6],则UnboundLocalError除非添加global vals到,否则执行将失败并显示为f。这也是我在第一种情况下的预期。

您能解释一下这种行为吗?

为什么vals在第一种情况下可以操作?为什么第二种类型的操作会失败而第一种类型的却不会失败?

更新:vals.extend(...)没有的情况下,评论中指出了这一点global。这加剧了我的困惑-
为什么+=将呼叫与区别对待extend

python中全局变量和局部变量

python中全局变量和局部变量

1、

python中定义在函数内部的变量称为局部变量,局部变量只能在局部函数内部生效,它不能在函数外部被引用。

def discount(price,rate):
    price_discounted = price * rate
    return price_discounted
sale_price = float(input("please input the sale_price:"))
discount_rate = float(input("please input the discount_rate:"))
sell_price = discount(sale_price,discount_rate)
print("sell_price is: %.3f" % sell_price)
## 在以上脚本中, 定义函数discount(),两个形参price和rate。 局部变量为 price、rate 和 price_discounted. 全局变量为 sale_price、discount_rate和 sell_price。

运行效果如下:

please input the sale_price:800
please input the discount_rate:0.5
sell_price is: 400.000

 

a、尝试在函数外部访问全局变量和局部变量,全局变量可以访问,局部变量不可以访问

>>> sale_price            ## 全局变量
800.0
>>> discount_rate          ## 全局变量
0.5
>>> sell_price             ## 全局变量
400.0
>>> price                  ## 局部变量
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    price
NameError: name 'price' is not defined
>>> rate                   ## 局部变量
Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    rate
NameError: name 'rate' is not defined
>>> price_discounted        ## 局部变量
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    price_discounted
NameError: name 'price_discounted' is not defined

 

b、尝试在函数内部访问全局变量

def discount(price,rate):
    price_discounted = price * rate
    print("output globle varable sale_price:",sale_price)
    return price_discounted
sale_price = float(input("please input the sale_price:"))
discount_rate = float(input("please input the discount_rate:"))
sell_price = discount(sale_price,discount_rate)
print("sell_price is: %.3f" % sell_price)
please input the sale_price:800
please input the discount_rate:0.5
output globle varable sale_price: 800.0             ##在函数内部可以访问全局变量
sell_price is: 400.000

 

c、尝试在函数内部修改全局变量

def discount(price,rate):
    price_discounted = price * rate
    sale_price = 5000            ## 在函数内部修改全局变量
    print("new_sale_price:",sale_price)       ## 在函数内部输出修改后的变量
    return price_discounted
sale_price = float(input("please input the sale_price:"))
discount_rate = float(input("please input the discount_rate:"))
sell_price = discount(sale_price,discount_rate)
print("sell_price is: %.3f" % sell_price)
print("output the varable sale_price:",sale_price)    ## 在函数外输出修改后的变量,验证是否改变
please input the sale_price:800
please input the discount_rate:0.5
new_sale_price: 5000       ## 在函数内部返回修改后的变量
sell_price is: 400.000
output the varable sale_price: 800.0    ## 在函数外部返回原始变量
## 在函数内部可以访问全局变量,但是不可以修改全局变量

 

 局部变量只能在函数内调用,不能够在函数外调用; 全局变量可以在函数内访问,全局变量不可以在函数内修改。

全局变量的作用域在整个模块,局部变量的作用域在函数内。

 

python中全局变量的修改

python中全局变量的修改

对于全局变量的修改,如果全局变量是int或者str,那么如果想要在函数中对函数变量进行修改,则需要先在函数内,声明其为global,再进行修改

如果是list或者dict则可以直接修改

a = 1
b = [2, 3]
c = 1

def func():
    a = 2
    print ("in func a:", a)
    b[0] = 1
    print ("in func b:", b)
    global c
    c = 3
    print ("in func c:", c)

if __name__ == ''__main__'':
    print ("before func a:", a)
    print ("before func b:", b)
    print ("before func c:", c)
    func()
    print ("after func a:", a)
    print ("after func b:", b)
print ("after func c:", c)

 

python中全局变量的问题

python中全局变量的问题

           写了段python程序,

            #!/usr/bin/python
             print(''Function:'')
            i=0
            def Add():
                    print("Hello")
                    global i
                    i+=1
                    if i==10:
                               print("the function is 10 times")


            s=0
            while s<11:
                        Add()
                        global s
                        s+=1
        在Add()函数中时,我没有加global时,报的错误为local variable ''i'' referenced before assignment,意思是在python的函数中和全局同名的变量,如果你有修改变量的值就会变成局部变量,在修改之前对该变量的引用自然就会出现没定义这样的错误了,如果确定要引用全局变量,并且要对它修改,必须加上global关键字。

        我在while循环中使用s,也使用了global修饰,报的错误为:name s is assigned before global declaration

        把global去掉就没问题了,这个难道s在while循环里面就已经是全局变量吗?

python中写入txt文件需要换行,以及\r 和\n

python中写入txt文件需要换行,以及\r 和\n


在Python中,用open()函数打开一个txt文件,写入一行数据之后需要一个换行

如果直接用

f.write(’\n’)
只会在后面打印一个字符串’\n’,而不是换行’
需要用

f.write(’\r\n’)

 

注意点:

1、python文件写入的时候,当写入一段话之后叠加一个换行符     #特别注意的是python中的换行是 \n ,而不是/n    是反斜杠\,     而不是斜杠/

例子

#先写入一段话
f.write("我爱python!")
f.write(’\r\n’)
或者
f.write(''我爱python!\r\n'')

 

2、python 中的\n  和\r\n  的区别:

不同的是光标的位置:\n在下一行开头,\r在本行的开头

print u"你好吗?\n朋友"
print u"——分隔线——"
print u"你好吗?\r朋友"

输出

你好吗?
朋友
——分隔线——
朋友吗?

 

有时我们并不想让转义字符生效,我们只想显示字符串原来的意思,这就要用r和R来定义原始字符串。如:print r''\t\r''

  实际输出为“\t\r”。

常见的转义字符

转义字符 输出
\''   ''

\"

"
\a   ‘bi’响一声
\b 退格
\f  换页(在打印时)
\n 回车,光标在下一行
\r 换行,光标在上一行
\t 八个空格
\\ \



3、python中的文件操作每次向文件中写入数据的时候,如果文件存在的话,就向文件中叠加,如果没有的话,就创建新文件之后项中写入内容

在进行python进行文件读写的时候,第一次写进去的内容,第二次在进行写入会被覆盖掉,

原因是我们的方式用的是“w"或者别的之类的

换成”a“就可以了

file = open("D:/file.txt", ''a'')

而对于,如果一开始有文件的话,每次都会将原有的文件覆盖,如果没有的话就会创建并写入

file = open("D:/file.txt", ''w+'')

 

 

今天的关于在Python中写入而非写入全局变量的分享已经结束,谢谢您的关注,如果想了解更多关于python中全局变量和局部变量、python中全局变量的修改、python中全局变量的问题、python中写入txt文件需要换行,以及\r 和\n的相关知识,请在本站进行查询。

本文标签: