I've made a simple program where the users adds as many numbers as they would like then type 'exit' to stop it and print the total but sometimes it says the converting the string to int fails, and sometimes it does convert but then it has the wrong out put e.g I type 1 + 1 but it prints 1
def addition():
x = 0
y = 1
total = 0
while x < y:
total += int(input())
if input() == "exit":
x += 1
print(total)
addition()
I have tryed converting it to a float then to an int but still has inconsistency, I did start learning python today and am finding the syntax hard coming from c++ / c# / Java so please go easy on the errors
Maybe this is what you are looking for:
def addition():
total = 0
while True:
value = input()
if value == "exit":
break
else:
try:
total += int(value)
except:
print('Please enter in a valid integer')
print(total)
EDIT
There are two reasons why the code isn't working properly:
First, the reason why it is failing is because you are trying to cast the word "exit" as an integer.
Second, as user2357112 pointed out, there are two input calls. The second input call was unintentionally skipping every other number being entered in. All you needed to do was one input call and set the entered value into a variable.
You can break the while loop, without using x and y.
def addition():
total = 0
while True:
total += int(input())
if input() == "exit":
break
print(total)
addition()
These are a few ways you can improve your code:
Run the loop forever and break out of it only if the user enters "exit"
To know when the user entered "exit" check if the input has alphabets with isalpha()
Making the above changes:
def addition():
total = 0
while True:
user_input = input()
if user_input.strip().isalpha() and user_input.strip() == 'exit':
break
total += int(user_input)
print(total)
addition()
def safe_float(val):
''' always return a float '''
try:
return float(val)
except ValueError:
return 0.0
def getIntOrQuit():
resp = input("Enter a number or (q)uit:")
if resp == "Q":
return None
return safe_float(resp)
print( sum(iter(getIntOrQuit,None)) )
is another way to do what you want :P
Related
I don't understand why is not working on my code
def random_calculation(num):
return((num*77 + (90+2-9+3)))
while random_calculation:
num = int(input("Pleace enter number: "))
if num == "0":
break
else:
print(random_calculation(num))
Can you guide me what is wrong here, i really dont understand
You have several errors in your code:
You cannot do while random_calculation like this. You need to call the function, but since inside the loop you are already checking for a break condition, use while True instead.
Also, you are converting the input to int, but then comparing agains the string "0" instead of the int 0
Here's the corrected code:
def random_calculation(num):
# 90+2-9+3 is a bit strange, but not incorrect.
return((num*77 + (90+2-9+3)))
while True:
num = int(input("Please enter number: "))
if num == 0:
break
# you don't need an else, since the conditional would
# break if triggered, so you can save an indentation level
print(random_calculation(num))
so,when you start the loop it ask you what number you want to enter and then the code checks if the number is == to 0. IF the number is equal to 0: break the loop. IF the number is equal to any other number it prints the "random_calculation" function
I am learning Python, and currently I am learning about sentinel loops. I have this piece of code that I need help understanding. What exactly is the while-loop doing? I did some research and I know it is looping through the if-statement (correct me if I am wrong); but is it looping through a specific equation until the user stops inputting their integers? Thank you in advanced.
(Please no hate comments I am still learning as a developer. & this is my first post Thanks)
even = 0 odd = 0
string_value = input("Please enter an int. value: ")
while string_value !="":
int_value = int(string_value)
if int_value % 2 == 0:
even += 1
else:
odd += 1
string_value = input("Please enter an int. value: ")
if even + odd == 0:
print("No values were found. Try again...") else:
print("Number of evens is: ", str(even)+".")
print("Number of odd is: ", str(odd)+".")
---Updated Code:
def main():
print("Process a series of ints enter at console \n")
count_even = 0
count_odd = 0
num_str = input("Please enter an int. value or press <Enter> to stop: ")
#Process with loop
while num_str !="":
num_int = int(num_str)
if num_int % 2 == 0:
count_even += 1
else:
count_odd += 1
num_str = input("Please enter an int. value: ")
if count_even + count_odd == 0:
print("No values were found. Try again...")
else:
print("Number of evens is: ", str(count_even)+".")
print("Number of odd is: ", str(count_odd)+".")
main()
First thing the while loop does is check if the user input is emptywhile string_value !="", if it is not empty than it will start the loop. The != means not equals and the "" is empty so not equals empty. Next it sets the variable int_value as the integer of the user input(will error if user inputs anything other than whole number). Next it checks if the variable int_value % 2(remainder of division by 2) is 0, so pretty much it checks if the number is divisible by 2, if it is divisible by two it will add 1 to the even variable. Otherwise it will add 1 to the odd variable
It will be very helpful if you go through python doc https://docs.python.org/3/tutorial/index.html
even = 0 odd = 0
The above line even and odd are variables keeping count of even number and odd number.
string_value = input("Please enter an int. value: ")
The above line prompt the user to input an integer
while string_value !="":
int_value = int(string_value)
if int_value % 2 == 0:
even += 1
else:
odd += 1
string_value = input("Please enter an int. value: ")
The above while loop check firstly, if the input is not empty, int() Return an integer object constructed from a number or string x, or return 0 if no arguments are given https://docs.python.org/3/library/functions.html#int. The if statement takes the modulus of the integer value, and then increases the counter for either odd or even.
Finally, the count of odd and even are printed.
the input() function waits until the user enters a string so unless the user enters an empty string the while loop will keep asking the user for strings in this line:
string_value = input("Please enter an int. value: ")
and check if its an empty string in this line:
while string_value !="":
I am completing questions from a python book when I came across this question.
Write a program which repeatedly reads numbers until the user enters "done". Once done is entered, print out total, count, and average of the numbers.
My issue here is that I do not know how to check if a user specifically entered the string 'done' while the computer is explicitly checking for numbers. Here is how I approached the problem instead.
#Avg, Sum, and count program
total = 0
count = 0
avg = 0
num = None
# Ask user to input number, if number is 0 print calculations
while (num != 0):
try:
num = float(input('(Enter \'0\' when complete.) Enter num: '))
except:
print('Error, invalid input.')
continue
count = count + 1
total = total + num
avg = total / count
print('Average: ' + str(avg) + '\nCount: ' + str(count) + '\nTotal: ' + str(total))
Instead of doing what it asked for, let the user enter 'done' to complete the program, I used an integer (0) to see if the user was done inputting numbers.
Keeping your Try-Except approach, you can simply check if the string that user inputs is done without converting to float, and break the while loop. Also, it's always better to specify the error you want to catch. ValueError in this case.
while True:
num = input('(Enter \'done\' when complete.) Enter num: ')
if num == 'done':
break
try:
num = float(num)
except ValueError:
print('Error, invalid input.')
continue
I think a better approach that would solve your problem would be as following :
input_str = input('(Enter \'0\' when complete.) Enter num: ')
if (input_str.isdigit()):
num = float(input_str)
else:
if (input_str == "done"):
done()
else:
error()
This way you control cases in which a digit was entered and the cases in which a string was entered (Not via a try/except scheme).
I am trying to create an average solver which can take a tuple and average the numbers. I want to use the except hook to give an error message and then continue from the beginning of the while loop. 'continue' does not work.
import sys
z = 1
x = []
y = 1
i = 1
print('Welcome to the Average Solver.')
while z==1 :
def my_except_hook(exctype, value, traceback):
print('Please only use integers.')
continue
sys.excepthook = my_except_hook
print("Enter your set with commas between numbers.")
x=input()
i=len(x)
print('The number of numbers is:',i)
y=float(float(sum(x))/i)
print('Your average is', float(y))
print(' ')
print("Would you like to quit? Press 0 to quit, press 1 to continue.")
z=input()
print('Thank you for your time.')
As #PatrickHaugh noted, the keyword continue means nothing to my_except_hook. It is only relevant inside a while loop. I know this is what you are trying to do by having continue being called in the flow of a loop, but it's not really in the context of a loop, so it doesn't work.
Also, i is how many numbers you are, yet you set it as the length of the user input. However, this will include commas! If you want the real amount of numbers, set i = len (x.split (",")). This will find out how many numbers are in between the commas.
Never mind, I solved the problem. I just used a try-except clause...
z = 1
x = []
y = 1
i = 1
print('Welcome to the Average Solver.')
while z == 1:
try:
print("Enter your set with commas between numbers.")
x = input()
i = len(x)
y = float(float(sum(x)) / i)
print('Your average is', float(y))
print(' ')
print("Would you like to quit? Press 0 to quit, press 1 to continue.")
z = input()
except:
print('Please use integers.')
x = []
continue
print('Thank you for your time.')
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!