This question already has answers here:
What are variable annotations?
(2 answers)
Closed 2 years ago.
I am starting out practicing python and came across this little code on leetcode:
def maxProfit(self, prices: List[int]) -> int:
Could someone please explain what the colon after prices does and what does List[int] and -> do?
I've just used a colon to slice lists/strings and denote the start of a code block indentation.
Reading online I realized that prices : List[int] means that price is the argument name and the expression means that prices should be a list of integers and the return type of the function should be an integer.
Can someone tell me if this is correct or would like to expand on it?
They are type annotations, List[int] refers to prices being a list of ints. While -> gives the type of the returning value, here maxProfit is supposed to return an int.
You are not required to use them.
Those are called annotations or type hints. They basically tell the python interpreter of what type the input parameters should be and what is the function going to return.
So in
def maxProfit(self, prices: List[int]) -> int:
List[int] signifies that the function is expecting a list of integers as the input value of prices. But for it to actually work you have to import List from typing module.
Then -> int signifies that the functions return value is of type integer.
These will not make the code any better, but are helpful for autocomplete and profiling the code. If you are a beginner you don't have to worry about these just now.
Related
This question already has answers here:
What is the return value of the range() function in python?
(5 answers)
Closed 6 months ago.
On an online course, the teacher says that range() produces a tuple, adding that this is the reason why we have to convert it into a list (thanks to the list() function) if we want to modify it.
Is this statement true ?
Because in the official documentation, they dont talk about tuple at all in the range() section : https://docs.python.org/3/tutorial/controlflow.html#the-range-function
Starting with python3, range returns a range object which is a sequence type which, among other things, can be iterated to create a list out of it.
Relevant docs about the range type.
Before that, it used to return a list, like Klaus commented. (docs)
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:
What are type hints in Python 3.5?
(5 answers)
Closed 4 years ago.
I have seen people using
def testing(cha: List[Dict]) -> List[List[Dict]])
I would like to know what is this function for and what is the "->" for?
I understand that it take the dictionary with value "cha" which is in list of dictionaries and convert it to list list of dictionaries.
Is my understanding above a correct one? If no, could someone please show me some simple example?
That is Python's type hinting. It's just syntactic sugar to help the developer reading your code get a sense of what type of input your function is expecting and what type of output it should return. Types to the left of -> denote the input type, and types to the right of -> denote the return type. In your example,
def testing(cha: List[Dict]) -> List[List[Dict]]:
...
testing is a function that is supposed to accept a list named cha which contains dictionaries and return a list which contains lists which in turn contain dictionaries. Something like this,
>>> testing([{'a':12, 'b':34}])
>> [[{'a':12, 'b':34}], [{'a':24, 'b':68}]]
That being said, Python is still a dynamically typed language and type hints don't add any compiler optimizations to your code. All type checking still happens at runtime. There is nothing stopping you from violating type hints of your function, which means I could pass any type of argument to testing and it would still try to use it as valid input.
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
Having trouble understanding why this is returning a str although I entered an int. Could someone please explain this? When you enter a value in input does it only capture the value as a string?
In Python 3.x, input returns the entered value as is (str) instead of evaluating it, so you should do int(input('Please input number:')) to get the value as an int.
In Python 2.x, however, raw_input would return the raw str value, while input would evaluate the entered value, as you can read on the docs:
input([prompt])
Equivalent to eval(raw_input(prompt)).
...
Consider using the raw_input() function for general input from users.
You can mimic this behavior in Python 3.x with eval: eval(input('Please input number:')) if you really need to, but first take a look at Security of Python's eval() on untrusted strings?
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)