Second input take " " without me choosing it [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
My code is just this :
x = int(input("Enter a number: "))
y = int(input("Enter a second number: "))
print('The sum of ', x, ' and ', y, ' is ', x+y, '.', sep='')
I get this error when i enter any number :
Enter a number:15
Enter a second number: Traceback (most recent call last):
File "C:/Users/mgt4/PycharmProjects/Beamy/test.py", line 5, in <module>
y = int(input("Enter a second number: "))
ValueError: invalid literal for int() with base 10: ''
I understand that it thinks the second number entered is a space but I don't know why and how i can fix this.

int(input("whatever")) will indeed raise a ValueError if input() returns something that can not be interpreted as an int. As a general rule, you should never trust user inputs (wherever they come from - input(), command line arguments, sys.stdin, text files, HTTP request, whatever) and always sanitize and validate them.
For your use case, you want a wrapper function around the int(input(...)) call:
def asknum(q):
while True:
raw = input(q)
try:
return int(raw.strip())
except ValueError:
print("'{}' is not a valid integer".format(raw)
num1 = asknum("enter an integer")
You could make it a bit more generic by providing a validation function instead:
def ask(q, validate):
while True:
raw = input(q)
try:
return validate(raw.strip())
except ValueError as e:
print(e)
And in this case you can simply use the int type as validation function:
num1 = ask("enter an integer", int)

Try to transform your code more generic:
REPEATS = 2
counter = 1
values = []
while True:
value = raw_input("Enter number {}: ".format(counter))
try:
number = int(value)
except ValueError:
print("Entered value '{}' isn't a number".format(value))
continue
counter += 1
values.append(number)
if counter > REPEATS:
break
print('The sum of values {} is {}'.format(", ".join([str(v) for v in values]), sum(values)))
Where REPEATS will be number of added values.
Example of output:
Enter number 1: 56
Enter number 2: 88
The sum of values 56, 88 is 144

Related

Dealing with two cases when a condition is met? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
If the number variable is an integer, an input that is equal to zero should become 'None' and any other value should stay as is. The code below works but for learning purposes I would like to see how this can be achieved differently?
while True:
try:
number = int(input('Type an integer: '))
if type(number) == int: # If the value is an integer, it proceeds.
if number == 0: # Here is another 'if' in case the value is zero which has to turn to the 'None' value
number = None
break
else: # For any other case it should just keep the value from the input above
break
except ValueError:
print("Type an integer")
print(number)
Try
number = number if number != 0 else None
Therefore the complete loop might look like:
while True:
try:
number = int(input('Type an integer: '))
print(number if number != 0 else None)
except ValueError:
print("Type an integer")
No need to check for the type(number) == int because you already passed it to int, which did not raise a ValueError. If this line of code is reached, it must be an int already at this point.
Breaking logic is often hard to follow. IMO this logic would be better suited to a method where you return it, making it more clear what the result of the loop will eventually be.
The prompt for incorrect text is confusing, you should comment that it was incorrect.
The return logic could use an if/else expression to reduce the code.
def ask_for_int():
while True:
try:
number = int(input('Type an integer: '))
return None if number == 0 else number
except ValueError:
print("Invalid input. Try again")
print(ask_for_int())

I am getting a ValueError for the line 4 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Getting value error on code line 4.
n = int(input("enter number of students: "))
list1=[]
for i in range(0,n):
ele=int(input("enter the score of the student: "))
list1.append(ele)
list1.sort()
print("the runner up is: ", list1[-2])
It might have happened because you have accidently provided a character value that cannot be converted to int. So in line 4 you are getting ValueError. Another possible reason is you have used a decimal point number as input. A decimal number of str type cannot be converted to int type. So either use a float or use try and except to handle the issue.
You need to add a validation for your code and so try this:
n = int(input("enter number of students: "))
list1=[]
counter = 0
while counter != n:
try:
ele=int(input("enter the score of the student: "))
list1.append(ele)
counter += 1
except ValueError:
print("Your input should be a number!")
list1.sort()
try:
print("the runner up is: ", list1[-2])
except:
print("You should at least have two scores!")

Why won't this while loop exit after a "0" is entered? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am trying to insert user input into a list until the user enters '0'. Right now, it won't exit out of the while loop once I enter 0.
Here's my code:
num_array = []
inputnum = raw_input('Please enter a number: ')
num_array.append(inputnum)
while inputnum != 0:
inputnum = raw_input('Please enter a number: ')
num_array.append(inputnum)
for i in range(len(num_array) - 1):
print(num_array[i] + ' + ')
print(num_array[total - 1] + ' = ' + sum(num_array))
Try check:
num_array = []
# raw_input return value as string,int convert it to string.
inputnum = int(raw_input('Please enter a number: '))
num_array.append(inputnum)
# earlier check for string '0' to interger 0 so the condition returned true but now int() converted inputnum to integer.
while inputnum != 0:
inputnum = int(raw_input('Please enter a number: '))
num_array.append(inputnum)
for i in range(len(num_array) - 1):
print("%d +" % num_array[i])
# sum() gave exception because earlier num_array had string type but int() converted all the value to integer.
print("%d = %d" % (num_array[len(num_array) - 1],sum(num_array)))
Try using
while inputnum != '0':
because the raw_input function returns a string, not integer. However, if your input_num needs to be an integer then follow the above solution.

List - int comparatives [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Here I am trying to get an input from the user which is added to a list, then the list must be validated before I run it through another function. I know that I need to change something for the comparative to work: can only be used with integers and the input in the list will be a string. Also there is an error that says "unorderable types: str() > int(). How do I get around this ?
def strInput():
string = []
string = str(input("Please enter numbers from 1-999... "))
if validate(string):
return string
else:
strInput()
def validate(i):
if i > 0 and i <= 999:
return True
else:
strInput()
I suppose you want to collect a list of numbers. The code below will do the trick
def validate(userInput):
return userInput.isdigit() and int(userInput) > 0 and int(userInput) <= 999
def getListOfNumbers():
listOfNumbers = []
while True:
userInput = raw_input("Please enter a number from 1 to 999. Enter 0 to finish input: ")
if userInput == '0':
return listOfNumbers
elif validate(userInput):
listOfNumbers.append(int(userInput))
#optional
else:
continue
myList = getListOfNumbers()
print myList
it should be: either do this:
if int(i) > 0 and int(i) <= 999:
if you in python 3 input takes input as string
or do this:
string = int(input("Please enter numbers from 1-999... "))
I hope it helps
def validate(i):
try:
num = int(i)
except:
return False
return num > 0 and num <= 999
def strInput():
string = str(input("Please enter numbers from 1-999... "))
if validate(string):
return string
else:
return strInput()
strings = []
strings.append(strInput())
strings.append(strInput())
print (strings)
prints out
Please enter numbers from 1-999... 1
Please enter numbers from 1-999... a
Please enter numbers from 1-999... 2
['1', '2']
You just need to convert the string into a integer. Try:
def validate(i):
if i.isdigit() and int(i) > 0 and int(i) <= 999:
return True
else:
strInput()

How do I write a function that repeatedly prompts the user for a number and then average the numbers? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm pretty new to programming, and I have no idea how to go about this.
Basically I need a function that repeatedly prompts a user to input an integer until they enter a non-numerical characters, then it takes the numbers and averages them.
This what I have so far, the ave function is to average the numbers, that's not the problem
def ioAve():
L = input("Enter your number: ")
if L == int:
print(L)
if L != int:
ave(L)
The program doesn't return anything at all.
This is probably the most pythonic way I can think of to solve this. Your approach of checking if an entered number is of a certain type is less desirable than catching the exceptions that might be raised when trying to convert (e.g. in this case a ValueError is raised when an invalid value is passed to int() ). You can learn more about exceptions in Python at the Python wiki.
The solution below also uses a list, which is an object that can contain multiple values. You can learn more about lists at effbot.org.
numbers = list()
while True:
try:
number = int(input("Enter a number: "))
numbers.append(number)
except ValueError:
break
print ("The average is", sum(numbers) / len(numbers))
cont = True
nums = []
while cont:
entered = input("Enter a number: ")
cont = all(char.isdigit() for char in entered)
if cont:
nums.append(int(entered))
print("The average is:", sum(nums)/len(nums))
Something like this:
print('Average: ',(lambda x:sum(x)/len(x))
([x for x in iter(lambda:(lambda x:int(x)
if x and all(x.isdigit() for x in x)else
...)(input('Enter a number: ')),...)]))
Sorry, I couldn't resist.
Something like this maybe. I'm sure there is a more pythonic way thou.
#import sys instead of using sys for program termination
def main():
sum = 0
iterations = 0
while True:
try:
num = int(raw_input("Input an integer: "))
iterations += 1
sum += num
except:
print "Average: "+str(sum//iterations)
#sys.exit() use break to "jump" out of an infinite loop
break
if __name__ == "__main__":
main()

Categories

Resources