So my task is simple: I am to make two functions,
one which takes input from a user as a list of integers. (User enters how many entries, then begins entering them individually)
second function reads that list and returns how many times a chosen value was found in that list.
For some reason when combining these functions, the count does not stay at 0 and count whenever x is seen in the list; it just jumps to whatever the initial entry count was.
code is as follows:
def get_int_list_from_user():
list1 = []
numNums = int(input("Enter number count: "))
for x in range(numNums):
nextval = int(input("Enter a whole number: "))
list1.append(nextval)
return list1
def count_target_in_list(int_list):
target_val = int(input("Enter target value: "))
count = 0
for target_val in int_list:
count = 1
print("Target counted ", count, "time(s)")
return count
Over here is where I've tried different ways of calling the functions, but each time just ends up with the same result.
list1 = my_functions.get_int_list_from_user()
count = my_functions.count_target_in_list(int_list=list1)
I also tried this:
my_functions.count_target_in_list(int_list=my_functions.get_int_list_from_user())
CodePudding user response:
This statement does not do what you think it does:
for target_val in int_list:
That essentially erases the original value passed into the function, and instead runs through the whole list, one element at a time. So, count
will always be equal to the length of the list. You wanted:
for val in int_list:
if val == target_val:
count = 1
CodePudding user response:
def count_target_in_list(int_list):
target_val = int(input("Enter target value: "))
count = 0
for target_val in int_list:
count = 1
print("Target counted ", count, "time(s)")
return count
instead, using this logic, you need to compare the loop values with the target value. in the code above the target value will be overridden by the iteration of the loop.
def count_target_in_list(int_list):
target_val = int(input("Enter target value: "))
count = 0
for value in int_list:
if target_val == value :
count = 1
print("Target counted ", count, "time(s)")
return count
CodePudding user response:
Have Edited the answer
def get_int_list_from_user():
list1 = []
numNums = int(input("Enter number count: "))
for x in range(numNums):
nextval = int(input("Enter a whole number: "))
list1.append(nextval)
return list1
def count_target_in_list(int_list):
target_val = int(input("Enter target value: "))
count = 0
for target_val in int_list:
if target_val in int_list:
count = 1
print("Target counted ", count, "time(s)")
return count
list1 = get_int_list_from_user()
count = count_target_in_list(int_list=list1)
Gives
Enter number count: 3
Enter a whole number: 1
Enter a whole number: 2
Enter a whole number: 3
Enter target value: 2
Target counted 1 time(s)
Enter number count: 3
Enter a whole number: 1
Enter a whole number: 1
Enter a whole number: 1
Enter target value: 1
Target counted 3 time(s)