python里if语句name未定义_If-else语句,未定义全局名称

正如注释中已经提到的,尝试使用“good”(=可读)变量名,因为这有助于减少混淆。在

从字符串到float的转换应该对使用try…except的非数字输入具有健壮性,因此我将其放在一个单独的函数中。在

通常,您不希望函数返回一个字符串,其中插入了所有计算值,但返回“原始”值。这些值的打印通常应该在其他地方进行。在

在您提到的注释中,您提到“需要从y获得r的值,如果我不把它放在注释中,它将取我的r值,并且不会从if r语句计算”,但是您的函数vel()在第一行使用r来计算vel_pp。变量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改变,并打印新值。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值