如何在python中将变量更改为字符串?

时间:2015-06-06 10:50:13

标签: python

所以我试图将一个随机变量更改为带有函数的字符串,任何想法为什么这不起作用?

def letter(x):
    if x == 1:
            x = "A"
    elif x == 2:
            x = "C"
    elif x == 3:
            x = "G"
    elif x == 4:
            x = "T"
    else:
            print "Error" 
randint18= random.randrange(1,5)
letter(randint18)
print randint18 `

5 个答案:

答案 0 :(得分:2)

您必须从函数返回值,并将其分配给变量。

def letter(x):
    ...
    return x


randint18 = random.randrange(1, 5)
result = letter(randint18)
print result

答案 1 :(得分:1)

您无法更改变量,必须将其返回并捕获返回的值。

import random

def letter(x):
    if x == 1:
            x = "A"
    elif x == 2:
            x = "C"
    elif x == 3:
            x = "G"
    elif x == 4:
            x = "T"
    else:
        print "Error" 
    return x  # return it here

randint18= random.randrange(1,5)
randint18 = letter(randint18)  # capture the returned value here 
print randint18

有一种更简单的方法可以实现您想要的效果,使用字典来映射值。

import random

def letter(x):
    mapd = {1:'A', 2:'C', 3:'G', 4:'T'}
    return mapd.get(x, None)

randint18= random.randrange(1,5)
randint18 = letter(randint18)
print randint18

答案 2 :(得分:1)

我已经提供了不正确的答案,但建议改进你的代码。我会在评论中这样做,但代码格式不够好。

为什么不使用字典进行映射,而不是使用if的序列?如果你愿意,你仍然可以把它放在一个函数中:

letter = {1:'A', 2:'C', 3:'G', 4:'T'}
randint18 = random.randrange(1,5)
mapping = letter.get(randint18, 'Error')
print mapping

请注意,如果映射从零开始,列表会更有效:

letter = ['A', 'C', 'G', 'T']
randint18 = random.randrange(0,4)
try: # in case your random index were allowed to go past 3
 mapping = letter[randint18]
except IndexError:
 mapping = 'Error'
print mapping

答案 3 :(得分:0)

您忘记在功能中加入退货

def letter(x):
    if x == 1:
            x = "A"
    elif x == 2:
            x = "C"
    elif x == 3:
            x = "G"
    elif x == 4:
            x = "T"
    else:
            print "Error" 
    return x
randint18 = random.randrange(1,5)
returned_result = letter(randint18)
print returned_result

答案 4 :(得分:0)

添加函数的返回值

return x

value_you_want = letter(randint18)##添加return语句。输出将保存到value_you_want

请注意,函数内定义的变量是函数的本地变量,不能在函数范围之外访问。您期望函数外部的x值是不可能的。只是检查运行您的函数并尝试访问变量x中的值。它会给出错误。

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    print x
NameError: name 'x' is not defined