Итак, сначала это задача, которую я должен "Второй вызов кодирования будет использовать цикл while для решения обоих условий
При любом числе, называемом пределом, мы найдем и напечатаем все квадраты, которые равны или ниже предела, следовательно:
Учитывая 30 ваше первое решение будет печатать 1, 4, 9, 16, 25
второе решение будет печатать кубы до предела, поэтому:
Учитывая 30, ваше второе решение напечатает 1, 8, 2 "
reply = True
while reply == True:
limit = input("Choose any number ")
if limit.isnumeric():
limit = float(limit)
reply = False
else:
print("What you have entered is not a number")
reply = True
number = 1
square = list()
cube = list()
while number > 0:
squarenumber = number ** 2
if squarenumber > limit:
break
square.append(squarenumber)
cubenumber = number ** 3
if cubenumber > limit:
break
cube.append(cubenumber)
number = number+1
print("All the squares below or equal to",limit,"are",*square)
print("All the cubes below or equal to", limit,"are",*cube)
Это код, который я сделал, и когда я ставлю 30 как значение "limit", это говорит
All the squares below or equal to 30.0 are 1 4 9 16
All the cubes below or equal to 30.0 are 1 8 27
Поэтому я не совсем уверен, что я сделал неправильно
Проблема возникает, когда значение number
равно 4. В этом случае вычисляется квадрат, а условие 14 > 30
ложно (30 - limit
). Но затем вы переходите к вычислению куба, в этом случае условие 64 > 30
истинно и, следовательно, цикл прерывается. Таким образом, одним из способов является разрыв цикла только тогда, когда квадрат значения больше предела. Или вы также можете инвертировать условие (добавьте квадраты и кубы в список, если они меньше предела)
reply = True
while reply == True:
limit = input("Choose any number ")
if limit.isnumeric():
limit = float(limit)
reply = False
else:
print("What you have entered is not a number")
reply = True
number = 1
square = list()
cube = list()
while number > 0:
squarenumber = number ** 2
# only append the square if it is less than limit value
if squarenumber < limit:
square.append(squarenumber)
else:
break # if the square value is greater than limit, then stop the loop
cubenumber = number ** 3
# only append the cube if it is less than limit value
if cubenumber < limit:
cube.append(cubenumber)
number = number+1
print("All the squares below or equal to",limit,"are",*square)
print("All the cubes below or equal to", limit,"are",*cube)
Проверка squarenumber
и cubenumber
против предела не будет работать, поскольку кубики растут быстрее, чем квадраты. Лучшее решение - проверить следующий квадрат и собрать кубы.
Вот возможное решение
limit = 30
number = 1
square = list()
cube = list()
while number > 0:
squarenumber = number ** 2
square.append(squarenumber)
if (number+1) ** 2 > limit:
break
cubenumber = number ** 3
if cubenumber < limit:
cube.append(cubenumber)
number = number+1
print('square: {}'.format(square)) #square: [1, 4, 9, 16, 25]
print('cube: {}'.format(cube)) #cube: [1, 8, 27]
while reply == True:
- если выражение оценивается как логическое, вы не должны сравнивать егоTrue
илиFalse
в оператореwhile
, просто напишите вwhile reply: