if函数中的奇怪语句

时间:2018-09-02 13:18:31

标签: python python-3.x function

我从以下python函数获得了非常奇怪的输出:

s = "-8.8373347749999997e-08"
def roundNumb(numb, pos):
    print("roundNumb()", numb , pos)
    ret = ""
    if int(numb[pos]) < 5:
        ret = numb[:pos]
        print("if int(numb[pos]) < 5: ", int(numb[pos]), " ", ret)
    else:
        if int(numb[pos]) == 9:
            ret = roundNumb(numb , pos - 1)
            print("int(numb[pos]) == 9 ", int(numb[pos]), " ",ret)
        else:
            ret = numb[:(pos-1)] + str(int(numb[(pos-1)]) + 1)
            print("else:", ret)
    return ret


>>> roundNumb(s, 12)
roundNumb() -8.8373347749999997e-08 12
roundNumb() -8.8373347749999997e-08 11
if int(numb[pos]) < 5:  4   -8.83733477
int(numb[pos]) == 9  9   -8.83733477
'-8.83733477'

如您所见,roundNumb函数被调用了两次,但是我真的不明白为什么。它应首先在if语句上结束:

if int(numb[pos]) < 5:

1 个答案:

答案 0 :(得分:0)

您调用功能 var ttsSettingsViewController: TTSSettingsViewController! @IBOutlet weak var textBox: UITextView! var speechSynthesizer = AVSpeechSynthesizer() var speechUtterence : AVSpeechUtterance = AVSpeechUtterance(string: "") override func viewDidLoad() { super.viewDidLoad() let storyBoard: UIStoryboard = UIStoryboard(name: "TTS", bundle: nil) ttsSettingsViewController = storyBoard.instantiateViewController(withIdentifier: "TTSSettingsViewController") as! TTSSettingsViewController } @IBAction func didTapSpeech(_ sender: Any) { if let textBoxText = textBox.text{ speechUtterence = AVSpeechUtterance(string: textBoxText) speechUtterence.volume = ttsSettingsViewController.volume speechUtterence.pitchMultiplier = ttsSettingsViewController.pitch speechUtterence.rate = ttsSettingsViewController.rate speechSynthesizer.speak(speechUtterence) } }

然后功能转到else块 并执行if块

roundNumb(s, 12) // where numb[pos] = 9

这是在此之前感兴趣的部分,如果再次执行块,则再次调用此函数

if int(numb[pos]) == 9:

然后执行functoin如果您的功能块

ret = roundNumb(numb , pos - 1) // and herer is function execution pause

print("int(numb[pos]) == 9 ", int(numb[pos]), " ",ret)

然后执行此打印功能,然后恢复已暂停的功能 然后执行此打印功能

if int(numb[pos]) < 5: ret = numb[:pos] print("if int(numb[pos]) < 5: ", int(numb[pos]), " ", ret)

有关递归的知识对于理解这一点很有帮助