I am writing a code where the user inputs as many numbers as they want until they input Stop. Each input gets added to a list. I want the input to be integer so the inputs are able to be sorted correctly but then when 'Stop' is inputted an error message will be created. But if I make the input string then the numbers will be sorted incorrectly.
Here is the code:
Num_List = list()
Numbers = input('Enter a number: ')
Num_List.append(Numbers)
Num_B = False
while Num_B == False:
Numbers = input('Enter a number: ')
Num_List.append(Numbers)
if Numbers == 'Stop':
Num_List.remove('Stop')
Num_List = [i for i in Num_List if i is not '']
Num_List.sort(reverse=False)
sorted(Num_List)
print(Num_List)
Num_B = True
I suspect that you are using python <2.8, so input() behave differently and execute what is given instead of returning it as string (like eval(input())). When given an int, no problems occurs but when given a "Stop", python does not know what to do with it (unless your code have a variable named "Stop" ...).
Here is a simple rework of your code for python2:
# little trick to use input with python2 or python3 !
# source: http://stackoverflow.com/a/7321970/956660
try: input = raw_input
except NameError: pass
# variables naming is prefered in snake_case
num_list = []
curr_num = '' # only use one variable for input
while curr_num.lower() != 'stop': # lower allows to be case insensitive
# raw_input prevent the "bug"
curr_num = input('Enter a number or "stop": ')
# conversion to int raise an error on invalid string, so we ignore errors
try: num_list.append(int(curr_num))
except ValueError: pass
# we print and sorted only when everything have been inputted
print('Numbers: %s' % num_list)
print('Sorted: %s' % sorted(num_list))
Edit: Refactor code to be python 2 & 3 compatible. So you can use input() the same way anywhere ;)
Here is my approach: In an infinite loop, get a user's input. If it is 'Quit' then break out of the loop. Otherwise, convert to integer and append to the list of numbers. The code:
numbers = list()
while True:
token = input('Number: ')
if token == 'Quit':
break
numbers.append(int(token))
print('List is:', numbers)
Update
Judging by the original poster's ignoring empty strings, I guess some of the imput are empty strings, which causes ValueError. With that guess, I modified my code to take in accounts of those tokens that are not converted to numbers successfully.
numbers = list()
while True:
token = input('Number: ')
if token == 'Stop':
break
try:
numbers.append(int(token))
except ValueError:
print('Invalid token, ignore: {!r}'.format(token))
print('List is:', numbers)
Update 2:
I have modifying my code yet again. This time, the code runs fine in both Python 2 and 3 interpreters.
from __future__ import print_function
# Level the difference between Python 2 and 3
try:
raw_input
except NameError:
raw_input = input
numbers = list()
while True:
try:
token = raw_input('Number: ')
numbers.append(int(token))
except ValueError:
if token == 'Stop':
break
print('Invalid token, ignore: {!r}'.format(token))
print('List is:', numbers)
Update 3
Output for update 2 from Python 3 run:
Number: 7
Number: 87
Number: 120
Number:
Invalid token, ignore: ''
Number: foo
Invalid token, ignore: 'foo'
Number: bar
Invalid token, ignore: 'bar'
Number: Stop
List is: [7, 87, 120]
Output from Python 2 run is the same.
You can do it like this:
Num_List = list()
Numbers = input('Enter a number:')
while Numbers != 'Stop':
Num_List.append(int(Numbers))
Numbers = input('Enter a number:')
Num_List = [i for i in Num_List if i is not '']
Num_List.sort(reverse=False)
sorted(Num_List)
print(Num_List)
Related
I don't know how to get input depending on user choice. I.e. 'How many numbers you want to enter?' if answers 5, then my array has 5 spaces for 5 integers in one line separated by space.
num = []
x = int(input())
for i in range(1, x+1):
num.append(input())
Upper code works, however inputs are split by enter (next line). I.e.:
2
145
1278
I want to get:
2
145 1278
I would be grateful for some help.
EDIT:
x = int(input())
while True:
attempt = input()
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)== x:
break
else:
print('Error')
except:
print('Error')
This seems to work. But why I'm getting "Memory limit exceeded" error?
EDIT:
Whichever method I use, I get the same problem.
x = int(input())
y = input()
numbers_list = y.split(" ")[:x]
array = list(map(int, numbers_list))
print(max(array)-min(array)-x+1)
or
x = int(input())
while True:
attempt = input()
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)== x:
break
else:
print('Error')
except:
print('Error')
array = list(map(int, num))
print(max(array)-min(array)-x+1)
or
z = int(input())
array = list(map(int, input().split()))
print(max(array)-min(array)-z+1)
Assuming you want to input the numbers in one line, here is a possible solution. The user has to split the numbers just like you did in your example. If the input format is wrong (e.g. "21 asd 1234") or the number does not match the given length, the user has to enter the values again, until a valid input is made.
x = int(input("How many numbers you want to enter?"))
while True:
attempt = input("Input the numbers seperated with one space")
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)==x:
print(num)
break
else:
print("You have to enter exactly %s numbers! Try again"%x)
except:
print("The given input does not match the format! Try again")
The easiest way to do this would be something like this:
input_list = []
x = int(input("How many numbers do you want to store? "))
for inputs in range(x):
input_number = inputs + 1
input_list.append(int(input(f"Please enter number {input_number}: ")))
print(f"Your numbers are {input_list}")
Is there a reason you want the input to be on one line only? Because you can only limit how many numbers you store (or print) that way, not how many the user inputs. The user can just keep typing.
You can use this without needing x:
num = [int(x) for x in input().split()]
If you want the numbers to be entered on one line, with just spaces, you can do the following:
x = int(input("How many numbers do you want to store? "))
y = input(f"Please enter numbers seperated by a space: ")
numbers_list = y.split(" ")[:x]
print(f"We have a list of {len(numbers_list)} numbers: {numbers_list}")
Even if someone enters more than the amount of promised numbers, it returns the promised amount.
Output:
How many numbers do you want to store? 4
Please enter numbers seperated by a space: 1 4 6 7
We have a list of 4 numbers: ['1', '4', '6', '7']
Try this.
x = int(input())
num = [] # List declared here
while True:
try:
# attempt moved inside while
# in case input is in next line, the next line
# will be read in next iteration of loop.
attempt = input()
# get values in current line
temp = [int(val) for val in attempt.split(" ")]
num = num + temp
if len(num) == x:
break
except:
print('Error2')
Maybe the bot was passing integers with newline instead of spaces, in which case the while loop will never terminate (assuming your bot continuously sends data) because every time, it will just re-write num.
Note - this code will work for both space as well as newline separated inputs
I am trying to validate user input to check that, when they enter their name, it is more than 2 characters and is alphabetic. I am attempting to do this using try/except as I have been told that it is the best loop for user validation. Unfortunately if the user enters characters that are not alphabetic, nothing happens, and the program proceeds like normal. I also do not know how to check if the input is longer than 2 characters in the try/except loop as it is very new to me. Any help is much appreciated.
list = []
def users_name():
while True:
try:
name = str(input("Please enter your first name: "))
list.append(name)
break
except TypeError:
print("Letters only please.")
continue
except EOFError:
print("Please input something....")
continue
users_name()
You program will continue to run because of the continue clause in the catch block.
You can also check to see if the length of what they entered is longer than two characters.
list = []
def users_name():
while True: # Never ending loop
try:
name = str(input("Please enter your first name: "))
if (len(name) > 2)
list.append(name)
break
except TypeError:
print("Letters only please.")
continue # This causes it to continue
except EOFError:
print("Please input something....")
continue # This causes it to continue
users_name()
Also, you might want to stop the loop somehow. Maybe put in a break clause when you insert into the array?
if(len(name) > 2)
list.append(name)
break
...
To check if the input is a digit or an alphabet character use isdigit() or isalpha()
if a.isalpha():
#do something
elif a.isdigit():
#do something
Your code will then look like this:
list = []
def users_name():
while True: # Never ending loop
try:
name = str(input("Please enter your first name: "))
if (len(name) > 2 && name.isalpha()):
list.append(name)
break
else:
raise TypeError
except TypeError:
print("Letters only please.")
continue # This causes it to continue
except EOFError:
print("Please input something....")
continue # This causes it to continue
users_name()
Also if you are using Python < 3 consider using raw_input(). input() will actually evaluate the input as Python code.
To check the length of your String you can use the method len() to obtain its character length. You can then select those that are greater than 2 or your desired length.
To check if you string has only alphabetic characters you can use the str.isalpha() method to check so.
Therefore, if you check len(name) > 2 and name.isalpha() will help you filter those string that do not match what you want:
>>> name = "MyName"
>>> len(name) > 2 and name.isalpha()
True
>>> wrong_name = "My42Name"
>>> len(wrong_name) > 2 and wrong_name.isalpha()
False
>>> short_name = "A"
>>> len(short_name) > 2 and short_name.isalpha()
False
I have a question concerning int(). Part of my Python codes looks like this
string = input('Enter your number:')
n = int(string)
print n
So if the input string of int() is not a number, Python will report ValueError and stop running the remaining codes.
I wonder if there is a way to make the program re-ask for a valid string? So that the program won't just stop there.
Thanks!
You can use try except
while True:
try:
string = input('Enter your number:')
n = int(string)
print n
break
except ValueError:
pass
Put the whole thing in an infinite loop. You should catch and ignore ValueErrors but break out of the loop when you get a valid integer.
What you're looking for isTry / Except
How it works:
try:
# Code to "try".
except:
# If there's an error, trap the exception and continue.
continue
For your scenario:
def GetInput():
try:
string = input('Enter your number:')
n = int(string)
print n
except:
# Try to get input again.
GetInput()
n = None
while not isinstance(n, int):
try:
n = int(input('Enter your number:'))
except:
print('NAN')
While the others have mentioned that you can use the following method,
try :
except :
This is another way to do the same thing.
while True :
string = input('Enter your number:')
if string.isdigit() :
n = int(string)
print n
break
else :
print("You have not entered a valid number. Re-enter the number")
You can learn more about
Built-in String Functions from here.
I want to write a program that repeatedly asks the user to enter an integer or to terminate input by pressing Enter key, and then prints the even integers from those numbers entered.
Now, I am pretty much done with this program, I've mentioned the code I've come up with below. I am facing only one problem: how can I terminate the program when the users presses the Enter key?
def evenMem(aList):
mnew = []
for i in aList:
if (i % 2) == 0:
mnew.append(i)
return mnew
def main():
m = []
while True:
n = int(input('Enter a number: '))
m.append(n)
print(evenMem(m))
main()
In case you're using Python 3.x, make the while loop look like this:
while True:
line = input('Enter a number: ')
if not line:
break
n = int(line)
m.append(n)
You might want to surround the conversion to int with a try-catch to handle the case where the user enters something which is not parseable as an int.
With Python 2.x, the input() function will raise an exception if the input is empty (or EOF), so you could do this instead:
while True:
try:
n = int(input('Enter a number: '))
except:
break
m.append(n)
Here is the directions for what I need to do:
You are to write a complete program that obtains three pieces of data and then process them. The three pieces of information are a Boolean value, a string, and an integer. The logic of the program is this: if the Boolean value is True, print out the string twice, once with double quotes and once without - otherwise print out twice the number.
Here is what I have so far:
def main():
Boolean = input("Give me a Boolean: ")
String = input("Give me a string: ")
Number = int(input("Give me a number: "))
Can anybody help me out?
On stackoverflow, we're here to help people solve problems, not to do your homework, as your question very likely sounds… That said, here is what you want:
def main():
Boolean = input("Give me a Boolean: ")
String = input("Give me a string: ")
Number = int(input("Give me a number: "))
if Boolean == "True":
print('"{s}"\n{s}'.format(s=String))
try:
print('{}\n{}'.format(int(Number)))
except ValueError as err:
print('Error you did not give a number: {}'.format(err))
if __name__ == "__main__":
main()
A few explanations:
Boolean is "True" checks whether the contained string is actually the word True, and returns True, False otherwise.
then the print(''.format()) builds the double string (separated by \n) using the string format.
finally, when converting the string Integer into an int using int(Integer), it will raise a ValueError exception that gets caught to display a nice message on error.
the if __name__ == "__main__": part is to enable your code to be only executed when ran as a script, not when imported as a library. That's the pythonic way of defining the program's entry point.
I like to add a bit of logic to ensure proper values when I do input.
My standard way is like this:
import ast
def GetInput(user_message, var_type = str):
while 1:
# ask the user for an input
str_input = input(user_message + ": ")
# you dont need to cast a string!
if var_type == str:
return str_input
else:
input_type = type(ast.literal_eval(str_input))
if var_type == input_type:
return ast.literal_eval(str_input)
else:
print("Invalid type! Try again!")
Then in your main you can do something like this!
def main():
my_bool = False
my_str = ""
my_num = 0
my_bool = GetInput("Give me a Boolean", type(my_bool))
my_str = GetInput("Give me a String", type(my_str))
my_num = GetInput("Give me a Integer", type(my_num))
if my_bool:
print('"{}"'.format(my_str))
print(my_str)
else:
print(my_num * 2)