Why doesn't my squaring function run?

放肆的年华 提交于 2019-12-20 07:56:27

问题


I decided to make a program that would square a number just for fun. Using an online compiler, I entered my code and from what I saw there were no errors; it wouldn't run it would just have a blank console entry.

My code:

import math

def square():
    number = raw_input("Please enter a number for me to square.")  
    number*number  
    print "Your answer is..."  
    print number  

Repl.it output:


回答1:


Do make sure you also call your function:

def square():
    # your function body here

square()

But in your function, you are ignoring the result of your calculation here:

number*number

Assign that result to something:

answer = number * number
print "Your answer is..."  
print answer  

You don't have a number, however. raw_input() returns a string, so you want to convert that to a number first:

number = int(number)

This assumes that the user actually entered something that can be converted to an integer; digits only, plus perhaps some whitespace and a + or - at the start. If you wanted to handle user errors gracefully here, take a look at Asking the user for input until they give a valid response for more advanced options.



来源:https://stackoverflow.com/questions/27253706/why-doesnt-my-squaring-function-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!