2017-03-08 67 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)' –

相关问题