130k views
1 vote
Write a program that asks the user how many numbers will be entered and then has the user enter those numbers. When this is done, report to the user the position of the first 7 entered and the last 7 entered. By position we mean, for example, that if the first 7 is the 2nd number entered then its position would be 2.

User L Co
by
7.8k points

1 Answer

1 vote

Answer:

The program written in Python 3 is as follows;

The program does not make use of comments; however, see explanation section for detailed line by line explanation of the program

num = int(input("Number of Inputs: "))

mylist = []

userinput = int(input("Enter a digit: "))

i = 1

while i < num:

mylist.append(userinput)

userinput = int(input("Enter a digit: "))

i += 1

try:

first7 = mylist.index(7)+1

print('The first position of 7 is ',first7)

last7 = num - 1 - mylist[::-1].index(7)

print('The last position of 7 is ',last7)

except:

print('7 is not on the list')

Step-by-step explanation:

This line prompts user for the number of inputs

num = int(input("Number of Inputs: "))

This line declares an empty list

mylist = []

This line inputs the first number into the empty list

userinput = int(input("Enter a digit: "))

The italicized lines represent an iteration that allows user to input the numbers into the empty list.

i = 1

while i < num:

mylist.append(userinput)

userinput = int(input("Enter a digit: "))

i += 1

The try-except is used to check the presence of 7 in the list

try:

This checks the first occurrence of 7

first7 = mylist.index(7)+1

This prints the first occurrence of 7

print('The first position of 7 is ',first7)

This checks the last occurrence of 7

last7 = num - 1 - mylist[::-1].index(7)

This prints the last occurrence of 7

print('The last position of 7 is ',last7)

The following is executed if there's no occurrence of 7

except:

print('7 is not on the list')

See Attachments for sample runs

Write a program that asks the user how many numbers will be entered and then has the-example-1
Write a program that asks the user how many numbers will be entered and then has the-example-2
User Lokesh Tiwari
by
7.7k points