While loop keeps taking input even after condition is satisfied - python

By using the while loop get numbers as input from the user and add them to the list. If the user enters 'done' then the program output maximum and minimum number from the list.
This code also includes the error message using the 'try and except' block for wrong inputs.
nums = list()
while(True):
x = input("Enter a Number: ")
if x == "done":
break
try:
inp = float(x)
nums.append(inp)
except:
print("Enter only numbers or type 'done'")
continue
print("Maximum: ", max(nums))
print("Minimum: ", min(nums))
Input: 1, 2, 3, 4, er, done,...
Issue: 'er' input did not call except block, instead kept taking inputs. Somehow the Program was still running even after typing 'done' and kept taking input.
Tried: Added print(x) after line:3 but did not get any output for that either.

Related

Trying to validate a text input, so it allows characters in the alphabet only as the input but I'm having problems. (Python)

So, I have a homework where I'm assigned to write multiple python codes to accomplish certain tasks.
one of them is: Prompt user to input a text and an integer value. Repeat the string n
times and assign the result to a variable.
It's also mentioned that the code should be written in a way to avoid any errors (inputting integer when asked for text...)
Keep in mind this is the first time in my life I've attempted to write any code (I've looked up instructions for guidance)
import string
allowed_chars = string.ascii_letters + "'" + "-" + " "
allowed_chars.isalpha()
x = int
y = str
z = x and y
while True:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Please enter a valid integer: ")
continue
else:
break
while True:
try:
answer = str
y = answer(input("Enter a text: "))
except ValueError:
print("Please enter a valid text")
continue
else:
print(x*y)
break
This is what I got, validating the integer is working, but I can't validate the input for the text, it completes the operation for whatever input. I tried using the ".isalpha()" but it always results in "str is not callable"
I'm also a bit confused on the assigning the result to a variable part.
Any help would be greatly appreciated.
Looks like you are on the right track, but you have a lot of extra confusing items. I believe your real question is: how do I enforce alpha character string inputs?
In that case input() in python always returns a string.
So in your first case if you put in a valid integer say number 1, it actually returns "1". But then you try to convert it to an integer and if it fails the conversion you ask the user to try again.
In the second case, you have a lot of extra stuff. You only need to get the returned user input string y and check if is has only alpha characters in it. See below.
while True:
x = input("Enter an integer: ")
try:
x = int(x)
except ValueError:
print("Please enter a valid integer: ")
continue
break
while True:
y = input("Enter a text: ")
if not y.isalpha():
print("Please enter a valid text")
continue
else:
print(x*y)
break

I am running into a Name error when I convert a string input to an int

I am very new to python and programming as a whole. I recently took up a python beginners course and got an assignment that I am having difficulties with, the assignment will be posted below.
"Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below."
I am currently trying to convert a string input to an int so I can compare it with a none type, when I do this I get a name error. Both the code and the error will be posted below
I am aware that there is a multitude of issues in this code and if you spot something feel free to let me know. Here is my code, please go easy on me.
Code:
Largest = None
smallest = None
while True:
try:
Numbers = int(input("Enter A number: "))
if Numbers == ('done'):
break
except:
print ('invalid number')
for Numbers in [Numbers]:
if Largest is None:
Largest = Numbers
elif Numbers > Largest:
Largest = Numbers
if smallest is None:
smallest = Numbers
elif Numbers < smallest:
smallest = Numbers
print (Largest)
print (smallest)
Error:
C:\Users\Noah\Desktop\py4e>throw_away.py
Enter A number: f
invalid number
Traceback (most recent call last):
File "C:\Users\Noah\Desktop\py4e\throw_away.py", line 10, in <module>
for Numbers in [Numbers]:
NameError: name 'Numbers' is not defined
This happens because, when you have an error, you go into your except clause, but you then move right on into processing your numbers. Because there was an error, the Numbers variable was not created.
You need a continue in your except clause.
By the way, for Numbers in [Numbers]: is wrong in several ways. First, you should not have the loop variable be the same as the thing you are iterating. Next, Numbers is not a list -- it's a single number. So, you don't need a for loop at all. Just delete that line.
You need to rewrite your script to make it work:
# In order to keep track of all numbers typed by the user,
# we will use this list. It needs to be allocated just once
# before the main loop begins.
Numbers = []
# Start the main loop
while True:
try:
# Ask for the user input
num = input("Enter A number: ")
# Before converting it to an integer, check if the input
# is the string 'done'
if num == ('done'):
# If it is, break the loop.
break
# Otherwise, try to convert it to a number
else:
num = int(num)
# In any case, if int(num) fails, this exception will be
# catched and this block will execute instead
except:
print ('invalid number')
# If no exceptions were raised, then it means everything is
# normal.
#
# Append the user input converted to a number to the list.
else:
Numbers.append(num)
# When outside of the loop, check if the list is empty.
if (len(Numbers) == 0):
print('No numbers were recorded. List is empty.')
# If its not empty, find the minimum and maximum number, and
# print them on the screen.
else:
print ('MAX: ', max(Numbers))
print ('MIN: ', min(Numbers))
NOTE: There are other ways to write this script and get the same output. This is one of many ways to solve your problem. There are ways to make this script even faster by taking out the min and max functions and using the smallest and Largest variables from your script. That's an exercise for you if you're curious about it.

