Reputation: 211
I am trying to generate a random number convert it to and int then print the number, but i am getting the error 'str' object is not callable. I have googled the problem but I cant seem to find what i am doing wrong.
here is my code:
import random
import time
while(True):
#generate a random frequency from 0Hz to 1MHz
frequency = int(random.randrange(0,1000000))
print('Frequency: %d'('frequency'))
print('Frequency: ',frequency, ' Hz')
print("sleep for 2 seconds")
time.sleep(2) # Delay for 1 minute (60 seconds)
The error i get is:
Traceback(most recent call last):
File "frequency1.py", line 7, in <module>
print('Frequency: %d'('Frequency'))
TypeError: 'str' object is not callable
Upvotes: 0
Views: 3967
Reputation: 52181
Your print statement is incorrect. It should instead be
print('Frequency: %d'%(frequency))
When you do 'Frequency: %d'(frequency)
, You are trying to call the string 'Frequency: %d'
as a function. This is why you get the error TypeError: 'str' object is not callable
. The error can be decoded as 'str' object
which is 'Frequency: %d'
is not callable i.e. it is not a function that can be called
You can try format
instead as it is better. Do read PEP - 3101 that mentions about format
and the %
operator. The print statement can be written as
print('Frequency: {}'.format(frequency))
The changed program after correcting the missing %
symbol can be written as
import random
import time
while(True):
#generate a random frequency from 0Hz to 1MHz
frequency = int(random.randrange(0,1000000))
print('Frequency: %d'%(frequency)) # Note the added %
print('Frequency: ',frequency, ' Hz')
print("sleep for 2 seconds")
time.sleep(2) # Delay for 1 minute (60 seconds)
This program on execution would give the following output.
Frequency: 753865
Frequency: 753865 Hz
sleep for 2 seconds
Frequency: 152017
Frequency: 152017 Hz
sleep for 2 seconds
Also note that the ,
in python adds a space. Hence you need not do print('Frequency: ',frequency, ' Hz')
but instead can directly write print('Frequency:',frequency, 'Hz')
.
Upvotes: 4
Reputation: 400109
String interpolation is done using the %
operator, but you're trying to call the string as if it were a function instead which explains the error.
It should be:
print("Frequency: %d" % frequency)
Note that the right-hand side of the %
only needs to be a tuple if there is more than one value, single values can be passed bare like above.
Also, in Python 3 it's more common with the more modern format()
syntax:
printf("Frequency: {}".format(frequency))
Upvotes: 2
Reputation: 391
>>> while(True):
... frequency = int(random.randrange(0,1000000))
... print('Frequency: %d'%frequency)
... print('Frequency: ',frequency, ' Hz')
... time.sleep(2) # Delay for 1 minute (60 seconds)
...
OUtput
Frequency: 720460 ('Frequency: ', 720460, ' Hz')
Frequency: 559979 ('Frequency: ', 559979, ' Hz')
Frequency: 649103 ('Frequency: ', 649103, ' Hz')
Upvotes: 1