How to stop a while loop processing integers with a string - python

I'm processing integer inputs from a user and would like for the user to signal that they are done with inputs by typing in 'q' to show they are completed with their inputs.
Here's my code so far:
(Still very much a beginner so don't flame me too much)
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num = int(input("Enter a number: "))
while num != "q":
num = int(input("Enter a number: "))
count += 1
total += num
del record[-1]
print (num)
print("The average of the numbers is", total / count)
main()
Any feedback is helpful!

You probably get a ValueError when you run that code. That's python's way of telling you that you've fed a value into a function that can't handle that type of value.
Check the Exceptions docs for more details.
In this case, you're trying to feed the letter "q" into a function that is expecting int() on line 6. Think of int() as a machine that only handles integers. You just tried to stick a letter into a machine that's not equipped to handle letters and instead of bursting into flames, it's rejecting your input and putting on the breaks.
You'll probably want to wrap your conversion from str to int in a try: statement to handle the exception.
def main():
num = None
while num != "q":
num = input("Enter number: ")
# try handles exceptions and does something with them
try:
num = int(num)
# if an exception of "ValueError" happens, print out a warning and keep going
except ValueError as e:
print(f'that was not a number: {e}')
pass
# if num looks like an integer
if isinstance (num, (int, float)):
print('got a number')
Test:
Enter number: 1
got a number
Enter number: 2
got a number
Enter number: alligator
that was not a number: invalid literal for int() with base 10: 'alligator'
Enter number: -10
got a number
Enter number: 45
got a number
Enter number: 6.0222
that was not a number: invalid literal for int() with base 10: '6.0222'
I'll leave it to you to figure out why 6.02222 "was not a number."

changing your code as little as possible, you should have...
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num.append(input("Enter a number: "))
while num[-1] != "q":
num.append(input("Enter a number: "))
count += 1
try:
total += int(num[-1])
except ValueError as e:
print('input not an integer')
break
print (num)
print("The average of the numbers is", total / count)
main()

You may attempt it the way:
def main():
num_list = [] #list for holding in user inputs
while True:
my_num = input("Please enter some numbers. Type 'q' to quit.")
if my_num != 'q':
num_list.append(int(my_num)) #add user input as integer to holding list as long as it is not 'q'
else: #if user enters 'q'
print(f'The Average of {num_list} is {sum(num_list)/len(num_list)}') #calculate the average of entered numbers by divide the sum of all list elements by the length of list and display the result
break #terminate loop
main()

Related

I have this code but whenever I input a word such as cow it stops working

Whenever I run this code it doesn't allow inputs such as cow. I have included the term float as I would like number and word input. I can enter numbers but not words. Has anyone got an idea where I am going wrong?
my output should look like :
How many strings do you want to enter:3
Enter string 1: 2
Enter string 2:-4
Enter string 3:cow
No of positive numbers entered is: 1
def main():
global countervalue
countervalue=0
string=int(input("How many strings do you want to enter? "))
for num in range(1,string+1):
value=float(input("Enter string %a: "%num))
IsPos(value)
print("No of positive whole numbers entered is:",countervalue)
def IsPos(val):
global countervalue
if val.is_integer() and val>=0:
countervalue+=1
return countervalue;
main()
I think you just need to test whether the input value is a number or not by converting to float and catching the resulting exception:
def main():
global countervalue
countervalue = 0
string = int(input("How many strings do you want to enter? "))
for num in range(1, string+1):
value = input("Enter string %a: " % num)
IsPos(value)
print("No of positive whole numbers entered is:", countervalue)
def IsPos(val):
global countervalue
try:
fval = float(val)
if fval.is_integer() and fval >= 0:
countervalue += 1
except ValueError:
pass
return countervalue
main()
Output as requested

ValueError: Name undefined in python

I am getting "Name undefined warning while compiling with try-catch block". Please give some idea about this error.
NAME UNDEFINED ERROR IMAGE
# Importing random package
import random
try:
top_range = int(input("Enter the range:"))
except ValueError:
print("Please enter he Integer Number")
# Getting the random number from system
sys_guess = random.randint(0, top_range)
print("System Guess =", sys_guess)
print("Try to GUESS the Number within 3 entries, MAXIMUM 3 guess......!")
# making for increment
guess = 0
# Guessing the number
while sys_guess >= 0:
user_input = int(input("Enter guessed number: "))
if sys_guess != user_input:
# incrementing the wrong value
guess += 1
print("Wrong Guess-->")
if guess == 2:
print("you have only one guess left")
if guess > 2:
print("Maximum number of guess tried, Failed to obtain the guess!!!!!")
break
else:
# incrementing the correct value
guess += 1
print("!HURRAY***CORRECT GUESS***!")
if sys_guess == user_input:
break
# printing the total number of guess
print("Total Guesses=", guess)
Stick the try catch block in a loop that will continue endlessly until the user enters a valid number. If there is an exception at the moment the top_range value is never defined thus the error.
while True:
try:
top_range = int(input("Enter the range:"))
break
except ValueError:
print("Please enter he Integer Number")

Apparently I'm not converting all arguments during string formatting but I can't figure out what's wrong

I'm trying to make a program that has the user input a number and check if it's even or odd by dividing it by 2 and seeing if there's a remainder. but I keep getting an error saying "not all arguments converted during string formatting"
I haven't been able to do much because I can't find anything about it anywhere.
var = input("Enter a number!")
var1 = var % 2
if var1 > 0:
print("The entered number is odd")
else:
print("The entered number is even")
The python builtin input function gives you a string, you have to convert it to a int using int(input(..))
#Converted string to int
var = int(input("Enter a number!"))
var1 = var % 2
if var1 > 0:
print("The entered number is odd")
else:
print("The entered number is even")
Then the output will look like
Enter a number!5
The entered number is odd
Enter a number!4
The entered number is even
Note that your code will break if you provide a string as an input here
Enter a number!hello
Traceback (most recent call last):
File "/Users/devesingh/Downloads/script.py", line 2, in <module>
var = int(input("Enter a number!"))
ValueError: invalid literal for int() with base 10: 'hello'
So you can do a try/except around conversion, and prompt the user if he doesn't give you an integer
var = None
#Try to convert to int, if you cannot, fail gracefully
try:
var = int(input("Enter a number!"))
except:
pass
#If we actually got an integer
if var:
var1 = var % 2
if var1 > 0:
print("The entered number is odd")
else:
print("The entered number is even")
else:
print("You did not enter a number")
The output will then look like
Enter a number!hello
You did not enter a number
Enter a number!4
The entered number is even
Enter a number!5
The entered number is odd
Looks much better now doesn't it :)
Like Austin mentioned in his comment, you need to typecast the output of the input function.
input returns a string, and asking for a remainder of a division between a string and a number is nonsensical.
var = int(input("Enter a number!"))
var1 = var % 2
if var1 > 0:
print("The entered number is odd")
else:
print("The entered number is even")

I am trying to get my program to take only integers and stop when the user presses 0

So the code before behaved properly before my "while type(number) is not int:" loop, but now when the user presses 0, instead of generating the sum of the list, it just keeps looping.
Would really appreciate some help with this! Thank you!
List = []
pro = 1
while(pro is not 0):
number = False
while type(number) is not int:
try:
number = int(input("Please enter a number: "))
List.append(number)
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
ans = 0
print(Sum)
Actually, this should keep looping forever for all numbers the user may input, not just zero.
To fix this, you can just add this break condition after (or before, it doesnt really matter) appending:
number = int(input("Please enter a number: "))
List.append(number)
if number == 0:
break
So I got it to work, when written like this:
List = []
pro = 1
while(pro is not 0):
while True:
try:
number = int(input("Please enter a number: "))
List.append(number)
break
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
pro = 0
print(Sum)
But I don't really understand how this is making it only take int values, any clarification would be really helpful, and otherwise thank you all for your help!
I'm guessing that you want to end while loop when user inputs 0.
List = []
pro = 1
while pro is not 0:
try:
number = int(input("Please enter a number: "))
List.append(number)
# This breaks while loop when number == 0
pro = number
except ValueError:
print("Please only enter integer values.")
Sum = 0
for i in List:
Sum += i
print(Sum)
EDIT: I have also cleaned the unnecessary code.
Put if number == 0: inside while type(number) is not int: loop like this:
List = []
while True:
try:
number = int(input("Please enter a number: "))
if number == 0:
Sum = 0
for i in List:
Sum = i + Sum
print(Sum)
break
List.append(number)
except ValueError:
print("Please only enter integer values.")

Asking for 10-digit numbers

I am testing that the user input is of length 10 and only contains numbers. At the moment, my code is:
while True:
number = input("Enter number: ")
try:
if len(number) != 10:
print ("Enter 10 digits\n")
continue
except ValueError:
print ("Enter only numbers\n")
continue
else:
break
The program will ask for user input, then test that it is of 10 length and only contains integers.
Currently, user input is read as a string so that if it began with a '0', then this would be included in len(), if you know what I mean? For example, if I inputted '0123456789', this would be seen to have a length of 10 and not 9 because it begins with '0'.
Also, I wanted to ensure that if the user entered 10 letters, this would be declined because only numbers are allowed.
Any help would be greatly appreciated.
Thank you.
At no point in your code do you actually check that the input is an integer..
You could do something like this:
while True:
number = input("Enter number: ")
if not number.isdigit(): # check if a string contains a number with .isdigit()
print ("Enter only numbers\n")
continue
elif len(number) != 10:
print ("Enter 10 digits\n")
continue
else:
break
Info on str.isdigit():
Type: method_descriptor
String Form:<method 'isdigit' of 'str' objects>
Namespace: Python builtin
Docstring:
S.isdigit() -> bool
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
while True:
number = input("Enter number: ")
try:
number = int(number)
except ValueError:
print ("Enter only numbers")
else:
if 10 > number//10**9 > 0 :
print ("Enter 10 digits")
continue
else:
break
You can checking for an error while casting to a number (integer)
try:
if len(number) != 10 and int(number):
print ("Your number is good!")
break
else :
print("Your number isn't good!")
continue
except ValueError:
print('only digit please')
continue
Note that the flaw in len(number) is that the nine firsts digit could be 0.
To ensure that is a valid number beetwen 1000000000 and 999999999 you can do the following:
import math
while True:
try:
if math.floor(math.log10(int(number)))+1 == 10:
print ("Your number is good!")
break
else :
print("Your number isn't good!")
continue
except ValueError:
print('only digit please')
continue

Categories