初学者 - 剧本识别" pi"和" e"并将它们转换为数字

时间:2017-02-03 09:09:31

标签: python

我对任何编码都是新手。

作为我的第一个小任务之一,我试图设计一个比较数字的程序。我想添加一个区分" pi"和" e"条目并将它们转换为相应的浮点数。但是,此功能无法正常工作。

# the user is prompted to insert a value. This will be stored `enter code here`as "input1"
input1=input("insert a number:")
# decide whether the input is a number or a word. Convert words `enter code here`into numbers:
def convert(pismeno):
    if pismeno == "pi":
    number=float(3.14)
    print ("word pi converted to number:", (number))
  elif pismeno == "e":
    number= float(2.71)
    print ("word e converted to number:", (number))
  else:
   number = float(pismeno)
    print (number, "is already a number. No need to convert.")
# call the convert function onto the input:
convert(input1)
print ("The number you chose is:",input1)*

我猜它与存储在函数内部的输出有关,而不是"泄漏"外面的一般代码。请记住,我几乎没有经验,所以坚持使用儿童语言,而不是通常的专业演讲。

2 个答案:

答案 0 :(得分:0)

如果您正在编写函数,则需要返回语句。代码的简化示例:

def convert(pismeno):
    if pismeno == "pi":
        number=float(3.14)
        print ("word pi converted to number:", number)
        return number
    else:
        ....

....
input1=input("insert a number:")
print(convert(input1))

我真的建议你学习编程的基本概念。你可以从这里开始:https://www.learnpython.org/。有关功能的更多信息:https://www.learnpython.org/en/Functions

答案 1 :(得分:0)

  

您选择的号码是:pi“而不是”您选择的号码是:3.14“

您当前的最终打印件只打印您最初提供的输入(input1

您需要提供一种从函数返回值的方法,然后将其设置为您调用它的变量

def convert(pismeno):
    ... Code ...    
    return number


# call the convert function onto the input:
output_num = convert(input1)
print ("The number you chose is:",output_num )