How to use the same code but with different variables - python

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)

Related

Data validation for multiple user inputs with Python

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!')

Break not Stopping Simple While Loop Python

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.

Assignment to a list function not working

I am trying to solve a simple problem. Enter three numbers and find the average of the largest two.
while True:
try:
n1 = int(input("Enter n1: "))
n2 = int(input("Enter n2: "))
n3 = int(input("Enter n3: "))
except ValueError:
print ("Enter an integer: ")
continue
else:
break
mylist = [n1,n2,n3]
mylist.remove(min(mylist))
print (float(sum(mylist))/2)
Why is this not working. If I remove the assignment n_avg and keep the last two lines of code as shown below it works. Can someone explain why?
mylist.remove(min(mylist))
print (float(sum(mylist))/2)
I wanted to share a slightly cleaner code.
mylist = []
while len(mylist) < 3:
try:
mylist.append(int(input("Enter a number:")))
except ValueError:
print ("Please enter an integer")
mylist.remove(min(mylist))
print (sum(mylist)/2.)
Works as expected.

Python: Continue if variable is an 'int' and has length >= 5

I have a piece of code that does some calculations with a user input number. I need a way to check if user entry is an integer and that entered number length is equal or more than 5 digits. If either one of conditions are False, return to entry. Here is what i got so far and its not working:
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "
If anyone has a solution, I'd appreciate it.
Thanks
This would be my solution
while True:
stringset = raw_input("Enter a number: ")
try:
number = int(stringset)
except ValueError:
print("Not a number")
else:
if len(stringset) >= 5:
break
else:
print("Re-enter number")
something like this would work
while True:
number = input('enter your number: ')
if len(number) >= 5 and number.isdigit():
break
else:
print('re-enter number')
Use this instead of your code
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5:
try:
val = int(userInput)
break
except ValueError:
print "Re-enter number:
else:
print "Re-enter number:
Do not use isdigit function if you want negative numbers too.
By default raw_input take string input and input take integer input.In order to get length of input number you can convert the number into string and then get length of it.
while True:
stringset = input("Enter number: ")
if len(str(stringset))>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "

Why doesn't the max() function run as it is expected?

numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(first_input)
while first_input:
input_numb = input("Write next number")
if input_numb == int():
numbers.append(input_numb)
elif input_numb == "done":
print("The largest number is "+max(numbers))
print("The smallest number is "+min(numbers))
break
Can someone look at this code and tell me what I did wrong please? After I put the input numbers I want to print the biggest and smallest number from the list numbers but I don't know why the max function does not return the biggest number, instead it returns the smallest one (just like the min function. Why?
numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(int(first_input))
while first_input:
input_numb = input("Write next number")
try:
numbers.append(int(input_numb))
except:
if input_numb == "done":
print("The largest number is ", max(numbers))
print("The smallest number is ", min(numbers))
break
else:
print('invalid input!')
out:
Write any number.When you are done just write "done":1
Write next numbera
invalid input!
Write next number2
Write next number3
Write next number6
Write next numberdone
The largest number is 6
The smallest number is 1
int() will return 0:
class int(x, base=10)
Return an integer object constructed from a number or string x, or
return 0 if no arguments are given.If x is a number, return x.__int__(). For floating point numbers, this truncates towards
zero.
In [7]: int() == 0 == False
Out[7]: True
you should use max in a list of number not a list of string, convert string to int before you append it to list
"The largest number is " + max(numbers)
return :
TypeError: Can't convert 'int' object to str implicitly, just use , to concate the string and int.
you should convert your inputs to integers using int(my_input) then add them to the list my_list.append(int(my_input)) and use the max or min functions max(my_list) after getting all the inputs from the user
numbers = []
user_input = input('Write any number.When you are done just write "done": ')
while user_input != "done":
try:
numbers.append(int(user_input))
user_input = input("Write next number : ")
except ValueError:
user_input = input("please enter a valid number : ")
print("The largest number is ", max(numbers))
print("The smallest number is ", min(numbers))

Categories

Resources