2017-03-08 64 views
-3
def vel(y,umax,r,Rmax): 
    vel_p=umax*(1-(r/Rmax)**2) 

    if r<50: 
     r=50-y 
    else: 
     r=y-50 
    return 'the value of velocity in cell is %r,%r,%r,%r'%(umax,r,Rmax,vel_p) 


def main(): 

    y=(input('enter y')) 
    a=(input('enter the umax')) 
    #b=(input('enter the r')) 
    b=(r) 
    c=(input('enter the Rmax')) 
    print(vel(a,c,b,y)) 

main() 

我不明白的地方我應該把[R它給了我沒有定義如果else語句,全局名稱沒有定義

+4

那麼,爲什麼你註釋掉輸入「r」的行並將其替換爲一個不存在的變量的引用呢? –

+1

你也不需要圍繞'input'進行括號。這看起來像它產生了一個「元組」,但它不會(忽略逗號'','),並且可能會引起混淆。 –

+0

,因爲我需要從y獲得r的值,如果我不把它放在註釋中,它將取我的r值,並且不會從if語句計算 – joe

回答

-1

在你主要方法錯誤全局變量R,您分配b = (r),而你永遠不規定什麼是R,所以如果你在全球範圍內具有可變r然後在main方法的第一行應該是

 
def main(): 
    global r 
    # Now you can use your r 

通過這樣做,你叫你的變量r在你的方法。

希望它能幫助:)

+0

謝謝你,我嘗試了兩種方法,它的工作。 – joe

+0

然後爲什麼一個-1爲我的答案,請標記它正確,如果它爲你工作:\ –

+0

我沒有標記任何,實際上我不能,我想增加,但不可能從我身邊先生 – joe

0

正如已經在評論中提到的,嘗試,因爲這有助於減少混淆使用「好」(=可讀)變量名。

從字符串到浮點數的轉換應該對非數值輸入進行穩健的處理,使用try ... except,所以我將它放在一個單獨的函數中。

通常,你不希望函數返回一個插入了所有計算值的字符串,而是返回「原始」值。這些值的打印通常應該在別的地方完成。

在你提到你的評論中,「如果我不把它放在評論中,那麼你需要從y中獲得r的值,它取得了我的r值並且不會從if語句計算」,但是你的函數vel()使用r來計算第一行中的vel_p。變量r是函數的參數,所以它必須來自某處。您可以讓用戶像輸入所有其他值一樣輸入它,或者您必須在其他地方定義它。如果你在全球範圍內做到這一點,請看Vipin Chaudharys的答案。

我的建議,如果你希望用戶輸入R:

def vel(y, u_max, r, r_max): 
    # You use the value of r here already! 
    vel_p=u_max*(1-(r/r_max)**2) 

    # Here you change r, if r is less than 50. 
    # You are using r again, before assigning a new value! 
    if r<50: 
     r=50-y 
    else: 
     r=y-50 

    # I use the preferred .format() function with explicit field names 
    # \ is used to do a line-break for readability 
    return 'The value of velocity in cell is umax: {value_u_max}, \ 
r: {value_r}, Rmax: {value_r_max}, vel_p: {value_vel_p}.'.format(
    value_u_max=u_max, value_r=r,value_r_max=r_max, value_vel_p=vel_p) 

# Helper function to sanitize user input  
def numberinput(text='? '): 
    while True: 
     try: 
      number=float(input(text)) 
      # return breaks the loop 
      return number 
     except ValueError: 
      print('Input error. Please enter a number!') 


def main(): 
    y=numberinput('Enter y: ') 
    u_max=numberinput('Enter the umax: ') 
    r=numberinput('Enter the r: ') 
    r_max=numberinput('Enter the Rmax: ') 
    print(vel(y, u_max, r, r_max)) 

main() 

通知,即r的輸入值是用來做計算。然後根據y更改它,並打印新值。

+0

非常感謝你很多,我明白我的錯誤。 – joe

+0

嗨,你能告訴我,如果我需要打印我的價值,我應該給什麼語法或命令?現在它正在返回整個論點,但我只需要速度。 – joe

+0

如果您只想打印'vel'的值,請更改函數的'return'語句:'return'單元格中velocity的值爲{value_vel_p}。'。format(value_vel_p = vel_p)' –

相關問題