How to stop the list, missing number from user enter - python

I'm doing this exercise:
In your main function, you need to keep asking user to enter an
integer, then store those integers in a list. Once the user decides to
stop entering, the function should print out all the integers from the
list, and also find the largest number in that list. If the user did
not enter any number, you should print out “Your list is empty”.
I tried to code it but I got stuck on print "Your list is empty". I don't know where to put the statement.
And when the user enters the number, the list will come out missing the first number the user entered.
def main():
user_list = []
user_num = input('Enter an integer or enter x to stop: ')
while user_num != 'x':
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' :
user_list.append(user_num)
if user_list == []:
print('Your List is empty')
exit()
index = 0
while index < len(user_list):
user_list[index] = int(user_list[index])
index += 1
print ('Here is the list of the numberyou entered:')
print (*user_list, sep = '\n')
largest = max(user_list)
print ('The largest number in your listis: ',largest)
main()

Simple, change:
while user_num != 'x':
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' :
user_list.append(user_num)
if user_list == []:
print('Your List is empty')
exit()
To:
while True:
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' and user_num:
user_list.append(user_num)
elif not user_list:
print('Your List is empty')
exit()
else:
break
Here is the optimized code:
def main():
user_list = []
while True:
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' and user_num:
user_list.append(int(user_num))
elif not user_list:
print('Your List is empty')
exit()
else:
break
print ('Here is the list of the numbers you entered:')
print (*user_list, sep = '\n')
largest = max(user_list)
print ('The largest number in your list is: ', largest)
main()

if user_list == []:
print('Your List is empty')
exit()
You should write this portion outside the while loop. Like this
def main():
user_list = []
user_num = input('Enter an integer or enter x to stop: ')
while user_num != 'x':
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' :
user_list.append(user_num)
if user_list == []:
print('Your List is empty')

def main():
user_list = []
while True:
user_num = input('Enter an integer or enter x to stop: ')
if user_num == 'x':
break # exit the "while" loop
user_list.append(user_num)
# this is after the loop:
if user_list == []:
print('Your List is empty')
exit()
# user_list = list(map(int, user_list))
for index in range(len(user_list)): # range is a list-like thing of 0, 1, 2, 3... up to the length of the list
user_list[index] = int(user_list[index])
print ('Here is the list of numbers you entered:')
print (*user_list, sep='\n')
largest = max(user_list)
print ('The largest number in your lists: ', largest)
main()

Related

python program troubleshoot

if the user enters a char it should show the wrong input and continue asking for input until it reaches the range of 10 elements. how to solve this? output
list = []
even = 0
for x in range(10):
number = int(input("Enter a number: "))
list.append(number)
for y in list:
if y % 2 == 0:
even +=1
print("Number of even numbers: " ,even)
for y in list:
if y % 2 == 0:
count = list.index(y)
print("Index [",count,"]: ",y)
myList = []
while len(myList) < 10:
try:
number = int(input("Enter a number: "))
myList.append(number)
except ValueError:
print('Wrong value. Please enter a number.')
print(myList)
Hope code is self explanatory:
arr = []
even = 0
error_flag = False
for x in range(10):
entry = input("Enter a number: ")
if not entry.isdigit():
print("Entry is not a number")
error_flag = True
break
arr.append(int(entry))
if not error_flag:
brr = []
for id, y in enumerate(arr):
if y%2 == 0:
brr.append([id,y])
print(f"Even numbers are: {len(brr)}")
for z in brr:
print(f"Index{z[0]} is {z[1]}")
list = []
even_list=[]
c=0
for x in range(10):
number = (input("Enter a number: "))
list.append(number)
if number.isdigit()==False :
print("wrong input")
break
elif int(number)%2==0:
even_list.append(number)
if len(list)==10:
print("Number of even numbers: ",len(even_list))
for i in list:
i=int(i)
if (i) %2==0:
print("Index %d : %d" %(c,i)) # print("Index",c,":",i)
c=c+1

I have a problem with the return statement returning no value

