为什么我的平方函数不运行? [英] Why doesn't my squaring function run?

查看:74
本文介绍了为什么我的平方函数不运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定制作一个程序,将数字平方只是为了好玩.使用在线编译器,我输入了代码,发现没有错误;它不会运行,只会有一个空白的控制台条目.

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.

我的代码:

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输出:

Repl.it output:

推荐答案

请确保还调用函数:

def square():
    # your function body here

square()

但是在您的函数中,您在这里忽略了计算结果:

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

number*number

将结果分配给某些东西

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

但是,您没有电话号码. raw_input()返回一个 string ,因此您要先将其转换为数字:

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.

这篇关于为什么我的平方函数不运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