This question already has an answer here:
time.sleep - TypeError: A Float is Required [closed]
(1 answer)
Closed 8 years ago.
I want to make a metronome. My code is:
import time
import sound
metronome = raw_input("")
int(metronome)
while 1==1:
sound.play_effect('Drums_02')
time.sleep(metronome)
When I run this code it comes up with an error message saying "A float is required."
I was woundering if anyone could make sense of it.
int(metronome) does not convert metronome into an integer. It creates a new int, and then discards it because you don't do anything with it. You want to instead pass that along to your sleep call:
time.sleep(int(metronome))
Or, if you're using it in multiple places, assign metronome an int value in the first place:
metronome = int(raw_input(""))
int(metronome)
does nothing to the variable except for printing the int representation of the string.
You wanted to say:
metronome = int(metronome)
or
metronome = int(raw_input(""))
metronome is still as string, not an integer. Store the result of int() back into the variable:
metronome = int(mentronome)
Related
This question already has answers here:
Transform string to f-string
(5 answers)
Closed 2 years ago.
I'm trying to pull a string from JSON, then convert it to an f string to be used dynamically.
Example
Assigned from JSON I get
whose_fault= "{name} started this whole mess"
How to build a lambda to convert it to an f-string and insert the given variable? I just can't quite get my head around it.
I know similar questions have been asked, but no answer seems to quite work for this.
Better question. What's the most pythonic way to insert a variable into a string (which cannot be initially created as an f-string)?
My goal would be a lambda function if possible.
The point being to insert the same variable into whatever string is given where indicated said string.
There is no such thing as f-string type object in python. Its just a feature to allow you execute a code and format a string.
So if you have a variable x= 2020, then you can create another string that contains the variable x in it. Like
y = f"It is now {x+1}". Now y is a string, not a new object type,not a function
This question already has answers here:
How can I check if a string represents an int, without using try/except?
(23 answers)
Closed 3 years ago.
I've began a very basic program where you have to find the number randomly chosen by the computer. I successfully added the randomizer to the program, yet I couldn't find how to compare the type of the asked number so that a message is printed whenever you type letters instead of numbers for example.
I tried this type of command
if type(nbredevine)!=int:
print ("""I asked you for an integer. Don't mess with me.""")
unfortunately this isnt working, and even though I've searched for it in the internet and on this site, i haven't been able to find something that fits this special situation.
I haven't been able to make the isinstance function work in this case. Is it because I'm too much of a neophyte ?
Thank you guys, and happy holidays for those of you who are in holidays.
When you use input, you always get a string. If the string contains only digits, it can be converted to an integer, but it's still a string. There are a couple of things you can do.
If you are only interested in non-negative integers, you can check using str.isdigit:
if nbredevine.isdigit():
value = int(nbredevine)
# use integer value
else:
print('Not an integer')
If you want to bypass all the fluff and check directly, you can just try converting to an integer:
try:
value = int(nbredevine)
except ValueError:
print('Not an integer')
else:
# use integer value
This question already has answers here:
Python - is there a way to store an operation(+ - * /) in a list or as a variable? [duplicate]
(2 answers)
assign operator to variable in python?
(5 answers)
Closed 9 months ago.
I'm a beginner in Python and I can't figure out the assignment of an operator to a variable.
I've read assign operator to variable in python? but I still can't figure out my problem.
a = str(+)
This line of code gives an Invalid Syntax Error.
Whereas, a =input() works completely fine when we give an operator as input. This operator is stored as string type because whatever you enter as input, input function converts it into a string.
Why str() is not able to store an operator as a string whereas input() can do the same task without any error?
Based on the other post, you'd have to do
import operator
a = operator.add
The answer there just does a lookup in a dictionary
You're not giving an operator to input(), you're always inputting and outputting a string, which could be any collection of characters & symbols
+ is not an identifier or value of any kind; it is part of Python's syntax. You probably want a = str("+") (or simply a = "+").
input doesn't take a value; whatever environment you are running in already takes care of converting your keystrokes to strings for input to read and return.
If you want a to be a callable function, then you can use operator.add as mentioned in #cricket_007's answer (though not passed through str, but used directly per my comment to that answer).
To add to the above answers you can validate the input as an integer:
while True:
try:
userInput = int(input('Enter a number:> '))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
break
This question already has answers here:
Convert a string to integer with decimal in Python
(8 answers)
Closed 6 years ago.
I'm trying to change a value, which is parsed through CGI over GET to Python before I want to send all the values over MQTT with JSON.
The value is as follows:
exposure = "0.0"
which is gained over CGI like so:
if form.getvalue("exposure"):
req["excompensaton"] = form.getvalue("exposure")
Sadly, however, the value needs to be "0", not "0.0" before I can send it over MQTT with JSON.
I've tried:
if form.getvalue("exposure"):
req["excompensaton"] = int(form.getvalue("exposure")
Sadly this came up with the error:
ValueError: invalid literal for int() with base 10: '0.0'
I also tried math.floor, but it ended up telling me that it needs to float.
Any help would be really appreciated!!
If the behavior of int() is what you want, cast to a float first:
int(float(form.getvalue("exposure")))
If you want to be certain of getting one of math.floor() or math.ceil(), you can incorporate those:
int(math.floor(float(form.getvalue("exposure"))))
This question already has answers here:
How do I convert a currency string to a floating point number in Python?
(10 answers)
Closed 7 years ago.
I've looked through the 'currency' threads, but they're all for going the other way. I'm reading financial data that comes in as $1,234.56 &c, with everything a string. I split the input line, and want to convert the value item to float for add/subtract (I'm mot worried about roundoff error). Naturally, the float() throws an error.
I could write a function to call as 'amount = float(num(value_string)), but woder if there's a "dollar_string_to_float()" function in one of the 32,000 Python modules.
I think this question is slightly different from this question, but I'm not sure.
Anyway, the code from the afformentioned question just need one function change from Decimal to Float and the removal of the Decimal import.
As you requested, the code is in a dollar_string_to_float function:
>>> from re import sub
>>> def dollar_string_to_float(s):
return float(sub(r'[^\d.]', '', money))
>>> money = '$1,234.56'
>>> print dollar_string_to_float(money)
1234.56
Look into the regular expressions module. You can compile a pattern that matches your dollars/cents format and extract the floating-point number from it.