the program i have writen is meant to take the users input which is a integer then times it with the range of 1-10 so userinput x 1-10. however when i run my program an error occurs saying 'bool' is not iterable..
im new to coding so please go easy <3
Heres my code:
And heres the error:
Traceback (most recent call last):
File "", line 1, in
loop()
File "C:/Users/chemg/AppData/Local/Programs/Python/Python35-32/loop1.py", line 6, in loop
for numbers in number in range(1,10):
TypeError: 'bool' object is not iterable
this error occurs after the user enters a value
Let's break this line up
for numbers in number in range(1,10):
range(1,10) => 1..10
number in range(1,10) => True/False, but what is 'number'? 0? So, 'False'
numbers in number in range(1,10) => Error!!! There are no 'numbers' in 'False'
Maybe you meant to do this?
for number in range(1,10):
# do something
You also have an error later where you are trying to print 4 things, but only specified 3 in the format().
print("Here it is {0}:\n {1} x {2} = {3}".format(number,add,name))
And you put name as {2}, so that would have printed something like
Here it is 1: 7 x James = ??
So, you can fix that by
add=int(input("Enter number and i will display the times table: "))
for number in range(1,10):
print("{0} x {1} = {2}".format(add, number, add*number))
You also probably don't want to store the result of the multiplication into 'add' because for each iteration of the loop, 'add' will be the value from the previous iteration rather than what the user entered which doesn't produce a multiplication table. In fact all your results will be 0 for the below:
for number in range(10):
print('{0} * {1}'.format(add, number))
add = add*number
print("Result:{0}".format(add))
Test in your cli with range(1,10) as you had in your code originally so it starts with 1 instead of 0 and you will see the results aren't a multiplication table:
for number in range(1,10):
print('{0} * {1}'.format(add, number))
add = add * number
print(add)
Here is a complete version with all the changes:
def loop():
name=input("Enter name: ").capitalize()
print("Hey {0}".format(name))
add=int(input("Enter number and i will display the times table: "))
for number in range(1,10):
product = add * number
print("Here it is {0}:\n {1} x {2} = {3}".format(name,add,number,product))
In your for loop number is a single variable ,not a iterable ,and it is an invalid syntax , so replace ur code with the below and
No need to write number=0,
def loop():
name=input("Enter name: ").capitalize()
print("Hey {0}".format(name))
add=int(input("Enter number and i will display the times table: "))
for number in range(1,11): # last value is not included so to iterate up to 10 write 11
product= add*number
print(" {1} x {2} = {3} \n ".format(number,add,product))
Ok i seemed to have done it. its probably what the answers put, but this is what i came up with
def loop():
numbers=int(input("Enter a number: "))
add=numbers
for number in range(1,900000000000):
numbers= add*number
print("{0} x {2} = {1}".format(add,numbers,number))
number in range(1,10) is being evaluated to False (because 0 isn't in range(1,10), so for numbers in False is causing problems.
You probably just want for number in range(1,10):.
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)
I would like to write a program that uses a while loop to repeatedly prompt the user for numbers and adds the numbers to a running total. When a blank line is entered, the program should print the average of all the numbers entered. I also would like to use a break statement to exit the while loop.
My Incorrect Work:
y = "\n"
total = 0
k = 0
while True:
x = input("Enter your number here: ")
x = float(x)
total = total + float(x)
k = k + 1
if type(x) != int:
print(total/k)
break
Be aware that the function input() will always outputs a string, so type(input()) != int will always be true.
Try using try-except function, when there is ValueError (example unable to convert blank/letters to float), the exception will be raised and break the loop:
total = 0
k = 0
while True:
x = input("Enter your number here: ")
try:
total += float(x)
k += 1
except ValueError:
if k > 0: #to avoid division by zero
print("Average: ", total/k)
break
Output:
Enter your number here: 3
Enter your number here: 4
Enter your number here: 5
Enter your number here:
Average: 4.0
Bearing in mind the comments already made, here is one such way to perform your task and finishing up when a blank entry is encountered.
total = 0.0
k = 0.0
while True:
x = input("Enter your number here: ")
if (x == " "): # Check for a blank line entry here before attempting to convert to float
print("Average is:", (total/k))
break
x = float(x)
total = total + float(x)
k = k + 1
As noted in the comments, one should check for the blank line entry prior to attempting to convert the entry.
You are immediately casting the value of x that is inputted to a float. So,
if type(x) != int
always is true, meaning the loop breaks after one iteration every time.
Others have already solved your problem in different ways, but I think that explaining our thinking might also be useful.
Currently, your program is not checking correclty the exit condition (empty line is entered instead of a number). When a new line is entered, your program should do one of the two possible scenarios:
when an empty line is entered: print result & exit (break)
else (assume a number is entered): add number to total
No third option is specified, so for now, let's assume that every line will either be an empty line or a number. Will expand it later.
After you decided what to do, the actions should just be easily wrapped in a while True: block - so it should be:
initialize_variables_total_and_count
while True:
read_line
decide_what_to_do:
# in case line was a number
convert_line_to_float
add_float_to_total
increment_count
other_case:
# empty line was entered
calculate_and_print
break
With only two options, you only need to decide once what to do. You can swap around the cases by deciding which condition to check for (and that also results in the other being the "default" behavior for other cases).
It's simpler to check for the line being empty with if line_entered == "":. In this case, any non-empty line is treated like a number, and if it were not one, the float() function will error out and your program crashes.
Checking if a string (the entered line) can be converted to a float is a bit harder. There is just no built-in for that in python, but there is a trick: you can try to convert it to a float, and if that works, it was convertible, and if that errors, it was not. There are other ways too, but this is the simplest - see this question on the topic.
In this case, every number will be added to the total, and every non-number (including the empty line, but also random strings like "asdf") will cause the program to calculate the total and stop.
You can avoid putting both cases into an if-else block by using break or continue. (technicly, you never need to use break or continue, all programs can be written without them. In this case, you could have a boolean variable, named run for example, write while run: and instead of break, do run = False). You can use the fact that both break and continue end the loop early to avoid placing the second case inside an else-block and still have the same behavior (as break and continue already causes skipping the rest of the loop body).
So an example implementation: (testing for == "", not using unstructured control flow)
total = 0
count = 0
run = True
while run:
line = input("Enter your number here: ")
if line == "":
print(total / count)
run = False
else:
total += float(line)
count += 1
I also renamed k to count, x to line and used in-place addition operators.
Another implementation, with break, testing for float with try/except (and re-using that for the entire control flow):
total = 0
count = 0
while True:
line = input("Enter your number here: ")
try:
# order matters here. If the first line errors out, the second won't happen so the count will only be inremented if it was indeed a float
total += float(line)
count += 1
except:
print(f"Average is: {total / count}")
break
Here I removed the run variable, and used a format string to print a bit fancier.
And an example using both continue and break:
total = 0
count = 0
while True:
line = input("Enter your number here: ")
if line != "":
total += float(line)
count += 1
continue
print(f"Average is: {total / count}")
break
You can fancy it a bit with adding more error handling - use three cases:
user entered empty line: print & exit
user entered a number: add to total
user entered something else: ignore line, but tell user what to do
I only provide one example implementation for this, but as you can see, it can be implemented in many ways.
total = 0
count = 0
# good practice to tell the user what to do
print("Average calcuator. Enter numbers one per line to calulate average of, enter empty line to print result & exit!")
while True:
line = input("Enter your number here: ")
if line == "":
print(f"Average is: {total / count}")
break
else:
try:
total += float(line)
count += 1
except ValueError:
print("You should enter a number or an empty line to calculate & exit!")
i'm a beginner in python, i'm using python 3x, i'm getting an 'attribute error' : 'NoneType' object has no attribute 'isdigit' on line 4 of my program.
Q: Use a "forever" while loop to get user input of integers to add to sum,
until a non-digit is entered, then break the loop and print sum .Here is the program :
sum = 0
num=""
while True:
num=print("input no. :")
if num.isdigit():
sum=sum+int(num)
else:
break
print("sum is :",sum)
what must be the modification to be done to modify the program.
thanks
num = print("input no. :")
print simply prints, it has no return value. You are looking for input:
num = input("input no. :")
As a side note, sum is a built-in function and it is not a good idea to overwrite it, so pick another name for sum.
I am trying to write a program that will add together a series of numbers that the user inputs until the user types 0 which will then display the total of all the inputted numbers. this is what i have got and im struggling to fix it
print ("Keep inputting numbers above 0 and each one will be added together consecutively. enter a and the total will be displayed on the screen. have fun")
number = input("Input a number")
sum1 = 0
while number >= 1:
sum1 = sum1 + number
if number <= 0:
print (sum1)
Here is a more robust way to input the number. It check if it can be added. Moreover I added the positive and negative number.
# -*-coding:Utf-8 -*
print ("Keep inputting numbers different than 0 and each one will be added together consecutively.")
print ("Enter a and the total will be displayed on the screen. Have fun.")
sum = 0
x = ""
while type(x) == str:
try:
x = int(input("Value : "))
if x == 0:
break
sum += x
x = ""
except:
x = ""
print ("Please enter a number !")
print ("Result : ", sum)
If you're using Python 3, you will need to say number = int(input("Input a number")) since input returns a string. If you're using Python 2, input will work for numbers but has other problems, and the best practice is to say int(raw_input(...)). See How can I read inputs as integers? for details.
Since you want the user to repeatedly enter a number, you also need an input inside the while loop. Right now it only runs once.
import random
print('-\n')
begin=int(raw_input('-\n')
end=int(raw_input('-\n')
rep=int(raw_input('-\n')
def dop():
print random.randinterga
ivfhoierh
while count < rep:
print do
count = count + 1
print('Thanks for using this program!\n')
raw_input('press enter to continue')
Okay, so I really have no idea what iv've done wrong but I keep getting a syntax error and IDLE highlights 'end'.
Edit: C
This is how I would do this:
import random
print 'I will print out random integers from a range you specify.'
begin = int(raw_input('Please enter the starting range: '))
end = int(raw_input('Please enter the end range: '))
rep = int(raw_input('Please enter the repeat value: '))
def get_random():
return random.randint(begin, end)
for _ in range(rep):
print get_random()
Attention to detail is so important.
Problems addressed:
Mismatched parentheses
Inconsistent assignments
Inconsistent use of print
Personal preference over returning, then printing
Renamed function do() for clarity
raw_input() doesn't need \n new lines
randint() gets upset generating ValueError: non-integer arg 1 for randrange() on float values; cast the raw_input() accordingly
(Minor) Corrected spelling in output
Replaced while loop with for loop, removing unneeded variable count and assignments
Hope this helps!
I guess you are using Python 2, judging by raw_input.
Correct your code to:
import random
print 'Hi, I will print out random intergers from a range you specify.\n'
#No need for parenthesis
begin=float(raw_input('Please enter the starting range. \n'))
end=float(raw_input('Please enter the end range. \n'))
rep=float(raw_input('Please enter how many times you cant to repeat the function. \n'))
# ERROR you forgot an extra parenthesis on the end of each of the last 3 lines.
def do():
print random.randint(begin, end)
count = 0
while count < rep:
do() # <- Parenthesis, and no need to print.
count = count + 1
print 'Thanks for using this program!\n' #No need for parenthesis
raw_input('press enter to continue')
Also this:
count = 0
while count < rep:
do() # <- Parenthesis, and no need to print.
count = count + 1
Can be replaced by this:
for count in range(rep):
do()