How to sum numbers entered by the user using Python and display the total?

My task is:
Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.
My idea was to append the numbers entered by the user to a list and after that loop through the list to sum the number and calculate the average using this total divided by the length of the list. Does that work? However, my list does not append integers, only strings. Besides, the word 'done' was also appended to the list.
my code is:
x=[ ]
while True:
line = input('enter a number: ')
x.append(line)
if line == 'done':
break
my desired output is:
Enter a number: 4
Enter a number: 5
Enter a number: bad data
Enter a number: 7
Enter a number: done
16 3 5.333333333333333
My idea was to append the numbers entered by the user to a list and after that loop through the list to sum the number and calculate the average using this total divided by the length of the list. Does that work?
Yes, that sounds like the perfect solution.
However, my list does not append integers, only strings.
Convert the input to an int before appending it:
x.append(int(line))
This will fail if line cannot be converted to an int, so you probably actually want:
try:
x.append(int(line))
except ValueError:
pass
Besides, the word 'done' was also appended to the list.
Check for the string 'done' before you append it.
if line == 'done':
break
try:
x.append(int(line))
except ValueError:
pass
Finally, you can use sum and len to do your calculations.
Here is what you can do, assuming the user can only input integers:
x=[]
while True:
try:
line = input('enter a number: ')
if line == 'done':
break
x.append(int(line))
except:
pass
print(sum(x),len(x),sum(x)/len(x))
If the user should be able to input floats:
x=[]
while True:
try:
line = input('enter a number: ')
if line == 'done':
break
x.append(float(line))
except:
pass
print(sum(x),len(x),sum(x)/len(x))

Does While loop ends when the program return value?

I am a new learner for Python. I have a question about while loop.
I wrote a program below to look for square roots.
When I input anything but integers, the message "is not an integer" shows up and it repeats itself until I input correct data(integers).
My question is, why does it end loop when it return value on line 5, return(int(val))?
Thank you for your attention.
def readInt():
while True:
val = input('Enter an integer: ')
try:
return(int(val))
except ValueError:
print(val, "is not an integer")
g = readInt()
print("The square of the number you entered is", g**2)
To answer your original question, 'return' effectively exits the loop and provide the result that follows the 'return' statement, but you have to explicity print it like so:
def read_int(num1, num2):
while True:
return num1 + num2
print(read_int(12, 15))
If you simply put 'read_int(12, 14)' instead of 'print(read_int(12, 15))' in this scenario, you won't print anything but you will exit the loop.
If you allow me, here are some modifications to your original code:
def read_int(): # functions must be lowercase (Python convention)
while True:
val = input('Enter an integer: ')
try:
val = int(val) # converts the value entered to an integer
minimum_value = 0 # There is no need to evaluate a negative number as it will be positive anyway
maximum_value = 1000000 # Also, a number above 1 million would be pretty big
if minimum_value <= val <= maximum_value:
result = val ** 2
print(f'The square of the number you entered is {result}.')
# This print statement is equivalent to the following:
# print('The square of the number you entered is {}.'.format(result))
break # exits the loop: else you input an integer forever.
else:
print(f'Value must be between {minimum_value} and {maximum_value}.')
except ValueError: # If input is not an integer, print this message and go back to the beginning of the loop.
print(val, 'is not an integer.')
# There must be 2 blank lines before and after a function block
read_int()
With the final 'print' that you actually have at the end of your code, entering a string of text in the program generates an error. Now it doesn't ;). Hope this is useful in some way. Have a great day!

Having issues with a program to input multiple numbers from the user, till the user types “Done". To compute their average and print the results

So here is how the program is supposed to work. The user would input something like this and the output would give them the answer.
Input:
1
2
2
1
Done
Output:
1.5
So far I was able to come up with the input question and got it to loop until you put Done.
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done":
break
else:
nums.append(int(num))
I don't know how to make the program perform the calculation to print out the average. I am very new to programming in python and I would appreciate any help I can get on fixing this program. Thanks in advance!
Break while loop when 'Done' is the input, else save the number as float. This throws an error if you try to enter 'finish'. Finally calculate and print the Average.
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done": # This has to be tested inside the while loop
break
# Only append after testing for 'Done'
nums.append(float(num)) # Ensure valid input by convert it into the desired type.
print('average: %s' % (sum(nums) / len(nums)))
It is a good practice to give the user useful error messages, when some input is not as the program needs it. It can save the user lots of trouble. If you just want to tell the user what the problem was when an invalid input is given, you can do it with a try statement as below:
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done":
break
try:
nums.append(float(num))
except Exception:
print('Please enter a number. Input "%s" will be ignored.' % num)
print('average: %s' % (sum(nums) / len(nums)))

Categories

Resources