You can even use the operator or
to something as you wish because this operator will evaluate the first operand and return it if it is evaluated as true or return the second operand (without evaluating it).
So it would be possible to do something like:
def foo(x):
return x or '42'
print(foo(False)) # 42
print(foo(0)) # 42
print(foo(True)) # True
print(foo('1')) # 1
But you won’t be able to numero[-3] or '0'
to return '0'
when the value numero[-3]
does not exist, because in Python an exception will be released IndexError
, interrupting the execution of the operator or
.
The equivalent of that would be
try:
return numero[-3]
except IndexError:
return '0'
Or check whether the string numero
has at least three characters.
Anyway, nothing justifies not using the mathematical solution to solve the problem of obtaining the digit of hundreds:
centena = (numero // 100) % 10
Being numero
a numerical value. This will already return to 100, when it exists, or 0 if the value is less than 100, as Fernando mentioned in the comments.
And what would be the -3 position of this string?
– Woss
a hundred a number
– Diovani
And what do you expect with the check? Return zero if the number does not have the hundred?
– Woss
Math doesn’t solve? Example:
numero // 100 % 10
returns to hundred or zero...– fernandosavio
Just what I wanted to do
– Diovani
@fernandosavio sure will do but there is no way to do as I exemplified?
– Diovani
number
andnumero
are the same thing? If yes,trunc
returns an integer value, not an string.– Woss
@Woss I had spelled wrong excuse, now this as in my code
– Diovani
1) You are converting the
input()
to float and then toint
through themath.func()
.. So I don’t know why you’re trying to work with strings in your code. 2) "there is no way to do as I exemplified" Don’t get it, do you want a solution to the problem or do you want your solution to work? Because I believe you tried to use it and it didn’t work...– fernandosavio
@fernandosavio I’m starting now in python and I thought this way would avoid some crash problems in the codeword, like a person typing a broken number. "as I exemplified" would be like in the javascript itself where a variable can receive a value or other. EX:
variavel = input || 'nada'
. where input would be any string and if the user did not type something the value of the variable would be 'nothing'– Diovani
If you want to ensure that an entire number has been typed, just use
int
and capture theValueError
. Ex: https://ideone.com/ejw5YH - in this case I ask the user to enter another number, but you could simply set another value in the variable within the blockexcept
, for example. Do not cling to what other languages do, each one is one way and there is not always an equivalence 1 to 1 of all resources.– hkotsubo