返回及;在Python中调用函数外部的变量。。。什么';这里怎么了?

返回及;在Python中调用函数外部的变量。。。什么';这里怎么了?,python,validation,try-catch,Python,Validation,Try Catch,我不喜欢问重复的问题,但我整天都在研究和工作这个项目,运气不好。它应该在Cel中测量水温。或者远,以英尺或米为单位的高度,告诉你在给定的高度,水是液态的、气态的还是固态的(不考虑大气压力,我只是想根据高度粗略估计一下)。经验法则是,每高于海平面300米(或1000英尺),水就会在低于100摄氏度约1度的温度下沸腾 我设法找到了几种方法使它返回一个大致正确的数字。下一步是向程序中添加错误检查。我尝试了一个“try”子句,但它没有抓住错误,我一辈子也弄不明白为什么 编辑 我尝试了另一种方法,它很有效

我不喜欢问重复的问题,但我整天都在研究和工作这个项目,运气不好。它应该在Cel中测量水温。或者远,以英尺或米为单位的高度,告诉你在给定的高度,水是液态的、气态的还是固态的(不考虑大气压力,我只是想根据高度粗略估计一下)。经验法则是,每高于海平面300米(或1000英尺),水就会在低于100摄氏度约1度的温度下沸腾

我设法找到了几种方法使它返回一个大致正确的数字。下一步是向程序中添加错误检查。我尝试了一个“try”子句,但它没有抓住错误,我一辈子也弄不明白为什么

编辑

我尝试了另一种方法,它很有效,捕捉到了错误,除了一个奇怪的问题。在函数inpALT()和INPTEM中输入输入时,它要求我输入两次输入,然后返回正确的值…:

def inpALT():
    alt = str(input("Enter altitude above altlevel, format 100M/F :"))
    if re.match(r'[0-9]*[mMfF]$', alt):
        return alt
    else:
        raise ValueError("Invalid Format")     

def inpTEMP():
    temp = str(input("Tempurature in format 70C/F :"))
    if re.match(r'[0-9]*[cCfF]$', temp):
    return temp
    else:
        raise ValueError("Invalid Format")


while True:
    try:
        inpALT()
        break
    except ValueError:("Invalid Format")      

while True:
    try:
        inpTEMP()
        break
    except ValueError:("Invalid Format")

temp = inpTEMP()
alt = inpALT()

---- snip ----
但是,只有在我必须输入两次数据后,它才会这样做:

输入海拔高度,格式为100M/F:100F

以70C/F格式输入温度:100F

以70C/F:100F的格式输入温度

输入海拔高度,格式为100M/F:100F


为什么会这样…?

这更多的是您在评论中得到的帮助的总结。我为您的具体问题提供了一个更正的代码。我已经对它进行了评论,所以我希望通过自己阅读和实现它,它会有很大帮助

我试图给你一个在
while循环中重构代码的想法。我不推荐提供的代码,但这不是重点。我不想太破坏你的编码风格。我把注意力集中在你提供的第二个代码上。对我来说,还不清楚我到底要去哪里

#!/usr/bin/env/python
# -*- coding: utf-8 -*-

"""corrected version with more PEP8 included."""

import re
import sys  # just for exit the script. There are multiple other ways.

# the assignments will be done later, no need for that here.
# alt = ""
# temp = ""


# readable names are better than cryptic ones
def get_altitude():
    alt = str(input("Enter altitude above sealevel, format 100M/F: "))

    # after `return` code will not be executed. You have to do it before the
    # return statement as mentioned by jojonas. Maybe you will also allow a
    # minus at the beginning and disallow no numbers (+ instead of *)?
    if not re.match(r'[0-9]*[mMfF]$', alt):
        raise ValueError

    return alt


# readable names are better than cryptic ones
def get_temperature():
    temp = str(input("Tempurature in format 70C/F: "))

    # the same here with the return statement
    if not re.match(r'[0-9]*[cCfF]$', temp):
        raise ValueError

    return temp


