If you want to emulate similar user behavior to scanf
you need three things:
-
raw_input()
: to read the user's input, return a string str
(ASCII in Python 2).
-
str.split()
: allows you to divide the string using another string passed as an argument. If nothing happens, divide by using blank spaces, in addition to deleting them from the beginning and end of the chain. Returns a list of strings.
-
int()
: to do an entire casting of the elements returned by str.split
.
To apply the casting on each item you can use a for in
:
entrada = raw_input("Ingrese Dia, Mes y Año de nacimiento"
"(Separados por un espacio): ")
dia_n, mes_n, anio_n = (int(item) for item in entrada.split())
or you can use map
to use a functional approach:
entrada = raw_input("Ingrese Dia, Mes y Año de nacimiento"
"(Separados por un espacio): ")
dia_n, mes_n, anio_n = map(int, entrada.split())
In the case of printf
you can use the old format with %
similar to C:
print "Años: %d Meses: %d" % (anio, mes)
or use str.format
:
print "Años: {} Meses: {}".format(anio, mes)
In Python 2 the default source code uses ASCII, so the appropriate encoding must be specified in the first or second line of the script if it is not. To use the ñ
as such in the string literal ( print "Años: ..."
) you can use UTF-8:
#-*- coding: utf-8 -*-
and remember to save the script with this encoding.
The rest of the code does not imply any more problems, it can be translated as is to Python just by changing the keys by the appropriate indentation and eliminating the ;
since they are unnecessary.
In Python 3 the idea is the same, only that you have to replace raw_input
with input
and print
is a function. Also for Python> = 3.6 you can (and owe efficiency) using formatted string literals:
entrada = input("Ingrese Dia, Mes y Año de nacimiento"
"(Separados por un espacio): ")
dia_n, mes_n, anio_n = (int(item) for item in entrada.split())
...
print(f"Años: {anio} Meses: {mes}")
In Python 3 the interpreter uses UTF-8 by default for the source code, so it is not necessary to specify the encoding if UTF-8 is used in the file.