python - 代码只正确运行了一半,并且在 f_num=num+num_rev 点处,这里输出只有 num_rev 而不是 f_num

标签 python

我有一个任务,从用户那里获取一个数字,将其反转并添加到用户给定的数字,然后检查总和是否是回文。

我已经编写了代码,但我卡在 5 处。首先,f_num=num+num_rev 不起作用,f_num 的答案是 321,这是给定输入为 123 时的 num_rev。添加不起作用,之后一切都无法正常工作。

while True:
    while True:
        try:
            num = int(input('\nEnter number:'))
        except ValueError:
            print("\nPlease enter only number")
        num_rev = 0
        while num > 0:
            dig = num %10
            num_rev = (num_rev *10) + dig
            num = num //10
        print("\nThe reverse of given number is {}.".format(num_rev))
        f_num=num+num_rev
        print("\nAfter adding the reverse number in given number,the sum is {}.".format(f_num))
        a_num_rev=0
        while f_num > 0:
            dig = f_num % 10
            a_num_rev = (a_num_rev *10) + dig
            f_num = f_num //10
        if f_num==a_num_rev:
            print("\nThe number {} is palindrome.".format(f_num))
            break
        else:
            print("\nThe number {} is not palindrome.".format(f_num))

    while True:
        Repeat=input("\nDo you want to repeat?\n\nYes or No:")
        Repeat=Repeat.lower()
        if Repeat not in ["yes","y","no","n"]:
            print("\nPlease select correct option")
        else:
            break

    if Repeat in ["yes","y"]:
        continue
    else:
        if Repeat in ["no","n"]:
            print("\n-----Thank you for using-----")
            input()
            break

最佳答案

反转从用户处获得的数字的过程会破坏原始值,因此当您尝试将原始值和反转值相加时,最终只会得到反转值作为总和(原始值为零)。

为了使代码正常工作,您需要保留一个具有 num 原始值的变量,以便稍后使用。像 num_orig = num 这样的行就足够了。然后在进行加法时使用该变量:f_num = num_orig + num_rev。或者,也许您可​​以重命名一些内容并对额外的变量进行破坏性修改,同时 num 保留原始值。

当您检查 f_num 以查看它是否等于其自身的反转时,您也会遇到类似的问题。当您计算a_num_rev时,您会销毁f_num(将其变成零)。

关于python - 代码只正确运行了一半,并且在 f_num=num+num_rev 点处,这里输出只有 num_rev 而不是 f_num,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56819253/

相关文章:

python - 使用python从Excel文件中提取图像

python - openai.error.InvalidRequestError : Engine not found

python - 在 gtk.ToolButton 中显示 gtk.Spinner

python - 如何将字典键值对转换为元组

python - 使用 python 对 beautifulsoup 标签列表进行排序

python - 使用基于列表列表中的项目的键创建 Python 字典

python - PySide.QtGui RuntimeError : '__init__' method of object's base class not called . ..但它是

python - 在 python 或 Spark 中获取大数据缺失值的最快方法是什么?

python - 使用 TF Estimator 时 Tensorflow 分布式训练的损失和学习率缩放策略

python - Linux、Python打开终端运行全局python命令