# The while loop stands for: do it forever. Maybe this is not what you want?!
# The user has to give a wrong input format (then sys.exit is your friend as
# one example of stopping the script or the user has to manually stop the
# script (STRG+C) or something like that. There are better ways.
while True:
    try:
        # you need to assign the returned values to a variable as mentioned
        # by jojonas already. Here is the way of doing it.
        alt = get_altitude()
        temp = get_temperature()

    # slight change in catching the error
    except ValueError:
        print('Invalid input format!')
        sys.exit(1)

    # finally will be done after exception occured! If you don't use
    # sys.exit (as I did as a fast hack not to totally disorder your
    # program), you have to be careful about this solution.
    finally:
        t = ''.join(x for x in temp if x.isdigit())
        a = ''.join(x for x in alt if x.isdigit())

        t = int(t)
        a = int(a)

        if "F" in temp:
            # just another way of expressing the same:
            t -= 32 / 1.8

        if "F" in alt:
            # just another way of expressing the same:
            a /= 3.3

        tPoint = 100 - a * 0.00552

        # just another way of expressing the same:
        if 0 - (int(tPoint)) < a < (100 - (int(tPoint))):
            print("Liquid")

        if a < (0 - int(tPoint)):
            print("Solid")

        if a > (100 - int(tPoint)):
            print("Gas")
#/usr/bin/env/python
#-*-编码:utf-8-*-
“”“包含更多PEP8的已更正版本。”“”
进口稀土
导入系统#仅用于退出脚本。还有很多其他的方法。
#作业将在以后完成,这里不需要。
#alt=“”
#temp=“”
#易读的名字比难懂的好
def get_高度()
alt=str(输入(“输入海平面以上的高度,格式100M/F:”)
#在“return”之后,将不执行代码。你必须在考试前做这件事
#jojonas提到的返回语句。也许你也会允许
#开始时为负数,不允许任何数字(+而不是*)?
如果没有重新匹配(r'[0-9]*[mMfF]$,alt):
升值误差
返回alt
#易读的名字比难懂的好
def get_温度():
temp=str(输入(“70C/F格式的温度:”)
#这里的return语句也是如此
如果没有重新匹配(r'[0-9]*[cCfF]$',临时):
升值误差
返回温度
#while循环代表:永远这样做。也许这不是你想要的?!
#用户必须给出错误的输入格式(那么sys.exit就是您的朋友)
#停止脚本或用户必须手动停止脚本的一个示例
#脚本(STRG+C)或类似的东西。有更好的方法。
尽管如此:
尝试:
#您需要将返回值分配给前面提到的变量
#已经是jojonas写的了。下面是做这件事的方法。
alt=获取高度()
温度=获取温度()
#捕捉错误时的细微变化
除值错误外:
打印('无效的输入格式!')
系统出口(1)
#最后将在异常发生后完成!如果您不使用
#sys.exit(正如我所做的那样,作为一个快速黑客,不要完全扰乱您的
#程序),您必须小心此解决方案。
最后:
t=''.join(如果x.isdigit(),则x代表temp中的x)
a=''.join(如果x.isdigit(),则x代表alt中的x)
t=int(t)
a=int(a)
如果温度为“F”:
#这只是表达相同观点的另一种方式:
t-=32/1.8
如果alt中的“F”:
#这只是表达相同观点的另一种方式:
a/=3.3
t点=100-a*0.00552
#这只是表达相同观点的另一种方式:
如果0-(int(tPoint))(100-int(tPoint)):
打印(“气体”)

我希望这会对您有所帮助。请询问是否仍有不清楚的地方。

要从函数中捕获返回值,必须将其分配给如下变量:
temp=inF()
。返回的值随后将存储在
temp
变量中。此外,正则表达式的匹配永远不会执行,因为您总是在执行行之前返回。我仍然有点迷茫——请您解释一下关于正则表达式不匹配的意思吗?这是因为“return”关键字起作用。它立即返回给定值并跳到调用函数的位置,“replacement”返回值的函数调用。好的,在我看到你的帖子之前,我刚刚重新构造了我的问题。非常感谢,这非常有效!哇,你刚刚救了我的救命恩人!我非常感谢你的详细评论和分解。我正试着学习python,非常感谢。有一件事——‘finally’又做了什么?你说在异常发生之后?异常不是我们正在捕获的错误吗?请参阅这篇文章,了解有关
的详细解释,请尝试…except…finally
。这里的finally只是因为sys.exit()而没有执行。不要在代码的这一部分给出太多。无论如何,我建议重构这一部分(正如我提到的)。