python - For 循环得到错误说 (odd number - odd number)/2 is a float

标签 python function for-loop

<分区>

我正在尝试制作一个函数,用奇数个星号(例如 1、3、5)制作金字塔

import math
baseInput = 0
while baseInput % 2 == 0:
    baseInput = int(input('Enter base length: '))
def drawPyramid(base):
    #makes variable for amount of asterisks that have to be drawn
    starcounter = 1
    for i in range(starcounter, base):
        #calculates number of spaces needed and prints them
        for i in range((base - starcounter + 1) // 2):
            print(' ', end='')
        #prints current amount of asterisks
        for i in range(starcounter):
            print('*', end='')
        print('\n')
        #increases amount of stars
        starcounter += 2
drawPyramid(baseInput - 1)

我认为这个输出会是:

  *
 ***
*****

相反,我收到一条错误消息

enter image description here

我不明白为什么 5 - 1 被认为是 float 。

最佳答案

I don't understand why 5 - 1 gets considered a float.

5 - 1 不是 float ,但 (5 - 1)/2 是。原因很简单:/ 除法运算符始终返回 float ,即使结果的小数部分为 0。

参见 https://docs.python.org/3/tutorial/introduction.html#using-python-as-a-calculator了解更多信息。

错误来自需要整数的 range 函数。

关于python - For 循环得到错误说 (odd number - odd number)/2 is a float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67331892/

相关文章:

python - 如何在 Django 中将 QuerySet 转换为列表?

php - 为每个 img 元素添加事件类

python - pyopencl.运行时错误: clBuildProgram failed: invalid build options

python - 将字符串转换为全部小写,无需内置函数

python - 关于在python中迭代函数的问题

c++ - 在单独的函数中创建一个动态数组并通过调用函数对其进行操作

python - 有谁知道内置函数 ord() 的缩写词?

for-loop - 如何从 Clojure 中的嵌套 for 循环生成一个惰性序列

Windows批处理在for循环中迭代 token

Python:返回元组或列表?