I have some code that takes overlapping elements from two lists and creates a new one with these elements. there are two functions which check for a valid input, however, the return statement returns no value to the main function. Can someone help me?
This is the code:
import random
import sys
def try_again():
d = input("\nTry again? (y/n): ")
if d == 'y':
main_func()
elif d != 'y' and d != 'n':
print("Invalid entry")
try_again()
elif d == 'n':
sys.exit()
def first_list_test(length_a, range_a):
length_a = int(input("Enter the length of the first random list: "))
range_a = int(input("Enter the range of the first random list: "))
if length_a > range_a:
print("The length of the list must be greater than the range for unique elements to generate")
first_list_test(length_a, range_a)
else:
print("Length: " + str(length_a))
print("Range: " + str(range_a))
return length_a, range_a
def second_list_test(length_b, range_b):
length_b = int(input("Enter the length of the second random list: "))
range_b = int(input("Enter the range of the second random list: "))
if length_b > range_b:
print("The length of the list must be greater than the range for unique elements to generate")
second_list_test(length_b, range_b)
else:
print("Length: " + str(length_b))
print("Range: " + str(range_b))
return length_b, range_b
def main_func():
length_a = int()
range_a = int()
first_list_test(length_a, range_a)
print(length_a)
print(range_a)
print("\n")
length_b = int()
range_b = int()
second_list_test(length_b, range_b)
print(length_b)
print(range_b)
print("\n")
a = random.sample(range(1, range_a), length_a)
a.sort()
b = random.sample(range(1, range_b), length_b)
b.sort()
num = int()
print(a, "\n")
print(b, "\n")
c = []
d = []
for num in a:
if num in b:
c.append(num)
for test_num in c:
if test_num not in d:
d.append(test_num)
d.sort()
if len(d) == 0:
print("No matches found")
else:
print("Overlapping elements: ")
print(d)
try_again()
main_func()

Python 3-Returning a recursive value from a choice option and

I am having a touch of difficulty in getting my values to display using recursive methods. I am wanting to type in 10 numbers and, depending on the choice, will return the largest number, the smallest number, and the sum of the numbers. I am getting two errors: One is that the (len) cannot return an int and if I put in a value in the individual function, it will continue to loop until the program reaches it's parsing limit (999). I am not sure how to proceed and get the values I want and it seems to be a main issue with the values I put in. Any suggestions would be appreciated!
def displayMenu():
print('Enter 1 to find the largest number: ')
print('Enter 2 to find the smallest number: ')
print('Enter 3 to sum the list of numbers: ')
print('Enter 4 to exit: ')
choice = int(input('Please enter your choice: '))
while choice <= 0 or choice >= 5:
print('Enter 1 to find the largest number: ')
print('Enter 2 to find the smallest number: ')
print('Enter 3 to sum the list of numbers: ')
print('Enter 4 to exit: ')
choice = int(input('Please enter your choice: '))
else:
return choice
def main():
MIN = 1
MAX = 100
num_MAX = 10
user_num = []
number_list = []
for i in range(num_MAX):
user_num = int(input('Please enter a number at this time: '))
while user_num < 1 or user_num > 100:
user_num = int(input('Please re-enter numbers between 1 and 100:' ))
number_list.append(user_num)
choice = displayMenu()
while choice != 4:
if choice == 1:
largest = find_largest(user_num)
print('The largest number is: ', largest)
elif choice == 2:
smallest = find_smallest(user_num)
print('The smallest number is: ', smallest)
elif choice == 3:
summy = find_sum(user_num)
print('The sum of the numbers entered is: ', summy)
choice = displayMenu()
def find_largest(user_num):
n = len(user_num)
if n == 1:
return user_num[0]
else:
temp = find_largest(user_num[0:n - 1])
if user_num[n - 1] > temp:
return user_num[n - 1]
else:
return temp
def find_smallest(user_num):
n = len(user_num)
if n == 1:
return user_num [0]
else:
temp = find_smallest(user_num[0:n - 1])
if user_num[n - 1] < temp:
return user_num[n - 1]
else:
return temp
def find_sum(user_num):
user_num = [1,2,3,4]
n = len(user_num)
if len(user_num) == 1:
return user_num [0]
else:
return user_num[n - 1] + sum[0:n - 1]
main()

Python String Iteration/Functions

