python - 我的代码有问题。它输出“无”
问题描述
“内部”列表应该输出一系列“真”和“假”,但它为所有 10 个值输出“无”
import random
import math
random.seed(1)
def rand():
number = random.uniform(-1,1)
return number
print(rand())
def distance(x, y):
for a,b in x,y:
ans = math.sqrt((x[0] - y[0])**2 + (x[1] - y[1])**2)
return ans
print(distance((0, 0), (1, 1)))
def in_circle(x, origin=(0,0)):
print(distance(x, origin) <1)
print(in_circle((1,1))) # this is supposed to print only "false" but it prints "False" and "None"
R = 10
inside = [in_circle((rand(), rand())) for i in range(R)]
print(inside[:3])
请帮忙!
解决方案
您必须在函数内部使用 return 而不是 print 。这应该适合你:
import random
import math
random.seed(1)
def rand():
number = random.uniform(-1,1)
return number
print(rand())
def distance(x, y):
for a,b in x,y:
ans = math.sqrt((x[0] - y[0])**2 + (x[1] - y[1])**2)
return ans
print(distance((0, 0), (1, 1)))
def in_circle(x, origin=(0,0)):
return(distance(x, origin) <1)
print(in_circle((1,1))) # this is supposed to print only "false" but it prints "False" and "None"
R = 10
inside = [in_circle((rand(), rand())) for i in range(R)]
print(inside[:3])
推荐阅读
- java - javafx打开窗口没有效果。应用程序启动然后抛出类未找到
- python - 在火炬 IterableDataset 中改组的速度问题
- swift - 如何快速隐藏和取消隐藏具有高度的视图?
- javascript - 使用 Puppeteer 通过 HTTP Post 发送正文时的 JSON 解析器
- javascript - React-table 对包含两个值或符号的自定义渲染单元格进行排序
- python - 在 Python 3 中,变量类型的变量和不可变类型的变量
- reactjs - Create React App 显示“除非提供 '--jsx' 标志,否则无法使用 JSX”
- locale - gnome-terminal-server:不支持区域设置
- c++ - 是否有用于查找字符串中最长且不重复长度的子字符串的结构函数?
- angular8 - 如何在 CKEDITOR 5 angular 中为 pdf 文件创建自定义上传适配器