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}')
Related
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!')
I am trying to get user input to store some numbers and print out the largest and smallest number. I need to have an except in my code that will print an error message then continue to print my numbers. The problem I am having is if I type a word like cat to get the error message, it also makes the word my largest number. I just want my error message followed by my 2 numbers
l = None
s = None
while True:
num = input('Enter your number')
if num == 'done':
break
try:
num=float(num)
except:
print('Invalid input')
if l is None:
l = num
elif num > l:
l = num
if s is None:
s = num
if num < s:
s = num
print('Maximum is ',l)
print('Minimum is ',s)
any help will be great thanks alot
I would add a continue right after your print('invalid input'). That will make it start the loop again and ask for another number from the user.
I hope this is more clear:
numbers = [2, 3, 2]
total = 0
while numbers:
total += numbers.pop()
this will return the total valeu of numbers.
Now I must the total valeu of purchase__amount (first code) in this way (second code):
purchase_amount=[]
item=[]
while item != 'done':
item=input("Enter the price, or type 'done' to finnesh ", )
if item != 'done':
if item.isdigit():
purchase_amount.append(item)
else:
print('please type only numbers')
print(purchase_amount)
numbers = [purchase_amount]
total = 0
while numbers:
total += numbers.pop()
print(numbers)
With each atempt though I cant get the numbers from the input in the first code to become a float here and be addet in one number.
There are a few things wrong with your code. One of the main issues being that input returns a string, not a float.
You need to cast the input value from the user. The standard way to do is like so.
item = input("Enter the price, or type 'done'")
if item == 'done':
... # Likely break from your loop
try:
item = float(item)
except ValueError:
print('Invalid input')
The second critical issue is that numbers is a list of list, you should use purchase_amount instead.
Although, poping from the list is unnecessary here as you can simply loop over it or, even better, use sum.
Here is a fixed version of your code.
Fixed code
purchase_amount = []
while True:
item = input("Enter the price, or type 'done'")
if item == 'done':
break
try:
purchase_amount.append(float(item))
except ValueError:
print('Invalid input')
print(purchase_amount)
total = sum(purchase_amount)
print(total)
I am trying to find out how to make it so the user [only enters numbers <0] and [no letters] allowed. Can someone show me how I would set this up. I have tried to set up try/catch blocks but I keep getting errors.
edgeone = input("Enter the first edge of the triangle: ")
I think you want numbers only > 0, or do you want less than zero? Anyway to do this you can using try/except, inside a while loop.
For Python 3, which I think you are using?
goodnumber = False
while not goodnumber:
try:
edgeone = int(input('Enter the first edge of the triangle:'))
if edgeone > 0:
print('thats a good number, thanks')
goodnumber = True
else:
print('thats not a number greater than 0, try again please')
except ValueError:
print('Thats not a number, try again please')
hope this helps.
you must use except handler for this case :
try:
value = int(raw_input("Enter your number:"))
if not ( value < 0 ):
raise ValueError()
except ValueError:
print "you must enter a number <0 "
else:
print value #or something else
Also This question already has an answer here: Accepting only numbers as input in Python
You can do like this.
i = 1
while(type(i)!=float):
i=input("enter no.")
try:
int(i):
except:
try:
i = float(i)
except:
pass
print(i)
I've tried to write like:
print "Enter numbers, stops when negative value is entered:"
numbers = [input('value: ') for i in range(10)]
while numbers<0:
but suddenly, I lose my mind, and don't know what to do next
the example is:
Enter numbers, stops when negative value is entered:
value: 5
value: 9
value: 2
value: 4
value: 8
value: -1
Maximum is 9
It sounds like you want something along these lines:
def get_number():
num = 0
while True: # Loop until they enter a number
try:
# Get a string input from the user and try converting to an int
num = int(raw_input('value: '))
break
except ValueError:
# They gave us something that's not an integer - catch it and keep trying
"That's not a number!"
# Done looping, return our number
return num
print "Enter numbers, stops when negative value is entered:"
nums = []
num = get_number() # Initial number - they have to enter at least one (for sanity)
while num >= 0: # While we get positive numbers
# We start with the append so the negative number doesn't end up in the list
nums.append(num)
num = get_number()
print "Max is: {}".format(max(nums))
This is what you're looking for:
print "Enter numbers, stops when negative value is entered:"
nums = []
while True: # infinite loop
try: n = int(raw_input("Enter a number: ")) # raw_input returns a string, so convert to an integer
except ValueError:
n = -1
print "Not a number!"
if n < 0: break # when n is negative, break out of the loop
else: nums.append(n)
print "Maximum number: {}".format(max(nums))
I think you want something like this:
# Show the startup message
print "Enter numbers, stops when negative value is entered:"
# This is the list of numbers
numbers = []
# Loop continuously
while True:
try:
# Get the input and make it an integer
num = int(raw_input("value: "))
# If a ValueError is raised, it means input wasn't a number
except ValueError:
# Jump back to the top of the loop
continue
# Check if the input is positive
if num < 0:
# If we have got here, it means input was bad (negative)
# So, we break the loop
break
# If we have got here, it means input was good
# So, we append it to the list
numbers.append(num)
# Show the maximum number in the list
print "Maximum is", max(numbers)
Demo:
Enter numbers, stops when negative value is entered:
value: 5
value: 9
value: 2
value: 4
value: 8
value: -1
Maximum is 9