This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 12 months ago.
I'm new to python and I am trying to figure out how do I enter an error message if the user inputs a number less than zero.
Here is my code to give you a better understanding and I thank you all in advance for any advice.
# Python Program printing a square in star patterns.
length = int(input("Enter the side of the square : "))
for k in range(length):
for s in range(length):
if(k == 0 or k == length - 1 or s == 0 or s == length - 1):
print('*', end = ' ')
else:
print('*', end = ' ')
print()
Here is a simple and straight forward way to use a while loop to achieve this. Simple setting an integer object of check to 0. Then the while loop will evaluate check's value, then take user input, if the user input is greater than 0, let's set out check object to 1, so when we get back to the top of the loop, it will end.
Otherwise, if the if check fails, it will print a quick try again message and execute at the top of the loop again.
check = 0
while check == 0:
length = int(input("Enter the side of the square : "))
if length > 0:
check = 1
else:
print("Please try again.")
You can use this code after the input statement and before for loop.
if length < 0 :
Print("invalid length")
Break
Related
number = 0
number_list = []
while number != -1:
number = int(input('Enter a number'))
number_list.append(number)
else:
print(sum(number_list)/ len(number_list))
EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. Unsure of where it's going wrong! Sorry for the confusion
Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.
number_list = []
def average(mylist):
return sum(mylist)/len(mylist)
while True:
number = int(input('Enter a number: '))
if number == -1:
break
number_list.append(number)
print(average(number_list));
Some points to note.
Instead of associating the else statement with the while loop, I revised the while loop utilizing the Boolean constant "True" and then tested for the value of "-1" in order to break out of the loop.
In the average function, I renamed the list variable to "mylist" so as to not confuse anyone who might analyze the code as list is a word that has significance in Python.
Finally, the return of the average was added to the end of the function. If a return statement is not included in a function, a value of "None" will be returned by a function, which is most likely why you received the error.
Following was a test run from the terminal.
#Dev:~/Python_Programs/Average$ python3 Average.py
Enter a number: 10
Enter a number: 22
Enter a number: 40
Enter a number: -1
24.0
Give that a try and see if it meets the spirit of your project.
converts the resulting list to Type: None
No, it doesn't. You get a ValueError with int() when it cannot parse what is passed.
You can try-except that. And you can just use while True.
Also, your average function doesn't output anything, but if it did, you need to call it with a parameter, not only print the function object...
ex.
from statistics import fmean
def average(data):
return fmean(data)
number_list = []
while True:
x = input('Enter a number')
try:
val = int(x)
if val == -1:
break
number_list.append(val)
except:
break
print(average(number_list))
edit
my program calculates the average to be 2 not 3
Your calculation includes the -1 appended to the list , so you are running 8 / 4 == 2
You don't need to save all the numbers themselves, just save the sum and count.
You should check if the input is a number before trying to convert it to int
total_sum = 0
count = 0
while True:
number = input("Enter a number: ")
if number == '-1':
break
elif not number.isnumeric() and not (number[0] == "-" and number[1:].isnumeric()):
print("Please enter numbers only")
continue
total_sum += int(number)
count += 1
print(total_sum / count)
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
Hey I'm trying to create an infinite list in python that takes user input in till 0 is entered, I don't really know if this is the right way to do so, here's what I did:
`n = input("Enter a list element separated by space ")
while n == 0:
break
else:
list = n.split()
print(list)`
Thank you!
This code will do what you originally described:
Numbers = []
while True:
number = int(input("Please enter a number:"))
if number == 0:
break
Numbers.append(number)
print(Numbers)
try this
l = []
while 1:
n = input("Enter a list element seperated by a space")
for x in n.split():
if x == 0:
break
l.append(int(x))
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 years ago.
For example, if you wanted to accept say 2 input values it would be something like,
x = 0
y = 0
line = input()
x, y = line.split(" ")
x = int(x)
y = int(y)
print(x+y)
Doing it this way however, would mean that I must have 2 inputs at all times, that is separated by a white space.
How do I make it so that a user could choose to enter any number of inputs, such as nothing (e.g. which leads to some message,asking them to try again), or 1 input value and have an action performed on it (e.g. simply printing it), or 2 (e.g. adding the 2 values together) or more.
You can set a parameter how many values there will be and loop the input and put them into a map - or you make it simple 2 liner:
numbers = input("Input values (space separator): ")
xValueMap = list(map(int, numbers.split()))
this will create a map of INT values - separated by space.
You may want to use a for loop to repeatedly get input from the user like so:
num_times = int(input("How many numbers do you want to enter? "))
numbers = list() #Store all the numbers (just in case you want to use them later)
for i in range(num_times):
temp_num = int(input("Enter number " + str(i) + ": "))
numbers.append(temp_num)
Then, later on, you can use an if/elif/else chain to do different actions to the numbers based on the length of the list (found using the len() function).
For example:
if len(numbers) == 0:
print("Try again") #Or whatever you want
elif len(numbers) == 1:
print(numbers[0])
else:
print(sum(numbers))
Try something like this. You will provide how many numbers you want to ask the user to input those many numbers.
def get_input_count():
count_of_inputs = input("What is the number you want to count? ")
if int(count_of_inputs.strip()) == 0:
print('You cannot have 0 as input. Please provide a non zero input.')
get_input_count()
else:
get_input_and_count(int(count_of_inputs.strip()))
def get_input_and_count(count):
total_sum = 0
for i in range(1,count+1):
input_number = input("Enter number - %s :"%i)
total_sum += int(input_number.strip())
print('Final Sum is : %s'%total_sum)
get_input_count()
I want to write a program with this logic.
A value is presented of the user.
Commence a loop
Wait for user input
If the user enters the displayed value less 13 then
Display the value entered by the user and go to top of loop.
Otherwise exit the loop
You just need two while loops. One that keeps the main program going forever, and another that breaks and resets the value of a once an answer is wrong.
while True:
a = 2363
not_wrong = True
while not_wrong:
their_response = int(raw_input("What is the value of {} - 13?".format(a)))
if their_response == (a - 13):
a = a -13
else:
not_wrong = False
Although you're supposed to show your attempt at coding towards a solution and posting when you encounter a problem, you could do something like the following:
a = 2363
b = 13
while True:
try:
c = int(input('Subtract {0} from {1}: '.format(b, a))
except ValueError:
print('Please enter an integer.')
continue
if a-b == c:
a = a-b
else:
print('Incorrect. Restarting...')
a = 2363
# break
(use raw_input instead of input if you're using Python2)
This creates an infinite loop that will try to convert the input into an integer (or print a statement pleading for the correct input type), and then use logic to check if a-b == c. If so, we set the value of a to this new value a-b. Otherwise, we restart the loop. You can uncomment the break command if you don't want an infinite loop.
Your logic is correct, might want to look into while loop, and input. While loops keeps going until a condition is met:
while (condition):
# will keep doing something here until condition is met
Example of while loop:
x = 10
while x >= 0:
x -= 1
print(x)
This will print x until it hits 0 so the output would be 9 8 7 6 5 4 3 2 1 0 in new lines on console.
input allows the user to enter stuff from console:
x = input("Enter your answer: ")
This will prompt the user to "Enter your answer: " and store what ever value user enter into the variable x. (Variable meaning like a container or a box)
Put it all together and you get something like:
a = 2363 #change to what you want to start with
b = 13 #change to minus from a
while a-b > 0: #keeps going until if a-b is a negative number
print("%d - %d = ?" %(a, b)) #asks the question
user_input = int(input("Enter your answer: ")) #gets a user input and change it from string type to int type so we can compare it
if (a-b) == user_input: #compares the answer to our answer
print("Correct answer!")
a -= b #changes a to be new value
else:
print("Wrong answer")
print("All done!")
Now this program stops at a = 7 because I don't know if you wanted to keep going with negative number. If you do just edited the condition of the while loop. I'm sure you can manage that.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I am trying to write a number guessing program as follows:
def oracle():
n = ' '
print 'Start number = 50'
guess = 50 #Sets 50 as a starting number
n = raw_input("\n\nTrue, False or Correct?: ")
while True:
if n == 'True':
guess = guess + int(guess/5)
print
print 'What about',guess, '?'
break
elif n == 'False':
guess = guess - int(guess/5)
print
print 'What about',guess, '?'
break
elif n == 'Correct':
print 'Success!, your number is approximately equal to:', guess
oracle()
What I am trying to do now is get this sequence of if/ elif/ else commands to loop until the user enters 'Correct', i.e. when the number stated by the program is approximately equal to the users number, however if I do not know the users number I cannot think how I could implement and if statement, and my attempts to use 'while' also do not work.
As an alternative to #Mark Byers' approach, you can use while True:
guess = 50 # this should be outside the loop, I think
while True: # infinite loop
n = raw_input("\n\nTrue, False or Correct?: ")
if n == "Correct":
break # stops the loop
elif n == "True":
# etc.
Your code won't work because you haven't assigned anything to n before you first use it. Try this:
def oracle():
n = None
while n != 'Correct':
# etc...
A more readable approach is to move the test until later and use a break:
def oracle():
guess = 50
while True:
print 'Current number = {0}'.format(guess)
n = raw_input("lower, higher or stop?: ")
if n == 'stop':
break
# etc...
Also input in Python 2.x reads a line of input and then evaluates it. You want to use raw_input.
Note: In Python 3.x, raw_input has been renamed to input and the old input method no longer exists.