I need my 'items' variable to print each item on a new line. I keep getting a total in 'items' and the total in 'total'. The 'total' prints out how I want, but I want the items to print individually.
Thoughts?
def adding_report():
user_input = input("Report Types include All Items ('A') or Total Only ('T')\nChoose Report Type ('A'or'T'):")
items = "\n"
total = 0
while True:
if user_input == 'A'.lower():
user_input1 = input("Input an integer to add to the total or 'Q' to quit: ")
if user_input1.isdigit():
items = int(user_input1)
total += int(user_input1)
continue
elif user_input1 == 'Q'.lower():
print("Items\n", items)
print("Total\n", total)
break
elif user_input1.startswith('q'):
print('Items\n', int(items))
print("Total\n", total)
break
else:
print("Input is not valid")
elif user_input == 'T'.lower():
user_input2 = input("Input an integer to add the total or 'Q' to quit: ")
adding_report()
user_input = raw_input("Report Types include All Items ('A') or Total Only ('T')\nChoose Report Type ('A'or'T'):")
items=[]
total = 0
print user_input
total = 0
while True:
user_input1 = raw_input("Input an integer to add to the total or 'Q' to quit: ")
if user_input == 'A'.lower() or user_input == "A":
if user_input1.isdigit():
items.append(int(user_input1))
total += int(user_input1)
continue
elif user_input1 == 'Q'.lower() or user_input1 =="Q" or user_input1.startswith('q'):
print "List of items is"
for item in items:
print item
print "Total ", total
break
else:
print("Input is not valid")
elif user_input == 'T'.lower() or user_input == "T":
if user_input1.isdigit():
items.append(int(user_input1))
total += int(user_input1)
continue
elif user_input1 == 'Q'.lower() or user_input1 =="Q" or user_input1.startswith('q'):
print "Total ",total
break
else:
print("Input is not valid")
Here is a modified code. It is hard to exactly understand what your script is supposed to do:
import textwrap # nice library to format text inside functions
def adding_report():
# initiate variables
total = 0
items = 0
# Make sure you get the right input
while True:
user_input = input(textwrap.dedent("""\
Report Types include All Items ('A') or Total Only ('T')
Choose Report Type ('A'or'T'):"""))
if user_input list("AT"):
break
# Create a loop where you ask the user for input
# Q or q quits (the print is outside the function)
while True:
user_input1 = input("Input an integer to add to the total or 'Q' to quit: ")
if user_input1.lower() == 'q':
break
if user_input1.isdigit():
if user_input == 'A':
items = int(user_input1)
total += int(user_input1)
elif user_input == 'T':
total += int(user_input1)
else:
print("Input is not valid")
# Return variables
return items,total
items,total = adding_report()
print("Items\n", items)
print("Total\n", total)
Here's my attempt at understanding what you trying to do:
print("Report Types includes All Items ('A') or Total Only ('T')")
report_type_raw = input("Choose Report Type ('A' or 'T'): ")
report_type = report_type_raw.lower()
if report_type in 'at':
items = []
total = 0
user_input = ''
while user_input != 'q':
user_input_raw = input("Input an integer to add to the total or 'Q' to quit: ")
if user_input_raw.isdigit():
current_item = int(user_input_raw)
if report_type == 'a':
items.append(user_input_raw)
total += current_item
user_input = ''
else:
user_input = user_input_raw.lower()
if user_input != 'q':
print("Input is not valid")
if report_type == 'a':
how_items_to_be_printed = ', '.join(items)
print("Items :", how_items_to_be_printed)
print("Total :", total)
else:
print("Report type is not valid")
Otherwise you'll have to clarify what you were trying to do.

Append Values from input to a sublist in Python

I am trying to append values from an input to sublists in a list.
Each number of Student and name should be in a sublist.
ex:
[[123,John],[124,Andrew]]
Where the outside list would be the number of students, and the sublists , the info of the students..
Here is what my code looks like:
listStudents = [[] for _ in range(3)]
infoStudent = [[]]
while True:
choice = int(input("1- Register Student 0- Exit"))
cont = 0
if choice == 1:
snumber = str(input("Student number: "))
infoStudent[cont].append(str(snumber))
name = str(input("Name : "))
infoStudent[cont].append(str(name))
cont+=1
listStudents.append(infoStudent)
if choice == 0:
print("END")
break
print(listStudents)
print(infoStudent)
If I put on the first loop, snumber = 123 , name = john , and snumber = 124, name = andrew on the second time it will show me : [[123,john,124,andrew]] instead of [[123,john], [124,andrew]].
Your code can be greatly simplified:
You don't need to pre-allocate the lists and sublists. Just have one list, and append the sublists as you receive inputs.
You don't need to cast user input from input to strings, as they are strings already.
Here's the modified code:
listStudents = []
while True:
choice = int(input('1- Register Student 0- Exit'))
if choice == 1:
snumber = input('Student number: ')
name = input('Name : ')
listStudents.append([snumber, name])
if choice == 0:
print('END')
break
print(listStudents)
Your code can be more pythonic and can make use of some basic error handling as well. Create the inner list inside the while loop and simply append to the outer student list. This should work.
students = []
while True:
try:
choice = int(input("1- Register Student 0- Exit"))
except ValueError:
print("Invalid Option Entered")
continue
if choice not in (1, 9):
print("Invalid Option Entered")
continue
if choice == 1:
snumber = str(input("Student number: "))
name = str(input("Name : "))
students.append([snumber, name])
elif choice == 0:
print("END")
break
print(students)

Categories