Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 14 days ago.
Improve this question
n = [1,2,3,4,5,6]
while True:
num = (input("enter your choice(from 1 to 6) "))
if num not in str(n) or num.isdigit == "False":
print("enter valid chice ")
os.system('cls')
pr()
else:
break
I want it to loop if the input is string and not in n
n = [1,2,3,4,5,6]
while True:
num = input("enter your choice(from 1 to 6) ")
if not num.isdigit() or int(num) not in n:
print("enter a valid choice ")
else:
break
The issue in the original code was checking isdigit as a string instead of calling the method on num. Also, the condition to check if num is not in n was incorrect. The corrected code checks if num is not a digit and also checks if the integer form of num is not in n.
Your code is convoluted, here's a simpler version:
# use try/except to get an int, or set our var outside the bounds in the while loop
try:
num = int(input("Enter your number (1-6):"))
except ValueError:
num = 0
# while our input isn't in the 1-6 range, ask for a number
while num not in [1,2,3,4,5,6]:
# same as before, if this is not a number, just set it to something that's not in [1-6] so we stay in the while loop
try:
num = int(input("Enter a valid choice please (1-6):"))
except ValueError:
num = 0
# your code here
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
num=int(input('Enter a number:'))
while num !=0:
if num>0:
if num%2==0 and num%7==0:
print('The number is a multiple of two and seven.' )
num=int(input('Enter a number:'))
elif num%2==0:
print('The number is a multiple of two.' )
num=int(input('Enter a number:'))
elif num%7==0:
print('The number is a multiple of seven.' )
num=int(input('Enter a number:'))
else:
print('The number is not a multiple of two or seven.' )
num=int(input('Enter a number:'))
else:
continue
else:
print('The user did not enter negative numbers.' )
Answer:
Enter a number:
>>> 5
The number is not a multiple of two or seven.
Enter a number:
>>> 6
The number is a multiple of two.
Enter a number:
>>> -8
The question is not very clear but I think I understand what you'd like to achieve.
Your solution is partially correct, but the "continue" inside the else is not followed by a new insertion of "num". So the input "num" is never changed when you insert a negative number.
Also the While-else clause has no sense in this case, if you want to count the negative number inserted you can just put a counter inside the first else clause.
You should change the code and move the "input" inside the while:
num = 1
negative_counter = 0
while num !=0:
num=int(input('Enter a number:'))
if num>0:
if num%2==0 and num%7==0:
print('The number is a multiple of two and seven.' )
elif num%2==0:
print('The number is a multiple of two.' )
elif num%7==0:
print('The number is a multiple of seven.')
else:
print('The number is not a multiple of two or seven.' )
else:
negative_counter = negative_counter + 1
continue
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I tried to use boolean instead of 'break' , but I could not manage to do that. Is there a way to edit this code without 'break' ?
Primes:
lower = int(input("Enter the lower bound: "))
upper = int(input("Enter the upper bound: "))
for num in range(lower,upper+1):
if num>1 :
for i in range(2,num):
if(num%i) == 0:
break
else:
print(num, end =", ")
You want to get rid of the break and preserve the same behavior of exiting the inner loop as soon as num % i == 0. This is one way to do it, using a boolean flag and replacing the for with a while so we can add one extra condition for the iteration:
for num in range(max(2, lower), upper + 1):
i = 2
prime = True
while i < num and prime:
if num % i == 0:
prime = False
i += 1
if prime:
print(num, end=", ")
You could replace break with pass. I think that will do what you want.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Write a function to enter from the keyboard a series of numbers between 1 and 20 and save them in a list.In case of entering an out-of-range value the program will display an error message and ask for a new number.To finish loading you must enter -1.La function does not receive any parameters, and returns the loaded list (or empty, if the user did not enter anything) as the return value.
def funcion():
list = []
num = 0
while num != -1:
num = int(input("Enter a number between 1 and 20: "))
while num > 20 :
num = int(input("Please re-enter the number: "))
list.append(num)
return lista
result = funcion()
print(result)
My question is how I do not show the -1 in the list
It's easier to have an infinite loop and break out of it when the user enters -1:
def funcion():
lista = []
num = 0
while True:
num = int(input("Enter a number between 1 and 20: "))
while num > 20:
num = int(input("Please re-enter the number: "))
if num == -1:
break
else:
lista.append(num)
return lista
result = funcion()
print(result)
The trick is saving the list except the last item like this:
return lista[:-1]
you can read more here:
https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/
The minimal change to your code would just use the list slicing syntax to return all elements of lista apart from the last one:
return lista[:-1]
See [1] below. This is a pythonic way of writing the slightly more intuitive, but more verbose statement:
return lista[:len(lista)-1]
... which in turn is short for the even longer:
return lista[0:len(lista)-1]
You seem to be new to python. I really recommend looking up "list slicing" and "list comprehensions": if you already know a programming language that doesn't have these, once you learn these, you'll wonder how you ever did without them!
[1] http://knowledgehills.com/python/negative-indexing-slicing-stepping-comparing-lists.htm
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()
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()