Attribute error using python3x - python

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.

Related

Keep asking for numbers and find the average when user enters -1

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)

How to make a function in python that gets the square for only digits values and does not give an error message when invoked by a string

I want to make a function in python that gets the square of digit values only and when invoked with a string it does not give an error and instead returns a message. This is what I have reached till now.
What I have tried:
def square(x):
answer = x
if answer == answer.int() :
print("the square of" ,x, "is", x*x)
if answer == answer.str() :
print("please enter a valid number to find its square")
but it gives me the error when invoked with a string such as "joe" as seen here:
Input In [114], in <cell line: 1>()
---> 1 square("joe")
Input In [113], in square(x)
1 def square(x):
3 answer = x
---> 4 if answer == answer.int() :
5 print("the square of" ,x, "is", x*x)
7 if answer == answer.str() :
AttributeError: 'str' object has no attribute 'int'
You can use type() to find the type of variable.
def square(x):
if type(x) is int:
print("The square of {} is {}".format(x, x*x))
else:
print("Please enter a valid number to print its square")
int() is a built-in function, not a method. You should be calling int(x) rather than x.int()
Use a try-except block. See below:
def square(x):
try:
x = int(x)
except ValueError:
print("Please enter a valid number to find its square")
return
print(f"The square of {x} is {x * x}")
You don’t need to do the logic on this yourself. Let Python handle the error checking (it will throw an error if the user enters a string into what should be an integer).
Instead, you would use try except to decide what to do next on encountering an error.
See the documentation here: https://docs.python.org/3/tutorial/errors.html
by using .int(), you are taking a value (in this case the variable "answer") and trying to turn it into an integer. The reason your code is bringing up errors is because you are using the int() function in the wrong way. Instead of using
if answer == answer.int() :
use
try:
answer = int(answer) #this will try to turn answer into an integer
except:
print("please enter a valid number to find its square") #if answer cannot be turned into an integer, than an error will be raised resulting in the execution of this code segment
it might be worth it to research the "try" and "except" functions more...

Getting " 'NoneType' Object has no attribute 'isdigit' " error on my code

with the code I'm trying to accomplish is that I'm asking the user to for a number between 1 and 12 and then display the times table for that number.
The while loop checks if it's not a number or if its less than 1 or more than 12 then it will loop until it input is correct. However I get the error (written on the title)
Any ideas how to fix this?
user_input = print('Input number between 1-12: ')
#While loop to keep checking the following conditions
while (not user_input.isdigit()) or (int(user_input < 1) or int(user_input > 12)):
print("Please input a number between 1-12")
user_input = print("Input selection >> ")
#Now convert user_input into an int
user_input = int(user_input)
print('------------------------------------------')
print()
print(f'This is the {user_input} times table')
print()
for i in range(1,13):
print(f'{i} x {user_input} = {i*user_input}')
user_input = input('Input number between 1-12: ')
#While loop to keep checking the following conditions
while (not user_input.isdigit()) or (int(user_input)< 1 or int(user_input) > 12):
list of issues:
you printed instead of input to receive input from the user
you attempted to use < on instances of str and int, instead you should check this outside the int conversion to make sure that you trying to use < which both operands are int
user_input = print('Input number between 1-12:')
The above line only print out Input number between 1-12: to the console, it does not ask for the user to input anything. Since the print() function displays the string inside it and returns None, you get the error that you're getting.
If you want to take user input, then use the input() function like,
user_input = input("Input number between 1-12: ")
The above line will prompt the user to input something while also displaying the text

My for loop isn't working

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):.

python checking user input for number in a while loop

I have a function below which is part of my big main function, what I want this function to do is that whenever called, I want the function to check if the user input is
a number or not. If it is a number it will return the number and break.
But if it is not a number I want it to loop again and again.when I try to
run it, it gives me unexpected an error:
unexpected eof while parsing
can any body help me what I am missing or how I should rearrange my code? thank you!
def getnumber():
keepgoing==True
while keepgoing:
number = input("input number: ")
result1 = number.isdigit()
if result1 == 1:
return number
break
elif keepgoing==True:
A neater and clearer what to do what you are already doing:
def getnumber():
while True:
number = input("Input number: ")
if number.isdigit():
return number
That's all you need, the extra variables are superfluous and the elif at the end makes no sense. You don't need to check booleans with == True or == 1, you just do if condition:. And nothing happens after return, your break will never be reached.
You don't need the last line:
elif keepgoing==True:
It's waiting for the rest of the file after the :.
Side note, it should be a single = in the first part, and can just be written simpler as well.
def getnumber():
while True:
number = input("input number: ")
result1 = number.isdigit()
if result1:
return number
Since you're inside the while loop, it'll keep executing. Using return will end the while loop, as will breaking and exiting the program. It will wait for input as well each time, though.
While assigning you have used keepgoing == True, I think it should be keepgoing=True
The following solution works on my machine, although I am running Python 2.7
def get_num():
while True: #Loop forever
number_str = raw_input("> Input a number: ") #Get the user input
if number_str.isdigit(): #They entered a number!
return int(number_str) #Cast the string to an integer and return it
I used raw_input rather than input, because raw_input gives you the exact string the user entered, rather than trying to evaluate the text, like input does. (If you pass the 12 to input, you'll get the number 12, but if you pass "12", you'll get the string '12'. And, if you pass my_var, you'll get whatever value was in my_var).
Anyway, you should also know that isdigit() returns whether or not the string has only digits in it and at least one character - that is not the same thing as isNumber(). For instance, "123".isdigit() is True, but "123.0".isdigit() is False. I also simplified your loop logic a bit.

Categories