- Joined
- Jan 27, 2022
- Messages
- 1
- Reaction score
- 0
code for this question in for loop
def generate_powers_of_two(n):
# Generates an array of powers of 2 to 2^n
return [2**i for i in range(n + 1)]
if __name__ == "__main__":
while True:
try:
n = int(input("Enter a number <n>: "))
if n < 0: raise ValueError
break
except ValueError:
print("The argument <n> must be a non-negative integer.")
print(f"Powers of 2 less than or equal to 2^{n}:")
print(generate_powers_of_two(n))
input("\nPress ENTER to exit.")
@echo off
setlocal enabledelayedexpansion
:input
set /p n="Enter a number <n>:"
if %n% lss 0 (
echo The argument <n> must be a non-negative integer.
goto input
)
set power=1
echo Powers of 2 less than or equal to "2^%n%":
for /L %%i in (0,1,%n%) do (
echo !power!
set /a power=power*2
)
echo.
pause
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.