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)
Related
I have a function, findnums(v) that is intended to append 5 numbers taken from user input to list v, which starts in main as an empty list. I have a nested try-except loop in my for loop for the function findnums(v) to try and reject non float user input.
I want my except condition to ignore the iteration that had the bad user input, not pass this bad input back to list v, and prompt the user to enter good input. While the condition doesn't pass bad input to the list, and does prompt the user to reenter good input, the bad data counts for an iteration and is not ignored. Ideally, I want the number of bad input iterations to be uncounted/infinite, and the number of good input iterations to always equal to 5.
Here is my code:
def main():
v=[]
findnums(v)
printlist(v)
def findnums(v):
for n in range(0,5):
try:
val=float(input('Please enter you number: '))
v.append(val)
except ValueError:
print("That is an invalid input, please start over.")
#main()
#findnums(v)
return(v)
def printlist(v):
print(v)
I've tried calling main() and the findnums(v) function in the except condition to have the program restart in the case of bad data, but in both cases it won't ignore the data as I want it to, but it will just rerun the program for each time the bad input is given, counting each piece of bad data for the final list. So if three pieces of bad data are entered, the program will ask for user input 12 time, and add those 12 items to the list v.
I think understand why this is happening. The data, good or bad is always being passed to v, I just can't think of a way of passing only good data to v.
I would use a while loop for this.
def main():
v=[]
findnums(v)
printlist(v)
def findnums(v):
# Reapeat the following until there is a break
while(True):
# If the list has a length of 5, break
if len(v) == 5:
break
try:
val = float(input('Please enter you number: '))
v.append(val)
except:
print("That is an invalid input, please start over.")
def printlist(v):
print(v)
You may put the try/except block inside a while loop. That will keep asking the user for an input until they enter a float.
def main():
v = []
findnums(v)
printlist(v)
def findnums(v):
for i in range(5):
while True:
try:
val = float(input('Please enter you number: '))
v.append(val)
except ValueError:
print("That is an invalid input, please start over.")
return v
def printlist(v):
print(v)
Be careful passing an array to a function as arrays are passed by reference. For more info check: What's the difference between passing by reference vs. passing by value?
How I would reformat this is shown below
def findnums():
v = []
for i in range(5):
while True:
try:
val = float(input('Please enter you number: '))
v.append(val)
except ValueError:
print("That is an invalid input, please start over.")
else:
break
return v
def main():
v = findnums()
print(v)
if __name__ == "__main__":
main()
It's generally not advisable to pass in the array for modification, as this might accidentally expand the old array in repeated calls. Just return the array from the function:
def main():
v = findnums(5)
printlist(v)
def findnums(n):
v=[]
while len(v) < n:
try:
val=float(input('Please enter you number: '))
v.append(val)
except ValueError:
print("That is an invalid input, please start over.")
return(v)
def printlist(v):
print(v)
main()
I am going through book automate boring stuff with python and trying to solve the practical problems.
In this project I need to define collatz() function and print results as seen in code until it gets 1.
So basically i need to input only one number and program should return numbers until it returns 1.
Program works fine but i have one question if i can make it better :D .
My question is after using try: and except: is there a way to not end process when typing string in input function but to get message below 'You must enter number' and get back to inputing new number or string and executing while loop normally. Code works fine just wondering if this is possible and if so how?
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
else:
print(3 * number + 1)
return 3 * number + 1
try:
yourNumber = int(input('Enter number: '))
while True:
yourNumber = collatz(yourNumber)
if yourNumber == 1:
break
except ValueError:
print('You must enter a number')
Put the try/except inside a loop, such that on the except the loop will continue but on a success it will break:
while True:
try:
yourNumber = int(input('Enter number: '))
except ValueError:
print('You must enter a number')
else:
break
while yourNumber != 1:
yourNumber = collatz(yourNumber)
I use Python 3 in Windows. My problem is that I need to find out how can I put in my code the choice that if the user pushes the Enter key the program will continue doing the calculation and when the user types q and pushes the Enter key the program will be terminated.
A simple code is below.
while True:
x = int(input('Give number: '))
y=x*3
print(y)
while True:
user_input = input('Give number: ')
if not user_input.isdigit(): #alternatively if user_input != 'q'
break
x = int(user_input)
y=x*3
print(y)
Assuming you want to calculate while new numbers are entered, the str isdigit function returns True if the string only contains digits. This approach will allow you to handle if the user enters a non-integer like xsd, which will crash the program if you try to cast to int. To only exit if q is entered, you would do if user_input != 'q', but this assumes the user only enters numbers or q.
while True:
s = input('Give number: ')
if s == 'q':
break
y=int(s)*3
print(y)
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 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)