Return & 在 Python 中的函数外部调用变量...这里有什么问题吗?

Return & Call Variables Outside Functions in Python... What's Wrong here?

我讨厌问重复的问题,但我整天都在研究和研究这个程序,但运气不佳。它应该在 Cel 中测量水的温度。或 Far.,以及以英尺或米为单位的高度,并告诉您在给定的高度,水是液态、气态还是固态(不考虑大气压,我只是想根据在高度上)。经验法则是,水沸腾的温度比 100 摄氏度低约 1 度。海拔每升高 300 米(或 1000 英尺)。

我设法找到了一些方法使它 return 成为一个大致正确的数字。下一步是向程序中添加错误检查。我尝试了 'try' 子句,但它没有捕捉到错误,我终究无法弄清楚原因。

编辑

我尝试了一种不同的方法,它起作用了,捕获了错误,除了一个奇怪的问题。当在函数 inpALT() 和 inpTEMP 中输入输入时,它要求我输入两次,而不是 returns 正确的值...:

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

但是,只有在我必须输入数据 两次:

之后才会这样做

Enter altitude above altlevel, format 100M/F :100F

Enter Temperature in format 70C/F :100F

Enter Tempurature in format 70C/F :100F

Enter altitude above altlevel, format 100M/F :100F

为什么要这样做...?

这是您在评论中获得的帮助的总结。我为您提供了针对您的特定问题的更正代码。我已经评论过了,所以我希望它能对你自己阅读和实现它有所帮助。

我试图给你一个在 while loop 中重构你的代码的想法。我不推荐提供的代码,但这不是这里的重点。我不想过多破坏您的编码风格。我专注于您提供的第二个代码。对我来说,我不清楚我必须去哪里。

#!/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")

希望对您有所帮助。有什么不明白的请追问