- #1
Sunwoo Bae
- 60
- 4
I want my output to read only the integers. Here's my attempt:
number = int(input())
for i in range(2, number+1, 2):
print(input())
number = int(input())
for i in range(2, number+1, 2):
print(input())
The first number indicates the number of strings in the sequence of inputs. It should be used to control a for loop that runs that many times, with pairs of input calls. For example, in your sample inputs, the first number entered indicates that three strings will be in the input sequence. Because the rest of the input values alternate between integers and strings, the loop body should do two inputs: the first to input a number and the second to input a string but not do anything with it.Sunwoo Bae said:Homework Statement: I have to print every other input.
Homework Equations: you are not given input to put in or the total number of input, but the input shows a total number of strings in the first line and the rest consists of alternation of string and integer.
for example, the input can be:
3
12
tiger
11
cats
10
dogs
I want my output to read only the integers. Here's my attempt:
number = int(input())
for i in range(2, number+1, 2):
print(input())
Number of strings: 3
12
Val: 12
tiger
11
Val: 11
cats
10
Val: 10
dogs
A for loop is a programming construct used to repeat a set of instructions for a specific number of times. It is often used for iterating over a collection of data or performing a task a certain number of times.
To print every other input in Python using a for loop, you can use the range function with a step of 2 to iterate over the input and print every other element. For example, you can use the code: for i in range(0, len(input), 2):
print(input[i])
The logic behind printing every other input using a for loop is to use the range function with a step of 2 to iterate over the input. This way, the loop will only iterate over every other element, and the print statement will only execute for those elements, resulting in every other input being printed.
Yes, it is possible to print every other input in reverse order using a for loop in Python. You can use the range function with a negative step (-2) to iterate over the input in reverse order and print every other element. For example, the code would be: for i in range(len(input)-1, -1, -2):
print(input[i])
Yes, there are other ways to print every other input in Python besides using a for loop. One alternative is to use list slicing, where you can specify the step in the slice to print every other element. For example, the code would be: print(input[::2])
Another way is to use the enumerate function to get the index of each element in the input and print only the elements with even indices. For example, the code would be: for index, element in enumerate(input):
if index % 2 == 0:
print(element)