2015-06-06 105 views
-1

所以我試圖改變一個隨機變量爲一個函數的字符串,任何想法,爲什麼這是行不通的?如何在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 ` 
+0

往回走你的Python控制檯慢,深呼吸,然後閱讀[這篇文章](http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/)right現在。 –

回答

2

您必須從函數返回值並將其賦值給變量。

def letter(x): 
    ... 
    return x 


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

謝謝!對不起,如果這是一個愚蠢的問題。 –

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 
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 
0

添加功能

return x 

value_you_want =信(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 
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 
相關問題