can you help me with this? Tried the below code but doesn't work. I'm trying to print out the attached output. Thanks in advance.
num_display = int(input('Please enter how many numbers you would like displayed: '))
inc_value = int(input('Please enter the increment value: '))
num_counter = 1
num_sequence = range(1, num_display 1 , inc_value)
value_counter = range(1, num_counter, inc_value)
for each_num in num_sequence:
print(f'Counter: {num_counter} value: {each_num}')
num_counter = num_counter 1
value_counter = value_counter 1
print("Bye.")
What the output should look like
Please enter how many numbers you would like displayed: 12
Please enter the increment value: 3
Counter: 1 value: 1
Counter: 2 value: 4
Counter: 3 value: 7
Counter: 4 value: 10
Counter: 5 value: 13
Counter: 6 value: 16
Counter: 7 value: 19
Counter: 8 value: 22
Counter: 9 value: 25
Counter: 10 value: 28
Counter: 11 value: 31
Counter: 12 value: 34
Bye.
CodePudding user response:
There are a few problems with your code. range()
does increment the counter by inc_value
automatically after each iteration, so don't manually update that counter in your loop.
Additionally there is a mathematical problem. If you want to print a number num_display
times incremented by inc_value
the formula to calculate the the last number (and hence the end
value for range()
) is start_value inc_value * num_display
, not num_display 1
. In your case the start_value
is 1
and therefore irrelevant, so you can omit it.
To get the number of iterations in a pythonic way use enumerate()
.
num_display = int(input('Please enter how many numbers you would like displayed: '))
inc_value = int(input('Please enter the increment value: '))
num_sequence = range(1, num_display * inc_value, inc_value)
for num_counter, each_num in enumerate(num_sequence):
print(f'Counter: {num_counter 1} value: {each_num}')
print("Bye.")
Expected output
Please enter how many numbers you would like displayed: 12
Please enter the increment value: 3
Counter: 1 value: 1
Counter: 2 value: 4
Counter: 3 value: 7
Counter: 4 value: 10
Counter: 5 value: 13
Counter: 6 value: 16
Counter: 7 value: 19
Counter: 8 value: 22
Counter: 9 value: 25
Counter: 10 value: 28
Counter: 11 value: 31
Counter: 12 value: 34
Bye.