I am creating a function for my python course that receives a list and returns the same list without the smallest number. However, I wanted to extend the function to ask the user for inputs to create the list after performing some data validations on the inputs.
I was able to validate the first input. However, I got stuck at the second data validation as I need to guarantee that the program should accept only integers in the list and throw and prompt the user again for every wrong input something like while not (type(number) == int) which breaks as soon as the user input matches an int.
How should I do this?
def smallest():
# This function asks the user for a list
# and returns the same list without the smallest number or numbers
list_range = 'Not a number'
list_created = []
while not (type(list_range) == int):
try:
list_range = int(input('Please enter the total number of elements for your list: '))
except:
print('Please provide a number!')
for number in range(1,list_range + 1):
try:
list_element = int(input('Please enter the value of the %d element: ' %number))
list_created.append(list_element)
except:
print('Please provide a number!')
smallest = min(list_created)
result = []
for num in list_created:
if num != smallest:
result.append(num)
return result
Thanks for the help in advance!
You could use a while loop until an int value is entered:
for number in range(1, list_range + 1):
while True:
list_element = input('Please enter the value of the %d element: ' % number)
try:
list_element = int(list_element)
list_created.append(list_element)
break
except ValueError:
print('Please provide a number!')
Related
Basic python learning:
I am asked to write a program that makes a list of 15 integer entries (size) the user inputs. For each input, the program should give the number of integers remaining to input. In the end, the program should list the 15 entries, and tell the user he is done.
With the code below, I get the list and the final report, but can't really figure out how to count down, print the remaining entries, and tell the user he is done.
my_list = []
for _ in range(15):
try:
my_list.append(int(input('Enter size: ')))
except ValueError:
print('The provided value must be an integer')
print(my_list)
One thing to figure out is "what to do if the user inputs something that is not a valid integer?" You can solve that by keeping asking the user for an input until it's a valid number.
You can do that using a while loop with a boolean variable:
good_int = False
while not good_int:
try:
num = int(input(f'Enter an integer: '))
good_int = True
except ValueError:
print('I said int, gorramit!!')
Now that we have that, there is a lot of approaches you can take here.
One of the interesting things a for loop can do is count backwards.
You can try:
my_list = []
for i in range(15, 0, -1):
good_int = False
while not good_int:
try:
my_list.append(int(input(f'Enter size for iteration {i}: ')))
good_int = True
except ValueError:
print('The provided value must be an integer')
print("Aight, you're done. This is the list:")
print(my_list)
Or... probably what is better, use a variable to store the number of tries (15) and don't consider a "valid try" until the user inputted a valid integer.
my_list = []
tries = 15
while tries > 0:
try:
my_list.append(int(input(f'Enter size for iteration {tries}: ')))
tries = tries - 1 # Or just tries -= 1
except ValueError:
print('The provided value must be an integer')
print("Aight, you're done. This is the list:")
print(my_list)
Since you don't want the loop to repeat a fixed number of times, but instead need it to repeat until you have 15 values, you should consider using a while instead of a for.
my_list = []
while len(my_list) < 15:
try:
my_list.append(int(input('Enter size: ')))
except ValueError:
print('The provided value must be an integer')
print(f'You are done: {my_list}')
It may be a good idea to inform the user how many values they still have to enter:
my_list = []
while len(my_list) < 15:
try:
my_list.append(int(input(f'Enter size ({15 - len(my_list)} left): ')))
except ValueError:
print('The provided value must be an integer')
print(f'You are done: {my_list}')
You're going to need to use a counter variable, which simply keeps track of the amount of numbers left for the program to receive. You will print it out after every input, and then subtract 1 from the variable. I added a check to make sure that we don't print out "You have to input 0 more numbers" since that isn't what we really want to do.
my_list = []
numbers_left = 15
for _ in range(15):
try:
my_list.append(int(input('Enter size: ')))
numbers_left = numbers_left - 1
if numbers_left != 0:
print("You have to input " + str(numbers_left) + " numbers to complete the program.")
except ValueError:
print('The provided value must be an integer')
print(my_list)
You can print with f strings and the deincrement the number for each for loop. I am not sure about the try and for loop isn't this better?
EDIT: Changed the for loop and gives errors on string vals.
my_list=[]
len_val=15
val=0
while val<len_val:
try:
my_list.append(int(input("Enter size:")))
val+=1
print(f"{(len_val-val)}to go!")
except ValueError:
print("Enter an integer")
print(len(my_list))
range(14, 0, -1) will do the job for you.
my_list = []
for i in range(14, 0, -1):
try:
my_list.append(int(input('Enter size: ')))
print(f'{i} to go')
except ValueError:
print('The provided value must be an integer')
print(my_list)
If you have ValueError during the execution. I would suggest using a while loop. Like this
my_list = []
size = 15
while len(my_list) < size:
try:
my_list.append(int(input(f'Enter size : ')))
print(f'{size-len(my_list)} to go')
except ValueError:
print('The provided value must be an integer')
print(f'You are done: {my_list}')
I want to make a code that allows me to check if the number I have entered is really a number and not a different character. Also, if it is a number, add its string to the list.
Something like this:
numbers = []
num1 = input("Enter the first number: ")
try:
check = int(num1)
numbers.append(num1)
print("The number {} has been added.".format(num1))
except ValueError:
print("Please, enter a number")
I have to do the same for several numbers, but the variables are different, like here:
num2 = input("Enter the next number: ")
try:
check = int(num2)
numbers.append(num2)
print("The number {} has been added.".format(num2))
except ValueError:
print("Please, enter a number")
Is there any way to create a code that does always the same process, but only changing the variable?
If you are trying to continue adding numbers without copying your code block over and over, try this:
#!/usr/bin/env python3
while len(numbers) < 5: #The five can be changed to any value for however many numbers you want in your list.
num2 = input("Enter the next number: ")
try:
check = int(num2)
numbers.append(num2)
print("The number {} has been added.".format(num2))
except ValueError:
print("Please, enter a number")
Hopefully this is helpful!
Create the list in a function (returning the list). Call the function with the number of integers required.
def get_ints(n):
result = []
while len(result) < n:
try:
v = int(input('Enter a number: '))
result.append(v)
print(f'Number {v} added')
except ValueError:
print('Integers only please')
return result
Thus, if you want a list of 5 numbers then:
list_of_numbers = get_ints(5)
I created a row of Fibonacci numbers. At the beginning is desired input the number to specify the size of Fibonacci series, in fact the size of the row. The number is required to be an integer number >=2.
The outcome is printing out all Fibonacci number until the last number of the row, with their respective indices within the row! After that it's required to take out a slice of the row, and the outcome is to print out all numbers within the slice with their respective indices.
I successfully mastered to exclude all values that do not fall within range specified, but however I had not succeed to exclude numbers and other inputs of undesired types, example would like to exclude float type of an input variable, and string type of an input variable.
I specified that undesirable types of an input variable are float and string! However it reports me an error! How to overcome that, or by another words how to specify the requirement to exclude a floating variable as well as string variable to not report me an error?
The code:
while True:
n = int(input('Please enter the size of Fibonacci row - positive integer number(N>=2)!'))
if n < 2:
print('This is not valid number! Please enter valid number as specified above!')
continue
elif type(n)==float: # this line is not working!
print('The number has to be an integer type, not float!')
continue
elif type(n)==str: # this line is not working!
print( 'The number has to be an integer type, not string!')
continue
else:
break
def __init__(self, first, last):
self.first = first
self.last = last
def __iter__(self):
return self
def fibonacci_numbers(n):
fibonacci_series = [0,1]
for i in range(2,n):
next_element = fibonacci_series[i-1] + fibonacci_series[i-2]
fibonacci_series.append(next_element)
return fibonacci_series
while True:
S = int(input('Enter starting number of your slice within Fibonacci row (N>=2):'))
if S>n:
print(f'Starting number can not be greater than {n}!')
continue
elif S<2:
print('Starting number can not be less than 2!')
continue
elif type(S)==float: # this line is not working!
print('The number can not be float type! It has to be an integer!')
continue
elif type(S)==str: # this line is not working!
print('Starting number can not be string! It has to be positive integer number greater than or equal to 2!')
continue
else:
break
while True:
E = int(input(f'Enter ending number of your slice within Fibonacci row(E>=2) and (E>={S}):'))
if E<S:
print('Ending number can not be less than starting number!')
continue
elif E>n:
print(f'Ending number can not be greater than {n}')
continue
elif E<2:
print('Ending number can not be greater than 2!')
continue
elif type(E)==float: # this line is not working!
print('Ending number can not be float type! It has to be an integer type!')
continue
elif type(E) ==str: # this line is not working!
print(f'Ending number can not be string! It has to be positive integer number greater than or equal to {S}')
continue
else:
break
print('Fibonacci numbers by index are following:')
for i, item in enumerate(fibonacci_numbers(n),start = 0):
print(i, item)
fibonacci_numbers1 = list(fibonacci_numbers(n))
print('Fibonacci numbers that are within your slice with their respective indices are following:')
for i, item in enumerate(fibonacci_numbers1[S:E], start = S):
print(i, item)
Solved :-) simply add try except block in ur code like the following:
while True:
try:
num = int(input("Enter an integer number: "))
break
except ValueError:
print("Invalid input. Please input integer only")
continue
print("num:", num)
upvote & check :-)
at the first line
n = int(input('Please enter the size of Fibonacci row - positive integer number(N>=2)!'))
you're converting the input to int, so whatever the user provides it will be converted to an int.
if you want your code to be working, replace it with this
n = input('Please enter the size of Fibonacci row - positive integer number(N>=2)!')
Use an try/except/else to test the input. int() raises a ValueError if a string value isn't strictly an integer.
>>> while True:
... s = input('Enter an integer: ')
... try:
... n = int(s)
... except ValueError:
... print('invalid')
... else:
... break
...
Enter an integer: 12a
invalid
Enter an integer: 1.
invalid
Enter an integer: 1.5
invalid
Enter an integer: 1+2j
invalid
Enter an integer: 5
>>>
If you need to check type, isinstance is usually better, e. g.:
if isinstance(var, int) or isinstance(var, str):
pass # do something here
Python noob here. I am trying to create a list with numbers a user inputs and then do some simple calculations with the numbers in the list at the end, in a while loop. The While loop is not breaking when 'done' is inputted. It just prints 'Invalid input.'
list = []
while True:
try:
n = int(input('Enter a number: '))
list.append(n)
except:
print('Invalid input')
if n == 'done':
break
print(sum.list())
print(len.list())
print(mean.list())
You will have to separate receiving user input with checking against "done" from conversion to a number and appending to the list. And you will have to check for "done" before converting the input to an integer.
Try something like this:
list_of_numbers = []
while True:
user_input = input("Enter a number or 'done' to end: ")
if user_input == "done":
break
try:
number = int(user_input)
except ValueError:
print("invalid number")
continue
list_of_numbers.append(number)
print(list_of_numbers)
# further processing of the list here
This is because the int() function is trying to convert your input into an integer, but it is raising an error because the string 'done' can not be converted to an integer. Another point is that sum(), mean() and len() are functions, not attributes of lists. Also mean() is not a built in function in python, it must be import with numpy. Try it like this:
from numpy import mean
list = []
while True:
try:
n = input('Enter a number: ')
list.append(int(n))
except:
if n!='done':
print('Invalid input')
if n == 'done':
break
print(sum(list))
print(len(list))
print(mean(list))
You must check if you can turn the input into a integer before appending to your list. You can use use the try/except to catch if the input variable is convertible to a integer. If it's not then you can check for done and exit.
list = []
while True:
n = input('Enter a number: ')
try:
n = int(n)
list.append(n)
except ValueError:
if n == 'done':
break
print('Invalid input')
total = sum(list)
length = len(list)
mean = total/length
print('sum:', total)
print('length:', length)
print('mean:', mean)
Example interaction
Enter a number: 12
Enter a number: 3
Enter a number: 4
Enter a number:
Invalid input
Enter a number: 5
Enter a number:
Invalid input
Enter a number: done
sum: 24
length: 4
mean: 6.0
If the user enters done, you will attempt to convert into an int, which will raise an exception that you then catch.
Instead, perform your check before attempting to convert it to an integer.
I'm trying to write a small program to calculate numbers from the user. There's also some conditions to check if the number is positive or the user just hits enter. For some reason, I can't get the data variable to convert into a float.
The error occurs on line 5 where I get the error "ValueError: could not convert string to float:" I've tried so many combinations now, and tried to search StackOverflow for the answer, but without any luck.
How can I convert the input into a float? Thanks in advance for any help!
sum = 0.0
while True:
data = float(input('Enter a number or just enter to quit: '))
if data < 0:
print("Sorry, no negative numbers!")
continue
elif data == "":
break
number = data
sum += data
print("The sum is", sum)
Instead of having the user press enter to quit, you can instead write:
sum = 0.0
while True:
data = float(input('Enter a number or "QUIT" to quit: '))
if data.upper() != "QUIT":
if data < 0:
print("Sorry, no negative numbers!")
continue
elif data == "":
break
number = data
sum += data
print("The sum is", sum)
You can't convert an empty string to a float.
Get the user's input, check if it's empty, and if it's not, then convert it to a float.
You can check if the data is empty before convert to float with this way:
sum = 0.0
while True:
data = input('Enter a number or just enter to quit: ')
if data != "":
data = float(data);
if data < 0:
print("Sorry, no negative numbers!")
continue
number = data
sum += data
print("The sum is", sum)
else:
print("impossible because data is empty")
You have to first check for the empty string and then convert it to float.
Also you might want to catch malformed user input.
sum = 0.0
while True:
answer = input('Enter a number or just enter to quit: ')
if not answer: # break if string was empty
break
else:
try:
number = float(data)
except ValueError: # Catch the error if user input is not a number
print('Could not read number')
continue
if number < 0:
print('Sorry, no negative numbers!')
continue
sum += data
print('The sum is', sum)
In python, empty things like '' compare like False, it's idiomatic to use this in comparisons with if not <variable> or if <variable>.
This also works for empty lists:
>>> not []
True
And for None
>>> not None
True
And pretty much everything else that could be described as empty or not defined like None: