EOF error in nested loops - python-3.x

This program is a bit of a pain. It has to find the average tempearatures. If it is below 60, it must count how many numbers (that were averaged out) were below 60. It must do the same for any number above 80 if the average temperature is above 80. EDIT: instead of asking the user for the # of values, the program will keep accepting until given a blank value. This is my program:
def main():
sums = 0.0
count = 0
heating = 0
cooling = 0
temp = (input("enter a number, <enter> to quit: "))
while temp != " ":
x = float(temp)
sums = sums + x
count = count + 1
temp = eval(input("enter a number, <enter> to quit: "))
avg = sums/count
if avg < 60:
if temp < 60:
heating = heating + 1
if avg > 80:
if temp > 80:
cooling = cooling + 1
print(avg, heating, cooling)
main()
This is the error I keep getting. I have tried variations of asking for the input with and without the eval, and also with switching the temp between float and int. I keep getting errors, more commonly, this one.
Traceback (most recent call last):
File "C:/Python33/heatingcooling.py", line 24, in <module>
main()
File "C:/Python33/heatingcooling.py", line 13, in main
temp = eval(input("enter a number, <enter> to quit: "))
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
Any ideas on how to get this program to run would be much appreciated. As a side note, we are not allowed to use raw inputs, which seemed to be the most common solution for this

Your current loop confuses temp with x a few places. You need to be consistent about them because they're different types (temp is a string and x is a float). Here's a fixed version of the code, with a few other fixes, like testing for an empty string and providing an initial value for avg:
sums = 0.0
count = 0
heating = 0
cooling = 0
avg = 0 # need an initial value for this, in case the first input is empty!
temp = input("enter a number, <enter> to quit: ") # temp is always a string
while temp: # equivalent to testing temp != ""
x = float(temp)
sums = sums + x
count = count + 1
avg = sums/count
if avg < 60:
if x < 60: # compare to x here, not temp
heating = heating + 1
if avg > 80:
if x > 80: # here too
cooling = cooling + 1
temp = input("enter a number, <enter> to quit: ") # moved this to the end of the loop
print(avg, heating, cooling)

Assuming you're in Python 3.x, removing the eval() should work with the input(...)
temp = input("enter a number, <enter> to quit: ")
The Python 3 documentation for input can be found here
Edit It sounds like you need to convert your temp variable into an int after you get it from the input() method, which is a str by default.
temp = float(input("enter a number, <enter> to quit: "))
Also, when you get your first temp variable, remove the outside parentheses:
temp = (input("enter a number, <enter> to quit: "))
to
temp = input("enter a number, <enter> to quit: ")
Assuming your enter a numeric value, you should then be able to cast this value to a float once inside the while loop.
Edit2
In your while loop change it to this:
while temp: # or while temp != ""
# etc.
This will resolve the ValueError: could not convert string to float error. You were terminating the while loop upon entering a space " ", but when the user hits enter, the input is really an empty string "". Thus, you were still entering the while loop and then trying to cast the empty string "" input into a float, which then raised the ValueError.

Related

Why does PyCharm not let me add a break statement inside a loop to terminate it?

To write a code to display the Fibonacci sequence to "n" number of values, there needs to be a condition stating that if a negative number or a number = 0 is entered, then the loop needs to be terminated and restarted. However, when I try this with my code, it shows me an error.
Here is my code:
`
nterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
break
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Here is my error:
File "C:\User\users\u\Documents\Code\Python\schoolprojects2\venv\Flow of control.py", line 10
break
^
SyntaxError: 'break' outside loop
Process finished with exit code 1
`

How to exit "While True" with enter key | Throws Value Error can't convert str to float

I have converted the base program into two functions. I need to be able to exit the program by hitting the enter/return key but when I do, it throws a ValueError: could not covert string to float.
I have tried assigning the var(x) outside of the loop and also tried using an if statement to close but the issue seems to be with the float attached to the input. I'm wondering if I can move the float statement to another part of the program and still get the correct output?
import math
def newton(x):
tolerance = 0.000001
estimate = 1.0
while True:
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference <= tolerance:
break
return estimate
def main():
while True:
x = float(input("Enter a positive number or enter/return to quit: "))
print("The program's estimate is", newton(x))
print("Python's estimate is ", math.sqrt(x))
if name == 'main':
main()
My expectation is that when the user hits the enter key, the program will end with no errors. The float is needed for the program.
File "C:/Users/travisja/.PyCharmCE2019.2/config/scratches/scratch.py", line 13, in main
x = float(input("Enter a positive number or enter/return to quit: "))
ValueError: could not convert string to float:
You're getting the error because it's trying to convert the input received when hitting just Enter (an empty string) to a float. An empty string can't be converted to a float, thus the error.
You can re-structure your code easily, though:
import math
# Prompt the user for a number first time
input_val = input("Enter a positive number or enter/return to quit: ")
# Continue until user hits Enter
while input_val:
try:
x = float(input_val)
print("The program's estimate is", newton(x))
print("Python's estimate is ", math.sqrt(x))
# Catch if we try to calculate newton or sqrt on a negative number or string
except ValueError:
print(f"Input {input_val} is not a valid number")
finally:
input_val = input("Enter a positive number or enter/return to quit: ")

Find average of given numbers in input

I've to create a program that computes the average of a collection of values entered by the user. The user will enter 0 as a sentinel value to indicate that no further values will be provided. The program should display an appropriate error message if the first value entered by the user is 0.
Note: Number of inputs by the user can vary. Also, 0 marks the end of the
input it should not be included in the average
x = int(input("Enter Values\n"))
num = 1
count = 0
sum = 0.0
if x == 0:
print("Program exits")
exit()
while (x>0):
sum += num
count += 1
avg = (sum/(count-1))
print("Average: {}".format(avg))
You were not taking input inside while loop. You were taking input on the first line for once. So your program was not taking input repeatedly.
You may be looking for this -
sum = 0.0
count = 0
while(1):
x=int(input("Enter Values: "))
if x == 0:
print("End of input.")
break;
sum+=x;
count+=1;
if count == 0:
print("No input given")
else:
avg = sum/count;
print("Average is - ",avg)
Your code does not work because int function expect only one number.
If you insert the numbers one by one, the following code works:
num = int(input("Enter a value: "))
count = 0
sum = 0.0
if num <= 0:
print("Program exits")
exit()
while (num>=0):
sum += num
count += 1
num = int(input("Enter a value: "))
avg = (sum/count)
print(f"Average: {avg}")

input error in Python3.6

t = int(input())
while t:
qu , pt = input().split(' ')
qu = int(qu)
pt = int(pt)
sd = []
for i in range(0,qu):
x = int(input()) # I think I am getting problem in this part of
sd.append(x)
hd , cw = 0 , 0
diff = pt / 10
cwk = pt / 2
for i in range(0,qu):
if sd[i] <= diff:
hd += 1
else:
if sd[i] >= cwk:
cw += 1
if hd == 2 and cw == 1:
print ('yes')
else:
print('no')
t -= 1
When I try to give input like '1 2 3' I get an an error like this
Traceback (most recent call last):
File "C:/Users/Matrix/Desktop/test.py", line 8, in <module>
x = int(input())
ValueError: invalid literal for int() with base 10: '1 2 3'
Why am I seeing this problem ? How do I rectify this ?
The issue is that you're passing it a string rather than an integer. When you typed "1 2 3," you left spaces, which are considered characters. Spaces cannot be cast as integers. If your set on having the input as number space number space number space, then I suggest you split the sentence at the whitespace into a list.
def setence_splitter(user_input):
# splits the input
words = text.split()
Now you have the list, words, which will have each individual number. You can call each individual number using its index in words. The first number will be words[0] and so on.

Cumulative total from user's input string

I have tried to write a function that takes sequence of integers as input from the user and returns cumulative totals. For example, if the input is 1 7 2 9, the function should print 1 8 10 19. My program isn't working. Here is the code:
x=input("ENTER NUMBERS: ")
total = 0
for v in x:
total = total + v
print(total)
and here is the output:
ENTER NUMBERS: 1 2 3 4
Traceback (most recent call last):
File "C:\Users\MANI\Desktop\cumulative total.py", line 4, in <module>
total = total + v
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I don't know what this error means. Please help me to debug my code.
This code will work. Remember: read the code and learn how it works.
x = input("Enter numbers: ") #Take input from the user
list = x.split(" ") #Split it into a list, where
#a space is the separator
total = 0 #Set total to 0
for v in list: #For each list item
total += int(v) #See below for explanation
print(total) #Print the total so far
There are two new things in this code:
x.split(y) splits x up into a list of smaller strings, using y as the separator. For example, "1 7 2 9".split(" ") returns ["1", "7", "2", "9"].
total += int(v) is more complicated. I'll break it down more:
The split() function gave us an array of strings, but we want numbers. The int() function (among other things) converts a string to a number. That way, we can add it.
The += operator means "increment by". Writing x += y is the same as writing x = x + y but takes less time to type.
There is another problem with the code: You say you need a function, but this is not a function. A function might look like this:
function cumulative(list):
total = 0
outlist = []
for v in list:
total += int(v)
outlist.append(total)
return outlist
and to use it:
x = input("Enter numbers: ").split(" ")
output = cumulative(x)
print(output)
but the program will work just fine.
Cumulative totals
input_set = []
input_num = 0
while (input_num >= 0):
input_num = int(input("Please enter a number or -1 to finish"))
if (input_num < 0):
break
input_set.append(input_num)
print(input_set)
sum = 0
new_list=[]
for i in range(len(input_set)):
sum = sum + input_set[i]
new_list.append(sum)
print(new_list)

Resources