From 8e0ceee41b8ace9ef28e4e1389f74e050e930c62 Mon Sep 17 00:00:00 2001 From: FedeHC Date: Tue, 14 Jan 2020 22:31:54 -0300 Subject: [sql/es] Translate SQL to Spanish --- es-es/sql-es.html.markdown | 115 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 es-es/sql-es.html.markdown diff --git a/es-es/sql-es.html.markdown b/es-es/sql-es.html.markdown new file mode 100644 index 00000000..8bb3aaac --- /dev/null +++ b/es-es/sql-es.html.markdown @@ -0,0 +1,115 @@ +--- +language: SQL +filename: learnsql-es.sql +contributors: + - ["Bob DuCharme", "http://bobdc.com/"] +translators: + - ["FedeHC", "https://github.com/FedeHC"] +lang: es-es +--- + +El lenguaje de consulta estructurada (SQL en inglés) es un lenguaje estándar ISO para crear y trabajar con bases de datos almacenados en un conjunto de tablas. Usualmente las implementaciones más usadas añaden sus propias extensiones al lenguaje; [Una comparación entre diferentes implementaciones de SQL](http://troels.arvin.dk/db/rdbms/) es una buena referencia sobre las diferencias entre distintos productos. + +Las implementaciones típicamente proveen de una línea de comandos donde uno puede introducir los comandos que se muestran aquí en forma interactiva, y también ofrecen una forma de ejecutar una serie de estos comandos almacenados en un archivo de script (mostrar que uno ha terminado con el prompt interactivo es un buen ejemplo de algo que no está estandarizado: la mayoría de las implementaciones de SQL soportan las palabras clave QUIT, EXIT, o ambas). + +Varios de estos comandos que sirven de ejemplo asumen que la [base de datos de empleados de muestra de MySQL](https://dev.mysql.com/doc/employee/en/) disponible en [github](https://github.com/datacharmer/test_db) ya ha sido cargada. Los archivos github son scripts de comandos, similares a los comandos que aparecen a continuación, que crean y cargan tablas de datos sobre los empleados de una empresa ficticia. La sintaxis para ejecutar estos scripts dependerá de la implementación de SQL que esté utilizando. Una aplicación que se ejecuta desde el prompt del sistema operativo suele ser lo habitual. + + +```sql +-- Los comentarios empiezan con dos guiones. Se termina cada comando con punto +-- y coma. + +-- SQL no distingue entre mayúsculas y minúsculas en palabras clave. Los +-- comandos de ejemplo que aquí se muestran siguen la convención de ser escritos +-- en mayúsculas porque hace más fácil distinguirlos de los nombres de las bases +-- de datos, de las tablas y de las columnas. + +-- A cont. se crea y se elimina una base de datos. Los nombres de la base de +-- datos y de la tabla son sensibles a mayúsculas y minúsculas. +CREATE DATABASE someDatabase; +DROP DATABASE someDatabase; + +-- Lista todas las bases de datos disponibles. +SHOW DATABASES; + +-- Usa una base de datos existente en particular. +USE employees; + +-- Selecciona todas las filas y las columnas de la tabla departments en la base +-- de datos actual. La actividad predeterminada es que el intérprete desplace +-- los resultados por la pantalla. +SELECT * FROM departments; + +-- Recupera todas las filas de la tabla departments, pero sólo las columnas +-- dept_no y dept_name. +-- Separar los comandos en varias líneas es aceptable. +SELECT dept_no, + dept_name FROM departments; + +-- Obtiene todas las columnas de departments, pero se limita a 5 filas. +SELECT * FROM departments LIMIT 5; + +-- Obtiene los valores de la columna dept_name desde la tabla departments cuando +-- dept_name tiene como valor la subcadena 'en'. +SELECT dept_name FROM departments WHERE dept_name LIKE '%en%'; + +-- Recuperar todas las columnas de la tabla departments donde la columna +-- dept_name comienza con una 'S' y tiene exactamente 4 caracteres después +-- de ella. +SELECT * FROM departments WHERE dept_name LIKE 'S____'; + +-- Selecciona los valores de los títulos de la tabla titles, pero no muestra +-- duplicados. +SELECT DISTINCT title FROM titles; + +-- Igual que el anterior, pero ordenado por los valores de title (se distingue +-- entre mayúsculas y minúsculas). +SELECT DISTINCT title FROM titles ORDER BY title; + +-- Muestra el número de filas de la tabla departments. +SELECT COUNT(*) FROM departments; + +-- Muestra el número de filas en la tabla departments que contiene 'en' como +-- subcadena en la columna dept_name. +SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%'; + +-- Una unión (JOIN) de información desde varias tablas: la tabla titles muestra +-- quién tiene qué títulos de trabajo, según sus números de empleados, y desde +-- qué fecha hasta qué fecha. Se obtiene esta información, pero en lugar del +-- número de empleado se utiliza el mismo como una referencia cruzada a la +-- tabla employee para obtener el nombre y apellido de cada empleado (y se +-- limita los resultados a 10 filas). +SELECT employees.first_name, employees.last_name, + titles.title, titles.from_date, titles.to_date +FROM titles INNER JOIN employees ON + employees.emp_no = titles.emp_no LIMIT 10; + +-- Se enumera todas las tablas de todas las bases de datos. Las implementaciones +-- típicamente proveen sus propios comandos para hacer esto con la base de datos +-- actualmente en uso. +SELECT * FROM INFORMATION_SCHEMA.TABLES +WHERE TABLE_TYPE='BASE TABLE'; + +-- Crear una tabla llamada tablename1, con las dos columnas mostradas, a partir +-- de la base de datos en uso. Hay muchas otras opciones disponibles para la +-- forma en que se especifican las columnas, como por ej. sus tipos de datos. +CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20)); + +-- Insertar una fila de datos en la tabla tablename1. Se asume que la tabla ha +-- sido definida para aceptar estos valores como aptos. +INSERT INTO tablename1 VALUES('Richard','Mutt'); + +-- En tablename1, se cambia el valor de fname a 'John' para todas las filas que +-- tengan un valor en lname igual a 'Mutt'. +UPDATE tablename1 SET fname='John' WHERE lname='Mutt'; + +-- Se borra las filas de la tabla tablename1 donde el valor de lname comience +-- con 'M'. +DELETE FROM tablename1 WHERE lname like 'M%'; + +-- Se borra todas las filas de la tabla tablename1, dejando la tabla vacía. +DELETE FROM tablename1; + +-- Se elimina toda la tabla tablename1 por completo. +DROP TABLE tablename1; +``` -- cgit v1.2.3 From 43cb5213104d3a7e1958eccb3fa3531a4ca511e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antonio=20Hern=C3=A1ndez=20Blas?= <1096022+nihilismus@users.noreply.github.com> Date: Wed, 5 Feb 2020 13:41:55 -0600 Subject: Limit document to 80 columns, where possible --- es-es/clojure-es.html.markdown | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/es-es/clojure-es.html.markdown b/es-es/clojure-es.html.markdown index 150d0bb2..937a7d95 100644 --- a/es-es/clojure-es.html.markdown +++ b/es-es/clojure-es.html.markdown @@ -10,8 +10,10 @@ lang: es-es --- Clojure es un lenguaje de la familia Lisp desarrollado sobre la Máquina Virtual -de Java. Tiene un énfasis mayor en la [programación funcional](https://es.wikipedia.org/wiki/Programación_funcional) pura -que Common Lisp, pero incluyendo la posibilidad de usar [SMT](https://es.wikipedia.org/wiki/Memoria_transacional) para manipular +de Java. Tiene un énfasis mayor en la +[programación funcional](https://es.wikipedia.org/wiki/Programación_funcional) +pura que Common Lisp, pero incluyendo la posibilidad de usar +[SMT](https://es.wikipedia.org/wiki/Memoria_transacional) para manipular el estado según se presente. Esta combinación le permite gestionar la concurrencia de manera muy sencilla @@ -19,7 +21,6 @@ y a menudo automáticamente. (Necesitas la versión de Clojure 1.2 o posterior) - ```clojure ; Los comentatios comienzan con punto y coma. @@ -29,8 +30,8 @@ y a menudo automáticamente. ; El "reader" (lector) de Clojure asume que el primer objeto es una ; función o una macro que se va a llamar, y que el resto son argumentos. -; El primer form en un archivo debe ser ns, para establecer el namespace (espacio de -; nombres) +; El primer form en un archivo debe ser ns, para establecer el namespace +; (espacio de nombres) (ns learnclojure) ; Algunos ejemplos básicos: @@ -78,9 +79,9 @@ y a menudo automáticamente. ; Colecciones & Secuencias ;;;;;;;;;;;;;;;;;;; -; Las Listas están basadas en las listas enlazadas, mientras que los Vectores en -; arrays. -; ¡Los Vectores y las Listas también son clases de Java! +; Las Listas están basadas en las listas enlazadas, mientras que los Vectores +; en arrays. +; Los Vectores y las Listas también son clases de Java! (class [1 2 3]); => clojure.lang.PersistentVector (class '(1 2 3)); => clojure.lang.PersistentList @@ -168,7 +169,8 @@ x ; => 1 (hello3 "Jake") ; => "Hello Jake" (hello3) ; => "Hello World" -; Las funciones pueden usar argumentos extras dentro de un seq utilizable en la función +; Las funciones pueden usar argumentos extras dentro de un seq utilizable en +; la función (defn count-args [& args] (str "You passed " (count args) " args: " args)) (count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" @@ -183,8 +185,8 @@ x ; => 1 ; Mapas ;;;;;;;;;; -; Mapas de Hash y mapas de arrays comparten una misma interfaz. Los mapas de Hash -; tienen búsquedas más rápidas pero no mantienen el orden de las claves. +; Mapas de Hash y mapas de arrays comparten una misma interfaz. Los mapas de +; Hash tienen búsquedas más rápidas pero no mantienen el orden de las claves. (class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap (class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap @@ -193,7 +195,8 @@ x ; => 1 ; Los mapas pueden usar cualquier tipo para sus claves, pero generalmente las ; keywords (palabras clave) son lo habitual. -; Las keywords son parecidas a cadenas de caracteres con algunas ventajas de eficiencia +; Las keywords son parecidas a cadenas de caracteres con algunas ventajas de +; eficiencia (class :a) ; => clojure.lang.Keyword (def stringmap {"a" 1, "b" 2, "c" 3}) @@ -250,8 +253,8 @@ keymap ; => {:a 1, :b 2, :c 3} ; Patrones útiles ;;;;;;;;;;;;;;;;; -; Las construcciones lógicas en clojure son macros, y presentan el mismo aspecto -; que el resto de forms. +; Las construcciones lógicas en clojure son macros, y presentan el mismo +; aspecto que el resto de forms. (if false "a" "b") ; => "b" (if false "a") ; => nil @@ -352,8 +355,10 @@ keymap ; => {:a 1, :b 2, :c 3} ; Actualiza un atom con swap! ; swap! toma una función y la llama con el valor actual del atom ; como su primer argumento, y cualquier argumento restante como el segundo -(swap! my-atom assoc :a 1) ; Establece my-atom al resultado de (assoc {} :a 1) -(swap! my-atom assoc :b 2) ; Establece my-atom al resultado de (assoc {:a 1} :b 2) +(swap! my-atom assoc :a 1) ; Establece my-atom al resultado +; de (assoc {} :a 1) +(swap! my-atom assoc :b 2) ; Establece my-atom al resultado +; de (assoc {:a 1} :b 2) ; Usa '@' para no referenciar al atom sino para obtener su valor my-atom ;=> Atom<#...> (Regresa el objeto Atom) @@ -377,7 +382,8 @@ my-atom ;=> Atom<#...> (Regresa el objeto Atom) ; Agents: http://clojure.org/agents ### Lectura adicional -Ésto queda lejos de ser exhaustivo, pero espero que sea suficiente para que puedas empezar tu camino. +Ésto queda lejos de ser exhaustivo, pero espero que sea suficiente para que +puedas empezar tu camino. Clojure.org tiene muchos artículos: [http://clojure.org/](http://clojure.org/) -- cgit v1.2.3 From e60cd7ecddd5873dac7cd462ea05a2c4f97b09d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antonio=20Hern=C3=A1ndez=20Blas?= <1096022+nihilismus@users.noreply.github.com> Date: Thu, 6 Feb 2020 12:38:28 -0600 Subject: Update translation --- es-es/clojure-es.html.markdown | 234 ++++++++++++++++++++++++----------------- 1 file changed, 136 insertions(+), 98 deletions(-) diff --git a/es-es/clojure-es.html.markdown b/es-es/clojure-es.html.markdown index 937a7d95..62935ebe 100644 --- a/es-es/clojure-es.html.markdown +++ b/es-es/clojure-es.html.markdown @@ -9,29 +9,30 @@ translators: lang: es-es --- -Clojure es un lenguaje de la familia Lisp desarrollado sobre la Máquina Virtual +Clojure es un lenguaje de la familia Lisp desarrollado para la Máquina Virtual de Java. Tiene un énfasis mayor en la [programación funcional](https://es.wikipedia.org/wiki/Programación_funcional) -pura que Common Lisp, pero incluyendo la posibilidad de usar +pura que Common Lisp, pero incluye varias utilidades de [SMT](https://es.wikipedia.org/wiki/Memoria_transacional) para manipular el estado según se presente. -Esta combinación le permite gestionar la concurrencia de manera muy sencilla -y a menudo automáticamente. +Esta combinación le permite gestionar el procesamiento concurrente de manera +muy sencilla, y a menudo automáticamente. + +(Necesitas la versión de Clojure 1.2 o reciente) -(Necesitas la versión de Clojure 1.2 o posterior) ```clojure -; Los comentatios comienzan con punto y coma. +; Los comentarios comienzan con punto y coma. -; Clojure se escribe mediante "forms" (patrones), los cuales son -; listas de objectos entre paréntesis, separados por espacios en blanco. +; Clojure se escribe mediante patrones ("forms"), los cuales son +; listas de cosas entre paréntesis, separados por espacios en blanco. -; El "reader" (lector) de Clojure asume que el primer objeto es una -; función o una macro que se va a llamar, y que el resto son argumentos. +; El lector ("reader") de Clojure asume que la primera cosa es una +; función o una macro a llamar, y el resto son argumentos. -; El primer form en un archivo debe ser ns, para establecer el namespace -; (espacio de nombres) +; La primera llamada en un archivo debe ser ns, para establecer el espacio de +; nombres ("namespace") (ns learnclojure) ; Algunos ejemplos básicos: @@ -52,69 +53,70 @@ y a menudo automáticamente. ; También es necesaria la negación para las operaciones lógicas (not true) ; => false -; Cuando se anidan Los patrones, estos funcionan de la manera esperada +; Los patrones anidados funcionan como esperas (+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 ; Tipos ;;;;;;;;;;;;; -; Clojure usa los tipos de objetos de Java para booleanos, strings (cadenas de -; caracteres) y números. -; Usa class para saber de qué tipo es. -(class 1); Los enteros son java.lang.Long por defecto -(class 1.); Los numeros en coma flotante son java.lang.Double -(class ""); Los strings van entre comillas dobles, y son -; son java.lang.String -(class false); Los Booleanos son java.lang.Boolean +; Clojure usa los tipos de objetos de Java para booleanos, cadenas de +; caracteres ("strings") y números. +; Usa class para inspeccionarlos. +(class 1); Los números enteros literales son java.lang.Long por defecto +(class 1.); Los números en coma flotante literales son java.lang.Double +(class ""); Los strings siempre van entre comillas dobles, y son + ; java.lang.String +(class false); Los booleanos son java.lang.Boolean (class nil); El valor "null" se escribe nil -; Si quieres crear una lista de datos, precedela con una comilla -; simple para evitar su evaluación +; Si quieres crear una lista literal de datos, usa ' para evitar su evaluación '(+ 1 2) ; => (+ 1 2) -; (que es una abreviatura de (quote (+ 1 2)) ) +; (que es una abreviatura de (quote (+ 1 2))) -; Puedes evaluar una lista precedida por comilla con eval +; Puedes evaluar una lista precedida por una comilla con eval (eval '(+ 1 2)) ; => 3 ; Colecciones & Secuencias ;;;;;;;;;;;;;;;;;;; -; Las Listas están basadas en las listas enlazadas, mientras que los Vectores -; en arrays. -; Los Vectores y las Listas también son clases de Java! +; Las Listas están basadas en listas enlazadas, mientras que los Vectores en +; arreglos. +; ¡Los Vectores y las Listas también son clases de Java! (class [1 2 3]); => clojure.lang.PersistentVector (class '(1 2 3)); => clojure.lang.PersistentList -; Una lista podría ser escrita como (1 2 3), pero debemos ponerle una -; comilla simple delante para evitar que el reader piense que es una función. +; Una lista podría ser escrita como (1 2 3), pero debemos precederle una +; comilla para evitar que el lector ("reader") piense que es una función. ; Además, (list 1 2 3) es lo mismo que '(1 2 3) -; Las "Colecciones" son solo grupos de datos -; Tanto las listas como los vectores son colecciones: +; Las Colecciones ("collections") son solo grupos de datos +; Tanto las Listas como los Vectores son colecciones: (coll? '(1 2 3)) ; => true (coll? [1 2 3]) ; => true -; Las "Secuencias" (seqs) son descripciones abstractas de listas de datos. -; Solo las listas son seqs. +; Las Secuencias ("seqs") son descripciones abstractas de listas de datos. +; Solo las listas son secuencias ("seqs"). (seq? '(1 2 3)) ; => true (seq? [1 2 3]) ; => false -; Una seq solo necesita proporcionar una entrada cuando es accedida. -; Así que, las seqs pueden ser perezosas -- pueden establecer series infinitas: +; Una secuencia solo necesita proporcionar uno de sus elementos cuando es +; accedido. +; Así que, las secuencias pueden ser perezosas -- pueden definir series +; infinitas: (range 4) ; => (0 1 2 3) (range) ; => (0 1 2 3 4 ...) (una serie infinita) (take 4 (range)) ; (0 1 2 3) -; Usa cons para agregar un elemento al inicio de una lista o vector +; Usa cons para agregar un elemento al inicio de una Lista o Vector (cons 4 [1 2 3]) ; => (4 1 2 3) (cons 4 '(1 2 3)) ; => (4 1 2 3) ; conj agregará un elemento a una colección en la forma más eficiente. -; Para listas, se añade al inicio. Para vectores, al final. +; Para Listas, se añade al inicio. Para vectores, al final. (conj [1 2 3] 4) ; => [1 2 3 4] (conj '(1 2 3) 4) ; => (4 1 2 3) -; Usa concat para concatenar listas o vectores +; Usa concat para concatenar Listas o Vectores (concat [1 2] '(3 4)) ; => (1 2 3 4) ; Usa filter y map para actuar sobre colecciones @@ -126,7 +128,7 @@ y a menudo automáticamente. ; = (+ (+ (+ 1 2) 3) 4) ; => 10 -; reduce puede tener un argumento indicando su valor inicial. +; reduce puede tomar un argumento como su valor inicial también (reduce conj [] '(3 2 1)) ; = (conj (conj (conj [] 3) 2) 1) ; => [3 2 1] @@ -138,44 +140,42 @@ y a menudo automáticamente. ; su última expresión (fn [] "Hello World") ; => fn -; (Necesitas rodearlo con paréntesis para invocarla) +; (Necesitas rodearlo con paréntesis para llamarla) ((fn [] "Hello World")) ; => "Hello World" -; Puedes crear una var (variable) mediante def +; Puedes definir una variable ("var") mediante def (def x 1) x ; => 1 -; Asigna una función a una var +; Asignar una función a una variable ("var") (def hello-world (fn [] "Hello World")) (hello-world) ; => "Hello World" -; Puedes defn como atajo para lo anterior +; Puedes usar defn como atajo para lo anterior (defn hello-world [] "Hello World") -; El [] es el vector de argumentos de la función. +; El [] es el Vector de argumentos de la función. (defn hello [name] (str "Hello " name)) (hello "Steve") ; => "Hello Steve" -; Otra abreviatura para crear funciones es: +; Puedes usar esta abreviatura para definir funciones: (def hello2 #(str "Hello " %1)) (hello2 "Fanny") ; => "Hello Fanny" -; Puedes tener funciones multi-variadic: funciones con un numero variable de -; argumentos +; Puedes tener funciones multi-variables ("multi-variadic") también (defn hello3 ([] "Hello World") ([name] (str "Hello " name))) (hello3 "Jake") ; => "Hello Jake" (hello3) ; => "Hello World" -; Las funciones pueden usar argumentos extras dentro de un seq utilizable en -; la función +; Las funciones pueden empaquetar argumentos extras en una secuencia para ti (defn count-args [& args] (str "You passed " (count args) " args: " args)) (count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" -; Y puedes mezclarlos con el resto de argumentos declarados de la función. +; Puedes combinar los argumentos regulares y los empaquetados (defn hello-count [name & args] (str "Hello " name ", you passed " (count args) " extra args")) (hello-count "Finn" 1 2 3) @@ -185,18 +185,18 @@ x ; => 1 ; Mapas ;;;;;;;;;; -; Mapas de Hash y mapas de arrays comparten una misma interfaz. Los mapas de -; Hash tienen búsquedas más rápidas pero no mantienen el orden de las claves. +; Los Mapas de Hash ("HashMap") y Mapas de Arreglo ("ArrayMap") comparten una +; interfaz. Los Mapas de Hash tienen búsquedas más rápidas pero no mantienen el +; orden de las llaves. (class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap (class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap -; Los mapas de arrays se convertidos en mapas de Hash en la mayoría de -; operaciones si crecen mucho, por lo que no debes preocuparte. +; Los Mapas de Arreglo se convierten automáticamente en Mapas de Hash en la +; mayoría de operaciones si crecen mucho, por lo que no debes preocuparte. -; Los mapas pueden usar cualquier tipo para sus claves, pero generalmente las -; keywords (palabras clave) son lo habitual. -; Las keywords son parecidas a cadenas de caracteres con algunas ventajas de -; eficiencia +; Los Mapas pueden usar cualquier tipo para sus llaves, pero generalmente las +; Claves ("keywords") son lo habitual. +; Las Claves son como strings con algunas ventajas de eficiencia (class :a) ; => clojure.lang.Keyword (def stringmap {"a" 1, "b" 2, "c" 3}) @@ -208,28 +208,28 @@ keymap ; => {:a 1, :c 3, :b 2} ; Por cierto, las comas son equivalentes a espacios en blanco y no hacen ; nada. -; Recupera un valor de un mapa tratandolo como una función +; Recupera un valor de un Mapa tratándola como una función (stringmap "a") ; => 1 (keymap :a) ; => 1 -; ¡Las keywords pueden ser usadas para recuperar su valor del mapa, también! +; ¡Las Claves pueden ser usadas para recuperar su valor del mapa, también! (:b keymap) ; => 2 ; No lo intentes con strings. ;("a" stringmap) ; => Exception: java.lang.String cannot be cast to clojure.lang.IFn -; Si preguntamos por una clave que no existe nos devuelve nil +; Recuperando una clave no existente nos devuelve nil (stringmap "d") ; => nil -; Usa assoc para añadir nuevas claves a los mapas de Hash +; Usa assoc para añadir nuevas claves a los Mapas de Hash (def newkeymap (assoc keymap :d 4)) newkeymap ; => {:a 1, :b 2, :c 3, :d 4} ; Pero recuerda, ¡los tipos de Clojure son inmutables! keymap ; => {:a 1, :b 2, :c 3} -; Usa dissoc para eliminar llaves +; Usa dissoc para eliminar claves (dissoc keymap :a :b) ; => {:c 3} ; Conjuntos @@ -241,50 +241,86 @@ keymap ; => {:a 1, :b 2, :c 3} ; Añade un elemento con conj (conj #{1 2 3} 4) ; => #{1 2 3 4} -; Elimina elementos con disj +; Elimina uno con disj (disj #{1 2 3} 1) ; => #{2 3} -; Comprueba su existencia usando el conjunto como una función: +; Comprueba su existencia usando al Conjunto como una función: (#{1 2 3} 1) ; => 1 (#{1 2 3} 4) ; => nil -; Hay más funciones en el namespace clojure.sets +; Hay más funciones en el espacio de nombres clojure.sets ; Patrones útiles ;;;;;;;;;;;;;;;;; -; Las construcciones lógicas en clojure son macros, y presentan el mismo -; aspecto que el resto de forms. +; Los operadores lógicos en clojure son solo macros, y presentan el mismo +; aspecto que el resto de patrones. (if false "a" "b") ; => "b" (if false "a") ; => nil -; Usa let para crear un binding (asociación) temporal +; Usa let para definir ("binding") una variable temporal (let [a 1 b 2] (> a b)) ; => false -; Agrupa expresiones mediante do +; Agrupa sentencias mediante do (do (print "Hello") "World") ; => "World" (prints "Hello") -; Las funciones tienen implicita la llamada a do +; Las funciones tienen un do implícito (defn print-and-say-hello [name] (print "Saying hello to " name) (str "Hello " name)) (print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff") -; Y el let también +; Y let también (let [name "Urkel"] (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") +; Usa las macros de tubería ("threading", "arrow", "pipeline" o "chain") +; (-> y ->>) para expresar la transformación de datos de una manera más clara. + +; La macro Tubería-primero ("Thread-first") (->) inserta en cada patrón el +; resultado de los previos, como el primer argumento (segundo elemento) +(-> + {:a 1 :b 2} + (assoc :c 3) ;=> (assoc {:a 1 :b 2} :c 3) + (dissoc :b)) ;=> (dissoc (assoc {:a 1 :b 2} :c 3) :b) + +; Esta expresión podría ser escrita como: +; (dissoc (assoc {:a 1 :b 2} :c 3) :b) +; y evalua a {:a 1 :c 3} + +; La macro Tubería-último ("Thread-last") hace lo mismo, pero inserta el +; resultado de cada línea al *final* de cada patrón. Esto es útil para las +; operaciones de colecciones en particular: +(->> + (range 10) + (map inc) ;=> (map inc (range 10) + (filter odd?) ;=> (filter odd? (map inc (range 10)) + (into [])) ;=> (into [] (filter odd? (map inc (range 10))) + ; Result: [1 3 5 7 9] + +; Cuando estés en una situación donde quieras tener más libertad en donde +; poner el resultado de transformaciones previas de datos en una expresión, +; puedes usar la macro as->. Con ella, puedes asignar un nombre especifico +; a la salida de la transformaciones y usarlo como identificador en tus +; expresiones encadenadas ("chain"). + +(as-> [1 2 3] input + (map inc input);=> You can use last transform's output at the last position + (nth input 2) ;=> and at the second position, in the same expression + (conj [4 5 6] input [8 9 10])) ;=> or in the middle ! + + ; Módulos ;;;;;;;;;;;;;;; ; Usa use para obtener todas las funciones del módulo (use 'clojure.set) -; Ahora podemos usar más operaciones de conjuntos +; Ahora podemos usar más operaciones de Conjuntos (intersection #{1 2 3} #{2 3 4}) ; => #{2 3} (difference #{1 2 3} #{2 3 4}) ; => #{1} @@ -294,19 +330,18 @@ keymap ; => {:a 1, :b 2, :c 3} ; Usa require para importar un módulo (require 'clojure.string) -; Usa / para llamar a las funciones de un módulo +; Usa / para llamar las funciones de un módulo ; Aquí, el módulo es clojure.string y la función es blank? (clojure.string/blank? "") ; => true -; Puedes asignarle una abreviatura a un modulo al importarlo +; Puedes asignarle una sobrenombre a un modulo al importarlo (require '[clojure.string :as str]) (str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst." -; (#"" es una expresión regular) +; (#"" es una expresión regular literal) -; Puedes usar require (y use, pero no lo hagas) desde un espacio de nombre +; Puedes usar require (y use, pero no lo hagas) desde un espacio de nombres ; usando :require, -; No necesitas preceder con comilla simple tus módulos si lo haces de esta -; forma. +; No necesitas preceder con comilla tus módulos si lo haces de esta manera. (ns test (:require [clojure.string :as str] @@ -315,8 +350,8 @@ keymap ; => {:a 1, :b 2, :c 3} ; Java ;;;;;;;;;;;;;;;;; -; Java tiene una enorme librería estándar, por lo que resulta util -; aprender como interactuar con ella. +; Java tiene una enorme y útil librería estándar, por lo que querrás +; aprender como hacer uso de ella. ; Usa import para cargar un módulo de java (import java.util.Date) @@ -329,14 +364,15 @@ keymap ; => {:a 1, :b 2, :c 3} ; Usa el nombre de la clase con un "." al final para crear una nueva instancia (Date.) ; -; Usa "." para llamar a métodos o usa el atajo ".método" +; Usa "." para llamar métodos. O, usa el atajo ".método" (. (Date.) getTime) ; -(.getTime (Date.)) ; exactamente la misma cosa +(.getTime (Date.)) ; exactamente lo mismo. ; Usa / para llamar métodos estáticos. (System/currentTimeMillis) ; (System siempre está presente) -; Usa doto para hacer frente al uso de clases (mutables) más tolerable +; Usa doto para lidiar con el uso de clases (mutables) de una manera más +; tolerable (import java.util.Calendar) (doto (Calendar/getInstance) (.set 2000 1 1 0 0 0) @@ -345,9 +381,9 @@ keymap ; => {:a 1, :b 2, :c 3} ; STM ;;;;;;;;;;;;;;;;; -; Software Transactional Memory es un mecanismo que usa clojure para gestionar -; el estado persistente. Hay unas cuantas construcciones en clojure que -; hacen uso de este mecanismo. +; La Memoria Transaccional ("Software Transactional Memory" / "STM") es un +; mecanismo que usa clojure para gestionar la persistecia de estado. Hay unas +; cuantas construcciones en clojure que hacen uso de él. ; Un atom es el más sencillo. Se le da un valor inicial (def my-atom (atom {})) @@ -356,15 +392,15 @@ keymap ; => {:a 1, :b 2, :c 3} ; swap! toma una función y la llama con el valor actual del atom ; como su primer argumento, y cualquier argumento restante como el segundo (swap! my-atom assoc :a 1) ; Establece my-atom al resultado -; de (assoc {} :a 1) + ; de (assoc {} :a 1) (swap! my-atom assoc :b 2) ; Establece my-atom al resultado -; de (assoc {:a 1} :b 2) + ; de (assoc {:a 1} :b 2) -; Usa '@' para no referenciar al atom sino para obtener su valor +; Usa '@' para no referenciar al atom y obtener su valor my-atom ;=> Atom<#...> (Regresa el objeto Atom) @my-atom ; => {:a 1 :b 2} -; Un sencillo contador usando un atom sería +; Aquí está un sencillo contador usando un atom (def counter (atom 0)) (defn inc-counter [] (swap! counter inc)) @@ -377,23 +413,25 @@ my-atom ;=> Atom<#...> (Regresa el objeto Atom) @counter ; => 5 -; Otros forms que utilizan STM son refs y agents. +; Otras construcciones de STM son refs y agents. ; Refs: http://clojure.org/refs ; Agents: http://clojure.org/agents +``` + ### Lectura adicional -Ésto queda lejos de ser exhaustivo, pero espero que sea suficiente para que +Ésto queda lejos de ser exhaustivo, pero ojalá que sea suficiente para que puedas empezar tu camino. Clojure.org tiene muchos artículos: -[http://clojure.org/](http://clojure.org/) +[http://clojure.org](http://clojure.org) Clojuredocs.org contiene documentación con ejemplos para la mayoría de funciones principales (pertenecientes al core): -[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) +[http://clojuredocs.org/quickref](http://clojuredocs.org/quickref) 4Clojure es una genial forma de mejorar tus habilidades con clojure/FP: [http://www.4clojure.com/](http://www.4clojure.com/) -Clojure-doc.org (sí, de verdad) tiene un buen número de artículos con los que iniciarse en Clojure: -[http://clojure-doc.org/](http://clojure-doc.org/) +Clojure-doc.org (sí, de verdad) tiene un buen número de artículos con los que +iniciarse en Clojure: [http://clojure-doc.org](http://clojure-doc.org) -- cgit v1.2.3 From 48068a92425a3b3c5f8a11d45489120297aababc Mon Sep 17 00:00:00 2001 From: FedeHC Date: Fri, 7 Feb 2020 16:31:40 -0300 Subject: Update es-es/sql-es.html.markdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Antonio Hernández Blas <1096022+nihilismus@users.noreply.github.com> --- es-es/sql-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/sql-es.html.markdown b/es-es/sql-es.html.markdown index 8bb3aaac..c20ebca0 100644 --- a/es-es/sql-es.html.markdown +++ b/es-es/sql-es.html.markdown @@ -8,7 +8,7 @@ translators: lang: es-es --- -El lenguaje de consulta estructurada (SQL en inglés) es un lenguaje estándar ISO para crear y trabajar con bases de datos almacenados en un conjunto de tablas. Usualmente las implementaciones más usadas añaden sus propias extensiones al lenguaje; [Una comparación entre diferentes implementaciones de SQL](http://troels.arvin.dk/db/rdbms/) es una buena referencia sobre las diferencias entre distintos productos. +El lenguaje de consulta estructurada (SQL en inglés) es un lenguaje estándar ISO para crear y trabajar con bases de datos almacenados en un conjunto de tablas. Las implementaciones generalmente añaden sus propias extensiones al lenguaje; [Comparación entre diferentes implementaciones de SQL](http://troels.arvin.dk/db/rdbms/) es una buena referencia sobre las diferencias entre distintos productos. Las implementaciones típicamente proveen de una línea de comandos donde uno puede introducir los comandos que se muestran aquí en forma interactiva, y también ofrecen una forma de ejecutar una serie de estos comandos almacenados en un archivo de script (mostrar que uno ha terminado con el prompt interactivo es un buen ejemplo de algo que no está estandarizado: la mayoría de las implementaciones de SQL soportan las palabras clave QUIT, EXIT, o ambas). -- cgit v1.2.3 From 57ef3f1377a636b20abeb9e2f91cea8ddb3bfce0 Mon Sep 17 00:00:00 2001 From: FedeHC Date: Fri, 7 Feb 2020 16:31:57 -0300 Subject: Update es-es/sql-es.html.markdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Antonio Hernández Blas <1096022+nihilismus@users.noreply.github.com> --- es-es/sql-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/sql-es.html.markdown b/es-es/sql-es.html.markdown index c20ebca0..3aa6ce7c 100644 --- a/es-es/sql-es.html.markdown +++ b/es-es/sql-es.html.markdown @@ -10,7 +10,7 @@ lang: es-es El lenguaje de consulta estructurada (SQL en inglés) es un lenguaje estándar ISO para crear y trabajar con bases de datos almacenados en un conjunto de tablas. Las implementaciones generalmente añaden sus propias extensiones al lenguaje; [Comparación entre diferentes implementaciones de SQL](http://troels.arvin.dk/db/rdbms/) es una buena referencia sobre las diferencias entre distintos productos. -Las implementaciones típicamente proveen de una línea de comandos donde uno puede introducir los comandos que se muestran aquí en forma interactiva, y también ofrecen una forma de ejecutar una serie de estos comandos almacenados en un archivo de script (mostrar que uno ha terminado con el prompt interactivo es un buen ejemplo de algo que no está estandarizado: la mayoría de las implementaciones de SQL soportan las palabras clave QUIT, EXIT, o ambas). +Las implementaciones típicamente proveen de una línea de comandos donde uno puede introducir los comandos que se muestran aquí en forma interactiva, y también ofrecen una forma de ejecutar una serie de estos comandos almacenados en un archivo de script (mostrar que uno ha terminado con el prompt interactivo es un buen ejemplo de algo que no está estandarizado - la mayoría de las implementaciones de SQL soportan las palabras clave QUIT, EXIT, o ambas). Varios de estos comandos que sirven de ejemplo asumen que la [base de datos de empleados de muestra de MySQL](https://dev.mysql.com/doc/employee/en/) disponible en [github](https://github.com/datacharmer/test_db) ya ha sido cargada. Los archivos github son scripts de comandos, similares a los comandos que aparecen a continuación, que crean y cargan tablas de datos sobre los empleados de una empresa ficticia. La sintaxis para ejecutar estos scripts dependerá de la implementación de SQL que esté utilizando. Una aplicación que se ejecuta desde el prompt del sistema operativo suele ser lo habitual. -- cgit v1.2.3 From a46ac670a03a75d2d24edca46981f7746c64f854 Mon Sep 17 00:00:00 2001 From: FedeHC Date: Fri, 7 Feb 2020 16:33:05 -0300 Subject: Update es-es/sql-es.html.markdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Antonio Hernández Blas <1096022+nihilismus@users.noreply.github.com> --- es-es/sql-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/sql-es.html.markdown b/es-es/sql-es.html.markdown index 3aa6ce7c..1ee0d454 100644 --- a/es-es/sql-es.html.markdown +++ b/es-es/sql-es.html.markdown @@ -42,7 +42,7 @@ SELECT * FROM departments; -- Recupera todas las filas de la tabla departments, pero sólo las columnas -- dept_no y dept_name. --- Separar los comandos en varias líneas es aceptable. +-- Separar los comandos en varias líneas está permitido. SELECT dept_no, dept_name FROM departments; -- cgit v1.2.3 From c7e03628fc70ce300f1d57528c709fc29b35e25e Mon Sep 17 00:00:00 2001 From: caminsha Date: Sun, 9 Feb 2020 23:01:52 +0100 Subject: started fixing the translation --- de-de/d-de.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown index 2b0b38dd..9cebd9f2 100644 --- a/de-de/d-de.html.markdown +++ b/de-de/d-de.html.markdown @@ -9,7 +9,7 @@ lang: de-de --- ```c -// Es war klar dass das kommt... +// Es war klar, dass das kommt... module hello; import std.stdio; @@ -20,10 +20,10 @@ void main(string[] args) { } ``` -Wenn du so wie ich bist und viel zeit im Internet verbringst stehen die Chancen gut -das du schonmal über [D](http://dlang.org/) gehört hast. -Die D-Sprache ist eine moderne, überall einsetzbare programmiersprache die von Low bis -High Level verwendet werden kann und dabei viele Stile anbietet. +Wenn du so wie ich bist und viel Zeit im Internet verbringst, stehen die Chancen +gut, dass du schonmal über [D](http://dlang.org/) gehört hast. +Die D-Sprache ist eine moderne, überall einsetzbare programmiersprache die von +Low bis High Level verwendet werden kann und dabei viele Stile anbietet. D wird aktiv von Walter Bright und Andrei Alexandrescu entwickelt, zwei super schlaue, richtig coole leute. Da das jetzt alles aus dem weg ist - auf zu den Beispielen! -- cgit v1.2.3 From 5c06bbba578ac019cd74cbeabcb21e42cffc5b42 Mon Sep 17 00:00:00 2001 From: caminsha Date: Sun, 9 Feb 2020 23:20:16 +0100 Subject: fixed some typos in German translation --- de-de/d-de.html.markdown | 54 ++++++++++++++++++++++++------------------------ 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown index 9cebd9f2..28ecc7ae 100644 --- a/de-de/d-de.html.markdown +++ b/de-de/d-de.html.markdown @@ -26,7 +26,7 @@ Die D-Sprache ist eine moderne, überall einsetzbare programmiersprache die von Low bis High Level verwendet werden kann und dabei viele Stile anbietet. D wird aktiv von Walter Bright und Andrei Alexandrescu entwickelt, zwei super schlaue, -richtig coole leute. Da das jetzt alles aus dem weg ist - auf zu den Beispielen! +richtig coole leute. Da das jetzt alles aus dem Weg ist - auf zu den Beispielen! ```c import std.stdio; @@ -38,7 +38,7 @@ void main() { writeln(i); } - auto n = 1; // auto um den typ vom Compiler bestimmen zu lassen + auto n = 1; // auto um den Typ vom Compiler bestimmen zu lassen // Zahlenliterale können _ verwenden für lesbarkeit while(n < 10_000) { @@ -68,21 +68,22 @@ void main() { } ``` -Neue Typen können mit `struct`, `class`, `union`, und `enum` definiert werden. Structs und unions -werden as-value (koppiert) an methoden übergeben wogegen Klassen als Referenz übergeben werden. -Templates können verwendet werden um alle typen zu parameterisieren. +Neue Typen können mit `struct`, `class`, `union`, und `enum` definiert werden. +Structs und unions werden as-value (koppiert) an Methoden übergeben wogegen +Klassen als Referenz übergeben werden. Templates können verwendet werden um +alle Typen zu parameterisieren. ```c // Hier, T ist ein Type-Parameter, Er funktioniert wie Generics in C#/Java/C++ struct LinkedList(T) { T data = null; - LinkedList!(T)* next; // Das ! wird verwendet um T zu übergeben. ( in C#/Java/C++) + LinkedList!(T)* next; // Das ! wird verwendet, um T zu übergeben. ( in C#/Java/C++) } class BinTree(T) { T data = null; - // Wenn es nur einen T parameter gibt können die Klammern um ihn weggelassen werden + // Wenn es nur einen T Parameter gibt, können die Klammern um ihn weggelassen werden BinTree!T left; BinTree!T right; } @@ -97,7 +98,7 @@ enum Day { Saturday, } -// Aliase können verwendet werden um die Entwicklung zu erleichtern +// Aliase können verwendet werden, um die Entwicklung zu erleichtern alias IntList = LinkedList!int; alias NumTree = BinTree!double; @@ -111,8 +112,8 @@ T max(T)(T a, T b) { return a; } -// Steht ref vor einem Parameter wird sichergestellt das er als Referenz übergeben wird. -// Selbst bei werten wird es immer eine Referenz sein. +// Steht ref vor einem Parameter, wird sichergestellt, dass er als Referenz +übergeben wird. Selbst bei Werten wird es immer eine Referenz sein. void swap(T)(ref T a, ref T b) { auto temp = a; @@ -120,18 +121,18 @@ void swap(T)(ref T a, ref T b) { b = temp; } -// Templates können ebenso werte parameterisieren. +// Templates können ebenso Werte parameterisieren. class Matrix(uint m, uint n, T = int) { T[m] rows; T[n] columns; } -auto mat = new Matrix!(3, 3); // Standardmäßig ist T vom typ Integer +auto mat = new Matrix!(3, 3); // Standardmäßig ist T vom Typ Integer ``` Wo wir schon bei Klassen sind - Wie wäre es mit Properties! Eine Property -ist eine Funktion die wie ein Wert agiert. Das gibt uns viel klarere Syntax +ist eine Funktion, die wie ein Wert agiert. Das gibt uns viel klarere Syntax im Stil von `structure.x = 7` was gleichgültig wäre zu `structure.setX(7)` ```c @@ -187,18 +188,17 @@ void main() { ``` Mit properties können wir sehr viel logik hinter unseren gettern -und settern hinter einer schönen syntax verstecken +und settern hinter einer schönen Syntax verstecken -Other object-oriented goodies at our disposal Andere Objektorientierte features sind beispielsweise `interface`s, `abstract class` und `override`. Vererbung funktioniert in D wie in Java: -Erben von einer Klasse, so viele interfaces wie man will. +Erben von einer Klasse, so viele Interfaces wie man will. -Jetzt haben wir Objektorientierung in D gesehen aber schauen +Jetzt haben wir Objektorientierung in D gesehen, aber schauen wir uns noch was anderes an. -D bietet funktionale programmierung mit _first-class functions_ -puren funktionen und unveränderbare daten. +D bietet funktionale Programmierung mit _first-class functions_ +puren Funktionen und unveränderbaren Daten. Zusätzlich können viele funktionale Algorithmen wie z.B map, filter, reduce und friends im `std.algorithm` Modul gefunden werden! @@ -207,11 +207,11 @@ import std.algorithm : map, filter, reduce; import std.range : iota; // builds an end-exclusive range void main() { - // Wir wollen die summe aller quadratzahlen zwischen + // Wir wollen die Summe aller Quadratzahlen zwischen // 1 und 100 ausgeben. Nichts leichter als das! - // Einfach eine lambda funktion als template parameter übergeben - // Es ist genau so gut möglich eine normale funktion hier zu übergeben + // Einfach eine Lambda-Funktion als Template Parameter übergeben + // Es ist genau so gut möglich eine normale Funktion hier zu übergeben // Lambdas bieten sich hier aber an. auto num = iota(1, 101).filter!(x => x % 2 == 0) .map!(y => y ^^ 2) @@ -221,13 +221,13 @@ void main() { } ``` -Ist dir aufgefallen wie wir eine Haskell-Style pipeline gebaut haben +Ist dir aufgefallen, wie wir eine Haskell-Style Pipeline gebaut haben um num zu berechnen? Das war möglich durch die Uniform Function Call Syntax. -Mit UFCS können wir auswählen ob wir eine Funktion als Methode oder +Mit UFCS können wir auswählen, ob wir eine Funktion als Methode oder als freie Funktion aufrufen. Walters artikel dazu findet ihr [hier.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) -Kurzgesagt kann man Funktionen deren erster parameter vom typ A ist, als +Kurzgesagt kann man Funktionen, deren erster Parameter vom typ A ist, als Methode auf A anwenden. Parrallel Computing ist eine Tolle sache, findest du nicht auch? @@ -239,10 +239,10 @@ import std.math : sqrt; void main() { // Wir wollen die Wurzel von jeder Zahl in unserem Array berechnen - // und dabei alle Kerne verwenden die wir zur verfügung haben + // und dabei alle Kerne verwenden, die wir zur verfügung haben auto arr = new double[1_000_000]; - // Wir verwenden den index und das element als referenz + // Wir verwenden den Index und das Element als Referenz // und rufen einfach parallel auf! foreach(i, ref elem; parallel(arr)) { ref = sqrt(i + 1.0); -- cgit v1.2.3 From 1adab9bc3f80d82123987ff34083568030735db7 Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Wed, 12 Feb 2020 04:49:56 +0100 Subject: Rename Python 2 markdown files into 'pythonlegacy' ``` for f in $(find . -iname "*python*" | grep -vE 'python3|git|statcomp'); do flegacy=$(echo "$f" | sed 's/python/pythonlegacy/') git mv "$f" "$flegacy" done ``` --- de-de/python-de.html.markdown | 766 --------------------------------- de-de/pythonlegacy-de.html.markdown | 766 +++++++++++++++++++++++++++++++++ es-es/python-es.html.markdown | 562 ------------------------ es-es/pythonlegacy-es.html.markdown | 562 ++++++++++++++++++++++++ fr-fr/python-fr.html.markdown | 488 --------------------- fr-fr/pythonlegacy-fr.html.markdown | 488 +++++++++++++++++++++ hu-hu/python-hu.html.markdown | 816 ----------------------------------- hu-hu/pythonlegacy-hu.html.markdown | 816 +++++++++++++++++++++++++++++++++++ it-it/python-it.html.markdown | 778 --------------------------------- it-it/pythonlegacy-it.html.markdown | 778 +++++++++++++++++++++++++++++++++ ko-kr/python-kr.html.markdown | 484 --------------------- ko-kr/pythonlegacy-kr.html.markdown | 484 +++++++++++++++++++++ pl-pl/python-pl.html.markdown | 640 ---------------------------- pl-pl/pythonlegacy-pl.html.markdown | 640 ++++++++++++++++++++++++++++ pt-br/python-pt.html.markdown | 509 ---------------------- pt-br/pythonlegacy-pt.html.markdown | 509 ++++++++++++++++++++++ python.html.markdown | 827 ------------------------------------ pythonlegacy.html.markdown | 827 ++++++++++++++++++++++++++++++++++++ ro-ro/python-ro.html.markdown | 493 --------------------- ro-ro/pythonlegacy-ro.html.markdown | 493 +++++++++++++++++++++ ru-ru/python-ru.html.markdown | 643 ---------------------------- ru-ru/pythonlegacy-ru.html.markdown | 643 ++++++++++++++++++++++++++++ tr-tr/python-tr.html.markdown | 502 ---------------------- tr-tr/pythonlegacy-tr.html.markdown | 502 ++++++++++++++++++++++ uk-ua/python-ua.html.markdown | 818 ----------------------------------- uk-ua/pythonlegacy-ua.html.markdown | 818 +++++++++++++++++++++++++++++++++++ zh-cn/python-cn.html.markdown | 476 --------------------- zh-cn/pythonlegacy-cn.html.markdown | 476 +++++++++++++++++++++ zh-tw/python-tw.html.markdown | 727 ------------------------------- zh-tw/pythonlegacy-tw.html.markdown | 727 +++++++++++++++++++++++++++++++ 30 files changed, 9529 insertions(+), 9529 deletions(-) delete mode 100644 de-de/python-de.html.markdown create mode 100644 de-de/pythonlegacy-de.html.markdown delete mode 100644 es-es/python-es.html.markdown create mode 100644 es-es/pythonlegacy-es.html.markdown delete mode 100644 fr-fr/python-fr.html.markdown create mode 100644 fr-fr/pythonlegacy-fr.html.markdown delete mode 100644 hu-hu/python-hu.html.markdown create mode 100644 hu-hu/pythonlegacy-hu.html.markdown delete mode 100644 it-it/python-it.html.markdown create mode 100644 it-it/pythonlegacy-it.html.markdown delete mode 100644 ko-kr/python-kr.html.markdown create mode 100644 ko-kr/pythonlegacy-kr.html.markdown delete mode 100644 pl-pl/python-pl.html.markdown create mode 100644 pl-pl/pythonlegacy-pl.html.markdown delete mode 100644 pt-br/python-pt.html.markdown create mode 100644 pt-br/pythonlegacy-pt.html.markdown delete mode 100644 python.html.markdown create mode 100644 pythonlegacy.html.markdown delete mode 100644 ro-ro/python-ro.html.markdown create mode 100644 ro-ro/pythonlegacy-ro.html.markdown delete mode 100644 ru-ru/python-ru.html.markdown create mode 100644 ru-ru/pythonlegacy-ru.html.markdown delete mode 100644 tr-tr/python-tr.html.markdown create mode 100644 tr-tr/pythonlegacy-tr.html.markdown delete mode 100644 uk-ua/python-ua.html.markdown create mode 100644 uk-ua/pythonlegacy-ua.html.markdown delete mode 100644 zh-cn/python-cn.html.markdown create mode 100644 zh-cn/pythonlegacy-cn.html.markdown delete mode 100644 zh-tw/python-tw.html.markdown create mode 100644 zh-tw/pythonlegacy-tw.html.markdown diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown deleted file mode 100644 index ee77683e..00000000 --- a/de-de/python-de.html.markdown +++ /dev/null @@ -1,766 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["kultprok", "http:/www.kulturproktologie.de"] -filename: learnpython-de.py -lang: de-de ---- - -Anmerkungen des ursprünglichen Autors: -Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode. - -Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service] - -Hinweis: Dieser Beitrag bezieht sich besonders auf Python 2.7, er sollte aber auf Python 2.x anwendbar sein. Haltet Ausschau nach einem Rundgang durch Python 3, der bald erscheinen soll. - -```python -# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz) -""" Mehrzeilige Strings werden mit - drei '-Zeichen geschrieben und werden - oft als Kommentare genutzt. -""" - -#################################################### -## 1. Primitive Datentypen und Operatoren -#################################################### - -# Die Zahlen -3 #=> 3 - -# Mathematik funktioniert so, wie man das erwartet -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 - -# Division ist ein wenig kniffliger. Ganze Zahlen werden ohne Rest dividiert -# und das Ergebnis wird automatisch abgerundet. -5 / 2 #=> 2 - -# Um das zu ändern, müssen wir Gleitkommazahlen einführen und benutzen -2.0 # Das ist eine Gleitkommazahl -11.0 / 4.0 #=> 2.75 Ahhh...schon besser - -# Rangfolge wird mit Klammern erzwungen -(1 + 3) * 2 #=> 8 - -# Boolesche Ausdrücke sind primitive Datentypen -True -False - -# Mit not wird negiert -not True #=> False -not False #=> True - -# Gleichheit ist == -1 == 1 #=> True -2 == 1 #=> False - -# Ungleichheit ist != -1 != 1 #=> False -2 != 1 #=> True - -# Ein paar weitere Vergleiche -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True - -# Vergleiche können verknüpft werden! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False - -# Strings werden mit " oder ' gebildet -"Das ist ein String." -'Das ist auch ein String.' - -# Strings können addiert werden! -"Hello " + "world!" #=> "Hello world!" - -# Ein String kann wie eine Liste von Zeichen verwendet werden -"Das ist ein String"[0] #=> 'D' - -# Mit % können Strings formatiert werden, etwa so: -"%s können %s werden" % ("Strings", "interpoliert") - -# Ein modernerer Weg, um Strings zu formatieren, ist die format-Methode. -# Diese Methode wird bevorzugt -"{0} können {1} werden".format("Strings", "formatiert") -# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen. -"{name} will {food} essen".format(name="Bob", food="Lasagne") - -# None ist ein Objekt -None #=> None - -# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen -# Benutzt stattdessen `is` -"etc" is None #=> False -None is None #=> True - -# Der 'is'-Operator testet Objektidentität. Das ist nicht -# sehr nützlich, wenn wir mit primitiven Datentypen arbeiten, aber -# sehr nützlich bei Objekten. - -# None, 0, und leere Strings/Listen werden alle als False bewertet. -# Alle anderen Werte sind True -0 == False #=> True -"" == False #=> True - - -#################################################### -## 2. Variablen und Collections -#################################################### - -# Textausgabe ist sehr einfach -print "Ich bin Python. Schön, dich kennenzulernen!" - - -# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren. -some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm -some_var #=> 5 - -# Das Ansprechen einer noch nicht deklarierte Variable löst eine Exception aus. -# Unter "Kontrollstruktur" kann noch mehr über -# Ausnahmebehandlung erfahren werden. -some_other_var # Löst einen NameError aus - -# if kann als Ausdruck verwendet werden -"yahoo!" if 3 > 2 else 2 #=> "yahoo!" - -# Listen speichern Sequenzen -li = [] -# Wir können mit einer bereits gefüllten Liste anfangen -other_li = [4, 5, 6] - -# append fügt Daten am Ende der Liste ein -li.append(1) #li ist jetzt [1] -li.append(2) #li ist jetzt [1, 2] -li.append(4) #li ist jetzt [1, 2, 4] -li.append(3) #li ist jetzt [1, 2, 4, 3] -# Vom Ende der Liste mit pop entfernen -li.pop() #=> 3 und li ist jetzt [1, 2, 4] -# und dann wieder hinzufügen -li.append(3) # li ist jetzt wieder [1, 2, 4, 3]. - -# Greife auf Listen wie auf Arrays zu -li[0] #=> 1 -# Das letzte Element ansehen -li[-1] #=> 3 - -# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError -li[4] # Raises an IndexError - -# Wir können uns Ranges mit Slice-Syntax ansehen -li[1:3] #=> [2, 4] -# Den Anfang auslassen -li[2:] #=> [4, 3] -# Das Ende auslassen -li[:3] #=> [1, 2, 4] - -# Ein bestimmtes Element mit del aus der Liste entfernen -del li[2] # li ist jetzt [1, 2, 3] - -# Listen können addiert werden -li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen - -# Listen mit extend verknüpfen -li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6] - -# Mit in auf Existenz eines Elements prüfen -1 in li #=> True - -# Die Länge der Liste mit len ermitteln -len(li) #=> 6 - - -# Tupel sind wie Listen, nur unveränderlich. -tup = (1, 2, 3) -tup[0] #=> 1 -tup[0] = 3 # Löst einen TypeError aus - -# Wir können all diese Listen-Dinge auch mit Tupeln anstellen -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True - -# Wir können Tupel (oder Listen) in Variablen entpacken -a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3 -# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen -d, e, f = 4, 5, 6 -# Es ist kinderleicht zwei Werte zu tauschen -e, d = d, e # d is now 5 and e is now 4 - - -# Dictionarys (Wörterbucher) speichern Key-Value-Paare -empty_dict = {} -# Hier ein gefülltes Wörterbuch -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Wir können Einträge mit [] nachschlagen -filled_dict["one"] #=> 1 - -# So holen wir alle Keys (Schlüssel) als Liste -filled_dict.keys() #=> ["three", "two", "one"] -# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert. -# Einzelne Resultate können anders angeordnet sein. - -# Alle Values (Werte) als Liste -filled_dict.values() #=> [3, 2, 1] -# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln. - -# Das Vorhandensein eines Schlüssels im Wörterbuch mit in prüfen -"one" in filled_dict #=> True -1 in filled_dict #=> False - -# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus -filled_dict["four"] # KeyError - -# Mit der get-Methode verhindern wir das -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None -# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt -filled_dict.get("one", 4) #=> 1 -filled_dict.get("four", 4) #=> 4 - -# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen -filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt -filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5 - - -# Sets speichern Mengen -empty_set = set() -# Initialisieren wir ein Set mit ein paar Werten -some_set = set([1,2,2,3,4]) # some_set ist jetzt set([1, 2, 3, 4]) - -# Seit Python 2.7 kann {} benutzt werden, um ein Set zu erstellen -filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} - -# Mehr Elemente hinzufügen -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} - -# Schnittmengen werden mit & gebildet -other_set = {3, 4, 5, 6} -filled_set & other_set #=> {3, 4, 5} - -# Mengen werden mit | vereinigt -filled_set | other_set #=> {1, 2, 3, 4, 5, 6} - -# Die Differenz einer Menge mit - bilden -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# Auf Vorhandensein von Elementen mit in prüfen -2 in filled_set #=> True -10 in filled_set #=> False - - -#################################################### -## 3. Kontrollstruktur -#################################################### - -# Erstellen wir mal eine Variable -some_var = 5 - -# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig! -# gibt "some_var ist kleiner als 10" aus -if some_var > 10: - print "some_var ist viel größer als 10." -elif some_var < 10: # Dieser elif-Absatz ist optional. - print "some_var ist kleiner als 10." -else: # Das hier ist auch optional. - print "some_var ist tatsächlich 10." - - -""" -For-Schleifen iterieren über Listen -Ausgabe: - hund ist ein Säugetier - katze ist ein Säugetier - maus ist ein Säugetier -""" -for animal in ["hund", "katze", "maus"]: - # Wir können Strings mit % formatieren - print "%s ist ein Säugetier" % animal - -""" -`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder -Ausgabe: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -While-Schleifen laufen, bis eine Bedingung erfüllt ist. -Ausgabe: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # Kurzform für x = x + 1 - -# Ausnahmebehandlung mit einem try/except-Block - -# Funktioniert in Python 2.6 und höher: -try: - # Mit raise wird ein Fehler ausgegeben - raise IndexError("Das hier ist ein Index-Fehler") -except IndexError as e: - pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären. - - -#################################################### -## 4. Funktionen -#################################################### - -# Mit def neue Funktionen erstellen -def add(x, y): - print "x ist %s und y ist %s" % (x, y) - return x + y # Werte werden mit return zurückgegeben - -# Funktionen mit Parametern aufrufen -add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück - -# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente -add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden. - -# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# Wir können auch Funktionen mit beliebiger Anzahl -# Schlüsselwort-Argumenten definieren -def keyword_args(**kwargs): - return kwargs - -# Rufen wir es mal auf, um zu sehen, was passiert -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} - -# Wir können beides gleichzeitig machem, wenn wir wollen -def all_the_args(*args, **kwargs): - print args - print kwargs -""" -all_the_args(1, 2, a=3, b=4) Ausgabe: - (1, 2) - {"a": 3, "b": 4} -""" - -# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen! -# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4) -all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4) -all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4) - -# Python hat First-Class-Funktionen -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) #=> 13 - -# Es gibt auch anonyme Funktionen -(lambda x: x > 2)(3) #=> True - -# Es gibt auch Funktionen höherer Ordnung als Built-Ins -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] - - -#################################################### -## 5. Module -#################################################### - -# Wir können Module importieren -import math -print math.sqrt(16) #=> 4.0 - -# Wir können auch nur spezielle Funktionen eines Moduls importieren -from math import ceil, floor -print ceil(3.7) #=> 4.0 -print floor(3.7) #=> 3.0 - -# Wir können auch alle Funktionen eines Moduls importieren -# Warnung: Dies wird nicht empfohlen -from math import * - -# Wir können Modulnamen abkürzen -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Module sind in Python nur gewöhnliche Dateien. Wir -# können unsere eigenen schreiben und importieren. Der Name des -# Moduls ist der Dateiname. - -# Wir können herausfinden, welche Funktionen und Attribute in einem -# Modul definiert sind. -import math -dir(math) - -# Wenn Sie ein Python-Skript namens math.py im selben Ordner -# wie Ihr aktuelles Skript haben, wird die Datei math.py -# anstelle des integrierten Python-Moduls geladen. -# Dies geschieht, weil der lokale Ordner Vorrang -# vor den in Python integrierten Bibliotheken hat. - - -#################################################### -## 6. Klassen -#################################################### - -# Wir verwenden das Schlüsselwort "class" um eine Klasse zu erzeugen. -class Human(object): - - # Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt - species = "H. sapiens" - - # Ein simpler Konstruktor, wird aufgerufen, wenn diese Klasse instanziiert wird. - # Beachten Sie, dass die doppelten vorangestellten und nachgestellten - # Unterstriche Objekte oder Attribute bezeichnen, die von Python verwendet werden, - # aber in benutzergesteuerten Namespaces leben. - # Methoden (oder Objekte oder Attribute) wie: __init__, __str__, __repr__ usw. - # werden als Sondermethoden (oder manchmal als Dundermethoden bezeichnet) bezeichnet. - # Sie sollten solche Namen nicht selbst erfinden. - def __init__(self, name): - # Wir weisen das Argument name dem name-Attribut der Instanz zu - self.name = name - - # Eine Instanzmethode. Alle Methoden erhalten "self" als erstes Argument. - def say(self, msg): - return "%s: %s" % (self.name, msg) - - # Eine weitere Instanzmethode - def sing(self): - return 'yo... yo... microphone check... one two... one two...' - - # Eine Klassenmethode wird von allen Instanzen geteilt. - # Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen - @classmethod - def get_species(cls): - return cls.species - - # Eine statische Methode wird ohne Klasse oder Instanz aufgerufen - @staticmethod - def grunt(): - return "*grunt*" - - # Eine Eigenschaft (Property) ist wie ein Getter. -    # Es verwandelt die Methode age() in ein schreibgeschütztes Attribut mit demselben Namen. -    # Es ist jedoch nicht nötig, triviale Getter und Setter in Python zu schreiben. - @property - def age(self): - return self._age - -    # Damit kann die Eigenschaft festgelegt werden - @age.setter - def age(self, age): - self._age = age - -    # Damit kann die Eigenschaft gelöscht werden - @age.deleter - def age(self): - del self._age - -# Wenn ein Python-Interpreter eine Quelldatei liest, führt er den gesamten Code aus. -# Diese __name__-Prüfung stellt sicher, dass dieser Codeblock nur ausgeführt wird, -# wenn dieses Modul das Hauptprogramm ist. -if __name__ == '__main__': - # Eine Instanz einer Klasse erstellen - i = Human(name="Ian") - i.say("hi") # "Ian: hi" - j = Human("Joel") - j.say("hello") # "Joel: hello" - # i und j sind Instanzen des Typs Mensch, oder anders ausgedrückt: Sie sind Objekte des Menschen - - # Rufen wir unsere Klassenmethode auf - i.say(i.get_species()) # "Ian: H. sapiens" - - # Ändern wir das gemeinsame Attribut - Human.species = "H. neanderthalensis" - i.say(i.get_species()) # => "Ian: H. neanderthalensis" - j.say(j.get_species()) # => "Joel: H. neanderthalensis" - - # Aufruf der statischen Methode - print(Human.grunt()) # => "*grunt*" - - # Kann keine statische Methode mit Instanz des Objekts aufrufen, - # da i.grunt () automatisch "self" (das Objekt i) als Argument verwendet - print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given - - # Die Eigenschaft für diese Instanz aktualisieren - i.age = 42 - # die Eigenschaft auslesen - i.say(i.age) # => "Ian: 42" - j.say(j.age) # => "Joel: 0" - # die Eigenschaft löschen - del i.age - # i.age # => würde einen AttributeError werfen - -#################################################### -## 6.1 Inheritance -#################################################### - -# Vererbung ermöglicht die Definition neuer untergeordneter Klassen, -# die Methoden und Variablen von ihrer übergeordneten Klasse erben. - -# Wenn Sie die oben definierte Human-Klasse als Basis- oder Elternklasse verwenden, -# können Sie eine untergeordnete Klasse, Superhero, definieren, die die Klassenvariablen -# wie "species", "name" und "age" sowie Methoden wie "sing" und "grunzen" aus der Klasse Human erbt. -# Die Untergeordnete Klasse kann aber auch eigene Eigenschaften haben. - -# Um von der Modularisierung per Datei zu profitieren, können Sie die Klassen -# in ihren eigenen Dateien platzieren, z. B. human.py - -# Um Funktionen aus anderen Dateien zu importieren, verwenden Sie das folgende Format -# from "Dateiname-ohne-Erweiterung" impotr "Funktion-oder-Klasse" - -from human import Human - -# Geben Sie die übergeordnete(n) Klasse(n) als Parameter für die Klassendefinition an -class Superhero(Human): - - # Wenn die untergeordnete Klasse alle Definitionen des übergeordneten Elements - # ohne Änderungen erben soll, können Sie einfach das Schlüsselwort "pass" - # (und nichts anderes) verwenden. In diesem Fall wird jedoch auskommentiert, - # um eine eindeutige untergeordnete Klasse zuzulassen: - # pass - - # Kindklassen können die Attribute ihrer Eltern überschreiben - species = 'Superhuman' - - # Kinder erben automatisch den Konstruktor ihrer übergeordneten Klasse - # einschließlich ihrer Argumente, können aber auch zusätzliche Argumente oder - # Definitionen definieren und ihre Methoden zB den Klassenkonstruktor überschreiben. - # Dieser Konstruktor erbt das Argument "name" von der Klasse "Human" und - # fügt die Argumente "superpowers" und "movie" hinzu: - def __init__(self, name, movie=False, - superpowers=["super strength", "bulletproofing"]): - - # zusätzliche Klassenattribute hinzufügen: - self.fictional = True - self.movie = movie - # Beachten Sie die veränderlichen Standardwerte, da die Standardwerte gemeinsam genutzt werden - self.superpowers = superpowers - - # Mit der Funktion "super" können Sie auf die Methoden der übergeordneten Klasse - # zugreifen, die vom untergeordneten Objekt überschrieben werden, - # in diesem Fall die Methode __init__. -        # Dies ruft den Konstruktor der übergeordneten Klasse auf: - super().__init__(name) - - # überschreiben der "sing" Methode - def sing(self): - return 'Dun, dun, DUN!' - - # eine zusätzliche Instanzmethode hinzufügen - def boast(self): - for power in self.superpowers: - print("I wield the power of {pow}!".format(pow=power)) - -if __name__ == '__main__': - sup = Superhero(name="Tick") - - # Instanztypprüfungen - if isinstance(sup, Human): - print('I am human') - if type(sup) is Superhero: - print('I am a superhero') - - # Die Reihenfolge der Methodenauflösung (MRO = Method Resolution Order) anzeigen, die sowohl von getattr() als auch von super() verwendet wird. -    # Dieses Attribut ist dynamisch und kann aktualisiert werden. - print(Superhero.__mro__) # => (, - # => , ) - - # Ruft die übergeordnete Methode auf, verwendet jedoch das eigene Klassenattribut - print(sup.get_species()) # => Superhuman - - # Ruft die überschriebene Methode auf - print(sup.sing()) # => Dun, dun, DUN! - - # Ruft die Methode von Human auf - sup.say('Spoon') # => Tick: Spoon - - # Aufruf einer Methode, die nur in Superhero existiert - sup.boast() # => I wield the power of super strength! - # => I wield the power of bulletproofing! - - # Vererbtes Klassenattribut - sup.age = 31 - print(sup.age) # => 31 - - # Attribut, das nur in Superhero existiert - print('Am I Oscar eligible? ' + str(sup.movie)) - -#################################################### -## 6.2 Multiple Inheritance -#################################################### - -# Eine weitere Klassendefinition -# bat.py - -class Bat: - - species = 'Baty' - - def __init__(self, can_fly=True): - self.fly = can_fly - - # This class also has a say method - def say(self, msg): - msg = '... ... ...' - return msg - - # And its own method as well - def sonar(self): - return '))) ... (((' - -if __name__ == '__main__': - b = Bat() - print(b.say('hello')) - print(b.fly) - -# Und noch eine andere Klassendefinition, die von Superhero und Bat erbt -# superhero.py -from superhero import Superhero -from bat import Bat - -# Definieren Sie Batman als eine Kindklasse, das von Superheld und Bat erbt -class Batman(Superhero, Bat): - - def __init__(self, *args, **kwargs): - # In der Regel müssen Sie super aufrufen, um Attribute zu erben: - # super (Batman, selbst) .__ init__ (* args, ** kwargs) - # Allerdings handelt es sich hier um Mehrfachvererbung, und super() - # funktioniert nur mit der nächsten Basisklasse in der MRO-Liste. - # Stattdessen rufen wir explizit __init__ für alle Vorfahren auf. - # Die Verwendung von *args und **kwargs ermöglicht die saubere Übergabe von - # Argumenten, wobei jedes übergeordnete Element eine Schicht der Zwiebel "abschält". - Superhero.__init__(self, 'anonymous', movie=True, - superpowers=['Wealthy'], *args, **kwargs) - Bat.__init__(self, *args, can_fly=False, **kwargs) - # überschreibt den Wert für das Namensattribut - self.name = 'Sad Affleck' - - def sing(self): - return 'nan nan nan nan nan batman!' - -if __name__ == '__main__': - sup = Batman() - - # Die Reihenfolge der Methodenauflösung (MRO = Method Resolution Order) anzeigen, - # die sowohl von getattr() als auch von super() verwendet wird. - # Dieses Attribut ist dynamisch und kann aktualisiert werden. - print(Batman.__mro__) # => (, - # => , - # => , - # => , ) - - # Ruft die übergeordnete Methode auf, verwendet jedoch das eigene Klassenattribut - print(sup.get_species()) # => Superhuman - - # Ruft die überschriebene Methode auf - print(sup.sing()) # => nan nan nan nan nan batman! - - # Ruft die Methode von Human auf, weil die Reihenfolge der Vererbung wichtig ist - sup.say('I agree') # => Sad Affleck: I agree - - # Aufrufmethode, die nur im 2. Vorfahren existiert - print(sup.sonar()) # => ))) ... ((( - - # Vererbtes Klassenattribut - sup.age = 100 - print(sup.age) # => 100 - - # Vererbtes Attribut vom 2. Vorfahren, dessen Standardwert überschrieben wurde. - print('Can I fly? ' + str(sup.fly)) # => Can I fly? False - - -#################################################### -## 7. Fortgeschrittenes -#################################################### - -# Generatoren helfen Ihnen, lazy Code zu erstellen. -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Generatoren sind speichereffizient, da sie nur die Daten laden, -# die zur Verarbeitung des nächsten Werts in der iterierbaren Komponente -# erforderlich sind. Dadurch können sie ansonsten unzulässig große Wertebereiche ausführen. -# HINWEIS: `range` ersetzt` xrange` in Python 3. -for i in double_numbers(range(1, 900000000)): # `range` ist ein Generator. - print(i) - if i >= 30: - break - -# Genauso wie Sie ein 'list comprehension' (Listen Abstraktion) erstellen können, können Sie auch 'generator comprehension' (Generator Abstraktion) erstellen. -values = (-x for x in [1,2,3,4,5]) -for x in values: - print(x) # prints -1 -2 -3 -4 -5 to console/terminal - -# Sie können eine Generator Abstraktion auch direkt in eine Liste umwandeln (casten). -values = (-x for x in [1,2,3,4,5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - -# Decorators -# In diesem Beispiel umschliesst "beg" "say". Wenn say_please True ist, wird die zurückgegebene Nachricht geändert. -from functools import wraps - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( - -``` - -## Lust auf mehr? - -### Kostenlos online (Englisch) - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2.6/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) - -### Totholz (Englisch) - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/de-de/pythonlegacy-de.html.markdown b/de-de/pythonlegacy-de.html.markdown new file mode 100644 index 00000000..ee77683e --- /dev/null +++ b/de-de/pythonlegacy-de.html.markdown @@ -0,0 +1,766 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["kultprok", "http:/www.kulturproktologie.de"] +filename: learnpython-de.py +lang: de-de +--- + +Anmerkungen des ursprünglichen Autors: +Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode. + +Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service] + +Hinweis: Dieser Beitrag bezieht sich besonders auf Python 2.7, er sollte aber auf Python 2.x anwendbar sein. Haltet Ausschau nach einem Rundgang durch Python 3, der bald erscheinen soll. + +```python +# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz) +""" Mehrzeilige Strings werden mit + drei '-Zeichen geschrieben und werden + oft als Kommentare genutzt. +""" + +#################################################### +## 1. Primitive Datentypen und Operatoren +#################################################### + +# Die Zahlen +3 #=> 3 + +# Mathematik funktioniert so, wie man das erwartet +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Division ist ein wenig kniffliger. Ganze Zahlen werden ohne Rest dividiert +# und das Ergebnis wird automatisch abgerundet. +5 / 2 #=> 2 + +# Um das zu ändern, müssen wir Gleitkommazahlen einführen und benutzen +2.0 # Das ist eine Gleitkommazahl +11.0 / 4.0 #=> 2.75 Ahhh...schon besser + +# Rangfolge wird mit Klammern erzwungen +(1 + 3) * 2 #=> 8 + +# Boolesche Ausdrücke sind primitive Datentypen +True +False + +# Mit not wird negiert +not True #=> False +not False #=> True + +# Gleichheit ist == +1 == 1 #=> True +2 == 1 #=> False + +# Ungleichheit ist != +1 != 1 #=> False +2 != 1 #=> True + +# Ein paar weitere Vergleiche +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Vergleiche können verknüpft werden! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Strings werden mit " oder ' gebildet +"Das ist ein String." +'Das ist auch ein String.' + +# Strings können addiert werden! +"Hello " + "world!" #=> "Hello world!" + +# Ein String kann wie eine Liste von Zeichen verwendet werden +"Das ist ein String"[0] #=> 'D' + +# Mit % können Strings formatiert werden, etwa so: +"%s können %s werden" % ("Strings", "interpoliert") + +# Ein modernerer Weg, um Strings zu formatieren, ist die format-Methode. +# Diese Methode wird bevorzugt +"{0} können {1} werden".format("Strings", "formatiert") +# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen. +"{name} will {food} essen".format(name="Bob", food="Lasagne") + +# None ist ein Objekt +None #=> None + +# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen +# Benutzt stattdessen `is` +"etc" is None #=> False +None is None #=> True + +# Der 'is'-Operator testet Objektidentität. Das ist nicht +# sehr nützlich, wenn wir mit primitiven Datentypen arbeiten, aber +# sehr nützlich bei Objekten. + +# None, 0, und leere Strings/Listen werden alle als False bewertet. +# Alle anderen Werte sind True +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Variablen und Collections +#################################################### + +# Textausgabe ist sehr einfach +print "Ich bin Python. Schön, dich kennenzulernen!" + + +# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren. +some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm +some_var #=> 5 + +# Das Ansprechen einer noch nicht deklarierte Variable löst eine Exception aus. +# Unter "Kontrollstruktur" kann noch mehr über +# Ausnahmebehandlung erfahren werden. +some_other_var # Löst einen NameError aus + +# if kann als Ausdruck verwendet werden +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Listen speichern Sequenzen +li = [] +# Wir können mit einer bereits gefüllten Liste anfangen +other_li = [4, 5, 6] + +# append fügt Daten am Ende der Liste ein +li.append(1) #li ist jetzt [1] +li.append(2) #li ist jetzt [1, 2] +li.append(4) #li ist jetzt [1, 2, 4] +li.append(3) #li ist jetzt [1, 2, 4, 3] +# Vom Ende der Liste mit pop entfernen +li.pop() #=> 3 und li ist jetzt [1, 2, 4] +# und dann wieder hinzufügen +li.append(3) # li ist jetzt wieder [1, 2, 4, 3]. + +# Greife auf Listen wie auf Arrays zu +li[0] #=> 1 +# Das letzte Element ansehen +li[-1] #=> 3 + +# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError +li[4] # Raises an IndexError + +# Wir können uns Ranges mit Slice-Syntax ansehen +li[1:3] #=> [2, 4] +# Den Anfang auslassen +li[2:] #=> [4, 3] +# Das Ende auslassen +li[:3] #=> [1, 2, 4] + +# Ein bestimmtes Element mit del aus der Liste entfernen +del li[2] # li ist jetzt [1, 2, 3] + +# Listen können addiert werden +li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen + +# Listen mit extend verknüpfen +li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6] + +# Mit in auf Existenz eines Elements prüfen +1 in li #=> True + +# Die Länge der Liste mit len ermitteln +len(li) #=> 6 + + +# Tupel sind wie Listen, nur unveränderlich. +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Löst einen TypeError aus + +# Wir können all diese Listen-Dinge auch mit Tupeln anstellen +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Wir können Tupel (oder Listen) in Variablen entpacken +a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3 +# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen +d, e, f = 4, 5, 6 +# Es ist kinderleicht zwei Werte zu tauschen +e, d = d, e # d is now 5 and e is now 4 + + +# Dictionarys (Wörterbucher) speichern Key-Value-Paare +empty_dict = {} +# Hier ein gefülltes Wörterbuch +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Wir können Einträge mit [] nachschlagen +filled_dict["one"] #=> 1 + +# So holen wir alle Keys (Schlüssel) als Liste +filled_dict.keys() #=> ["three", "two", "one"] +# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert. +# Einzelne Resultate können anders angeordnet sein. + +# Alle Values (Werte) als Liste +filled_dict.values() #=> [3, 2, 1] +# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln. + +# Das Vorhandensein eines Schlüssels im Wörterbuch mit in prüfen +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus +filled_dict["four"] # KeyError + +# Mit der get-Methode verhindern wir das +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen +filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt +filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5 + + +# Sets speichern Mengen +empty_set = set() +# Initialisieren wir ein Set mit ein paar Werten +some_set = set([1,2,2,3,4]) # some_set ist jetzt set([1, 2, 3, 4]) + +# Seit Python 2.7 kann {} benutzt werden, um ein Set zu erstellen +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Mehr Elemente hinzufügen +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Schnittmengen werden mit & gebildet +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Mengen werden mit | vereinigt +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Die Differenz einer Menge mit - bilden +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Auf Vorhandensein von Elementen mit in prüfen +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Kontrollstruktur +#################################################### + +# Erstellen wir mal eine Variable +some_var = 5 + +# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig! +# gibt "some_var ist kleiner als 10" aus +if some_var > 10: + print "some_var ist viel größer als 10." +elif some_var < 10: # Dieser elif-Absatz ist optional. + print "some_var ist kleiner als 10." +else: # Das hier ist auch optional. + print "some_var ist tatsächlich 10." + + +""" +For-Schleifen iterieren über Listen +Ausgabe: + hund ist ein Säugetier + katze ist ein Säugetier + maus ist ein Säugetier +""" +for animal in ["hund", "katze", "maus"]: + # Wir können Strings mit % formatieren + print "%s ist ein Säugetier" % animal + +""" +`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder +Ausgabe: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +While-Schleifen laufen, bis eine Bedingung erfüllt ist. +Ausgabe: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Kurzform für x = x + 1 + +# Ausnahmebehandlung mit einem try/except-Block + +# Funktioniert in Python 2.6 und höher: +try: + # Mit raise wird ein Fehler ausgegeben + raise IndexError("Das hier ist ein Index-Fehler") +except IndexError as e: + pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären. + + +#################################################### +## 4. Funktionen +#################################################### + +# Mit def neue Funktionen erstellen +def add(x, y): + print "x ist %s und y ist %s" % (x, y) + return x + y # Werte werden mit return zurückgegeben + +# Funktionen mit Parametern aufrufen +add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück + +# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente +add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden. + +# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Wir können auch Funktionen mit beliebiger Anzahl +# Schlüsselwort-Argumenten definieren +def keyword_args(**kwargs): + return kwargs + +# Rufen wir es mal auf, um zu sehen, was passiert +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Wir können beides gleichzeitig machem, wenn wir wollen +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) Ausgabe: + (1, 2) + {"a": 3, "b": 4} +""" + +# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen! +# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4) +all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4) +all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4) + +# Python hat First-Class-Funktionen +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Es gibt auch anonyme Funktionen +(lambda x: x > 2)(3) #=> True + +# Es gibt auch Funktionen höherer Ordnung als Built-Ins +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + + +#################################################### +## 5. Module +#################################################### + +# Wir können Module importieren +import math +print math.sqrt(16) #=> 4.0 + +# Wir können auch nur spezielle Funktionen eines Moduls importieren +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Wir können auch alle Funktionen eines Moduls importieren +# Warnung: Dies wird nicht empfohlen +from math import * + +# Wir können Modulnamen abkürzen +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Module sind in Python nur gewöhnliche Dateien. Wir +# können unsere eigenen schreiben und importieren. Der Name des +# Moduls ist der Dateiname. + +# Wir können herausfinden, welche Funktionen und Attribute in einem +# Modul definiert sind. +import math +dir(math) + +# Wenn Sie ein Python-Skript namens math.py im selben Ordner +# wie Ihr aktuelles Skript haben, wird die Datei math.py +# anstelle des integrierten Python-Moduls geladen. +# Dies geschieht, weil der lokale Ordner Vorrang +# vor den in Python integrierten Bibliotheken hat. + + +#################################################### +## 6. Klassen +#################################################### + +# Wir verwenden das Schlüsselwort "class" um eine Klasse zu erzeugen. +class Human(object): + + # Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt + species = "H. sapiens" + + # Ein simpler Konstruktor, wird aufgerufen, wenn diese Klasse instanziiert wird. + # Beachten Sie, dass die doppelten vorangestellten und nachgestellten + # Unterstriche Objekte oder Attribute bezeichnen, die von Python verwendet werden, + # aber in benutzergesteuerten Namespaces leben. + # Methoden (oder Objekte oder Attribute) wie: __init__, __str__, __repr__ usw. + # werden als Sondermethoden (oder manchmal als Dundermethoden bezeichnet) bezeichnet. + # Sie sollten solche Namen nicht selbst erfinden. + def __init__(self, name): + # Wir weisen das Argument name dem name-Attribut der Instanz zu + self.name = name + + # Eine Instanzmethode. Alle Methoden erhalten "self" als erstes Argument. + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Eine weitere Instanzmethode + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # Eine Klassenmethode wird von allen Instanzen geteilt. + # Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen + @classmethod + def get_species(cls): + return cls.species + + # Eine statische Methode wird ohne Klasse oder Instanz aufgerufen + @staticmethod + def grunt(): + return "*grunt*" + + # Eine Eigenschaft (Property) ist wie ein Getter. +    # Es verwandelt die Methode age() in ein schreibgeschütztes Attribut mit demselben Namen. +    # Es ist jedoch nicht nötig, triviale Getter und Setter in Python zu schreiben. + @property + def age(self): + return self._age + +    # Damit kann die Eigenschaft festgelegt werden + @age.setter + def age(self, age): + self._age = age + +    # Damit kann die Eigenschaft gelöscht werden + @age.deleter + def age(self): + del self._age + +# Wenn ein Python-Interpreter eine Quelldatei liest, führt er den gesamten Code aus. +# Diese __name__-Prüfung stellt sicher, dass dieser Codeblock nur ausgeführt wird, +# wenn dieses Modul das Hauptprogramm ist. +if __name__ == '__main__': + # Eine Instanz einer Klasse erstellen + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i und j sind Instanzen des Typs Mensch, oder anders ausgedrückt: Sie sind Objekte des Menschen + + # Rufen wir unsere Klassenmethode auf + i.say(i.get_species()) # "Ian: H. sapiens" + + # Ändern wir das gemeinsame Attribut + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Aufruf der statischen Methode + print(Human.grunt()) # => "*grunt*" + + # Kann keine statische Methode mit Instanz des Objekts aufrufen, + # da i.grunt () automatisch "self" (das Objekt i) als Argument verwendet + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # Die Eigenschaft für diese Instanz aktualisieren + i.age = 42 + # die Eigenschaft auslesen + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # die Eigenschaft löschen + del i.age + # i.age # => würde einen AttributeError werfen + +#################################################### +## 6.1 Inheritance +#################################################### + +# Vererbung ermöglicht die Definition neuer untergeordneter Klassen, +# die Methoden und Variablen von ihrer übergeordneten Klasse erben. + +# Wenn Sie die oben definierte Human-Klasse als Basis- oder Elternklasse verwenden, +# können Sie eine untergeordnete Klasse, Superhero, definieren, die die Klassenvariablen +# wie "species", "name" und "age" sowie Methoden wie "sing" und "grunzen" aus der Klasse Human erbt. +# Die Untergeordnete Klasse kann aber auch eigene Eigenschaften haben. + +# Um von der Modularisierung per Datei zu profitieren, können Sie die Klassen +# in ihren eigenen Dateien platzieren, z. B. human.py + +# Um Funktionen aus anderen Dateien zu importieren, verwenden Sie das folgende Format +# from "Dateiname-ohne-Erweiterung" impotr "Funktion-oder-Klasse" + +from human import Human + +# Geben Sie die übergeordnete(n) Klasse(n) als Parameter für die Klassendefinition an +class Superhero(Human): + + # Wenn die untergeordnete Klasse alle Definitionen des übergeordneten Elements + # ohne Änderungen erben soll, können Sie einfach das Schlüsselwort "pass" + # (und nichts anderes) verwenden. In diesem Fall wird jedoch auskommentiert, + # um eine eindeutige untergeordnete Klasse zuzulassen: + # pass + + # Kindklassen können die Attribute ihrer Eltern überschreiben + species = 'Superhuman' + + # Kinder erben automatisch den Konstruktor ihrer übergeordneten Klasse + # einschließlich ihrer Argumente, können aber auch zusätzliche Argumente oder + # Definitionen definieren und ihre Methoden zB den Klassenkonstruktor überschreiben. + # Dieser Konstruktor erbt das Argument "name" von der Klasse "Human" und + # fügt die Argumente "superpowers" und "movie" hinzu: + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # zusätzliche Klassenattribute hinzufügen: + self.fictional = True + self.movie = movie + # Beachten Sie die veränderlichen Standardwerte, da die Standardwerte gemeinsam genutzt werden + self.superpowers = superpowers + + # Mit der Funktion "super" können Sie auf die Methoden der übergeordneten Klasse + # zugreifen, die vom untergeordneten Objekt überschrieben werden, + # in diesem Fall die Methode __init__. +        # Dies ruft den Konstruktor der übergeordneten Klasse auf: + super().__init__(name) + + # überschreiben der "sing" Methode + def sing(self): + return 'Dun, dun, DUN!' + + # eine zusätzliche Instanzmethode hinzufügen + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # Instanztypprüfungen + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') + + # Die Reihenfolge der Methodenauflösung (MRO = Method Resolution Order) anzeigen, die sowohl von getattr() als auch von super() verwendet wird. +    # Dieses Attribut ist dynamisch und kann aktualisiert werden. + print(Superhero.__mro__) # => (, + # => , ) + + # Ruft die übergeordnete Methode auf, verwendet jedoch das eigene Klassenattribut + print(sup.get_species()) # => Superhuman + + # Ruft die überschriebene Methode auf + print(sup.sing()) # => Dun, dun, DUN! + + # Ruft die Methode von Human auf + sup.say('Spoon') # => Tick: Spoon + + # Aufruf einer Methode, die nur in Superhero existiert + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # Vererbtes Klassenattribut + sup.age = 31 + print(sup.age) # => 31 + + # Attribut, das nur in Superhero existiert + print('Am I Oscar eligible? ' + str(sup.movie)) + +#################################################### +## 6.2 Multiple Inheritance +#################################################### + +# Eine weitere Klassendefinition +# bat.py + +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # This class also has a say method + def say(self, msg): + msg = '... ... ...' + return msg + + # And its own method as well + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + +# Und noch eine andere Klassendefinition, die von Superhero und Bat erbt +# superhero.py +from superhero import Superhero +from bat import Bat + +# Definieren Sie Batman als eine Kindklasse, das von Superheld und Bat erbt +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # In der Regel müssen Sie super aufrufen, um Attribute zu erben: + # super (Batman, selbst) .__ init__ (* args, ** kwargs) + # Allerdings handelt es sich hier um Mehrfachvererbung, und super() + # funktioniert nur mit der nächsten Basisklasse in der MRO-Liste. + # Stattdessen rufen wir explizit __init__ für alle Vorfahren auf. + # Die Verwendung von *args und **kwargs ermöglicht die saubere Übergabe von + # Argumenten, wobei jedes übergeordnete Element eine Schicht der Zwiebel "abschält". + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # überschreibt den Wert für das Namensattribut + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + +if __name__ == '__main__': + sup = Batman() + + # Die Reihenfolge der Methodenauflösung (MRO = Method Resolution Order) anzeigen, + # die sowohl von getattr() als auch von super() verwendet wird. + # Dieses Attribut ist dynamisch und kann aktualisiert werden. + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + # Ruft die übergeordnete Methode auf, verwendet jedoch das eigene Klassenattribut + print(sup.get_species()) # => Superhuman + + # Ruft die überschriebene Methode auf + print(sup.sing()) # => nan nan nan nan nan batman! + + # Ruft die Methode von Human auf, weil die Reihenfolge der Vererbung wichtig ist + sup.say('I agree') # => Sad Affleck: I agree + + # Aufrufmethode, die nur im 2. Vorfahren existiert + print(sup.sonar()) # => ))) ... ((( + + # Vererbtes Klassenattribut + sup.age = 100 + print(sup.age) # => 100 + + # Vererbtes Attribut vom 2. Vorfahren, dessen Standardwert überschrieben wurde. + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False + + +#################################################### +## 7. Fortgeschrittenes +#################################################### + +# Generatoren helfen Ihnen, lazy Code zu erstellen. +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Generatoren sind speichereffizient, da sie nur die Daten laden, +# die zur Verarbeitung des nächsten Werts in der iterierbaren Komponente +# erforderlich sind. Dadurch können sie ansonsten unzulässig große Wertebereiche ausführen. +# HINWEIS: `range` ersetzt` xrange` in Python 3. +for i in double_numbers(range(1, 900000000)): # `range` ist ein Generator. + print(i) + if i >= 30: + break + +# Genauso wie Sie ein 'list comprehension' (Listen Abstraktion) erstellen können, können Sie auch 'generator comprehension' (Generator Abstraktion) erstellen. +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# Sie können eine Generator Abstraktion auch direkt in eine Liste umwandeln (casten). +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + +# Decorators +# In diesem Beispiel umschliesst "beg" "say". Wenn say_please True ist, wird die zurückgegebene Nachricht geändert. +from functools import wraps + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( + +``` + +## Lust auf mehr? + +### Kostenlos online (Englisch) + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### Totholz (Englisch) + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown deleted file mode 100644 index 2b8f498a..00000000 --- a/es-es/python-es.html.markdown +++ /dev/null @@ -1,562 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["Camilo Garrido", "http://www.twitter.com/hirohope"] - - ["Fabio Souto", "http://fabiosouto.me"] -lang: es-es -filename: learnpython-es.py ---- - -Python fue creado por Guido Van Rossum en el principio de los 90. Ahora es uno -de los lenguajes más populares que existen. Me enamoré de Python por su claridad sintáctica. -Es básicamente pseudocódigo ejecutable. - -¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google] - -Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser aplicable a Python 2.x. ¡Pronto un recorrido por Python 3! - -```python -# Comentarios de una línea comienzan con una almohadilla (o signo gato) -""" Strings multilínea pueden escribirse - usando tres "'s, y comúnmente son usados - como comentarios. -""" - -#################################################### -## 1. Tipos de datos primitivos y operadores. -#################################################### - -# Tienes números -3 #=> 3 - -# Evidentemente puedes realizar operaciones matemáticas -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 - -# La división es un poco complicada. Es división entera y toma la parte entera -# de los resultados automáticamente. -5 / 2 #=> 2 - -# Para arreglar la división necesitamos aprender sobre 'floats' -# (números de coma flotante). -2.0 # Esto es un 'float' -11.0 / 4.0 #=> 2.75 ahhh...mucho mejor - -# Resultado de la división de enteros truncada para positivos y negativos -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # funciona con números de coma flotante --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# El operador módulo devuelve el resto de una división entre enteros -7 % 3 # => 1 - -# Exponenciación (x elevado a y) -2**4 # => 16 - -# Refuerza la precedencia con paréntesis -(1 + 3) * 2 #=> 8 - -# Operadores booleanos -# Nota: "and" y "or" son sensibles a mayúsculas -True and False #=> False -False or True #=> True - -# Podemos usar operadores booleanos con números enteros -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True - -# Niega con 'not' -not True #=> False -not False #=> True - -# Igualdad es == -1 == 1 #=> True -2 == 1 #=> False - -# Desigualdad es != -1 != 1 #=> False -2 != 1 #=> True - -# Más comparaciones -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True - -# ¡Las comparaciones pueden ser concatenadas! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False - -# Strings se crean con " o ' -"Esto es un string." -'Esto también es un string' - -# ¡Strings también pueden ser sumados! -"Hola " + "mundo!" #=> "Hola mundo!" - -# Un string puede ser tratado como una lista de caracteres -"Esto es un string"[0] #=> 'E' - -# % pueden ser usados para formatear strings, como esto: -"%s pueden ser %s" % ("strings", "interpolados") - -# Una forma más reciente de formatear strings es el método 'format'. -# Este método es la forma preferida -"{0} pueden ser {1}".format("strings", "formateados") -# Puedes usar palabras clave si no quieres contar. -"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") - -# None es un objeto -None #=> None - -# No uses el símbolo de igualdad `==` para comparar objetos con None -# Usa `is` en lugar de -"etc" is None #=> False -None is None #=> True - -# El operador 'is' prueba la identidad del objeto. Esto no es -# muy útil cuando se trata de datos primitivos, pero es -# muy útil cuando se trata de objetos. - -# None, 0, y strings/listas vacíos(as) todas se evalúan como False. -# Todos los otros valores son True -bool(0) #=> False -bool("") #=> False - - -#################################################### -## 2. Variables y Colecciones -#################################################### - -# Imprimir es muy fácil -print "Soy Python. ¡Encantado de conocerte!" - - -# No hay necesidad de declarar las variables antes de asignarlas. -una_variable = 5 # La convención es usar guiones_bajos_con_minúsculas -una_variable #=> 5 - -# Acceder a variables no asignadas previamente es una excepción. -# Ve Control de Flujo para aprender más sobre el manejo de excepciones. -otra_variable # Levanta un error de nombre - -# 'if' puede ser usado como una expresión -"yahoo!" if 3 > 2 else 2 #=> "yahoo!" - -# Las listas almacenan secuencias -lista = [] -# Puedes empezar con una lista prellenada -otra_lista = [4, 5, 6] - -# Añadir cosas al final de una lista con 'append' -lista.append(1) # lista ahora es [1] -lista.append(2) # lista ahora es [1, 2] -lista.append(4) # lista ahora es [1, 2, 4] -lista.append(3) # lista ahora es [1, 2, 4, 3] -# Remueve del final de la lista con 'pop' -lista.pop() #=> 3 y lista ahora es [1, 2, 4] -# Pongámoslo de vuelta -lista.append(3) # Nuevamente lista ahora es [1, 2, 4, 3]. - -# Accede a una lista como lo harías con cualquier arreglo -lista[0] #=> 1 -# Mira el último elemento -lista[-1] #=> 3 - -# Mirar fuera de los límites es un error 'IndexError' -lista[4] # Levanta la excepción IndexError - -# Puedes mirar por rango con la sintáxis de trozo. -# (Es un rango cerrado/abierto para ustedes los matemáticos.) -lista[1:3] #=> [2, 4] -# Omite el inicio -lista[2:] #=> [4, 3] -# Omite el final -lista[:3] #=> [1, 2, 4] - -# Remueve elementos arbitrarios de una lista con 'del' -del lista[2] # lista ahora es [1, 2, 3] - -# Puedes sumar listas -lista + otra_lista #=> [1, 2, 3, 4, 5, 6] - Nota: lista y otra_lista no se tocan - -# Concatenar listas con 'extend' -lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6] - -# Chequea la existencia en una lista con -1 in lista #=> True - -# Examina el tamaño de una lista con 'len' -len(lista) #=> 6 - - -# Las tuplas son como las listas, pero son inmutables. -tupla = (1, 2, 3) -tupla[0] #=> 1 -tupla[0] = 3 # Levanta un error TypeError - -# También puedes hacer todas esas cosas que haces con listas -len(tupla) #=> 3 -tupla + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tupla[:2] #=> (1, 2) -2 in tupla #=> True - -# Puedes desempacar tuplas (o listas) en variables -a, b, c = (1, 2, 3) # a ahora es 1, b ahora es 2 y c ahora es 3 -# Tuplas son creadas por defecto si omites los paréntesis -d, e, f = 4, 5, 6 -# Ahora mira que fácil es intercambiar dos valores -e, d = d, e # d ahora es 5 y e ahora es 4 - - -# Diccionarios almacenan mapeos -dicc_vacio = {} -# Aquí está un diccionario prellenado -dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} - -# Busca valores con [] -dicc_lleno["uno"] #=> 1 - -# Obtén todas las llaves como una lista -dicc_lleno.keys() #=> ["tres", "dos", "uno"] -# Nota - El orden de las llaves del diccionario no está garantizada. -# Tus resultados podrían no ser los mismos del ejemplo. - -# Obtén todos los valores como una lista -dicc_lleno.values() #=> [3, 2, 1] -# Nota - Lo mismo que con las llaves, no se garantiza el orden. - -# Chequea la existencia de una llave en el diccionario con 'in' -"uno" in dicc_lleno #=> True -1 in dicc_lleno #=> False - -# Buscar una llave inexistente deriva en KeyError -dicc_lleno["cuatro"] # KeyError - -# Usa el método 'get' para evitar la excepción KeyError -dicc_lleno.get("uno") #=> 1 -dicc_lleno.get("cuatro") #=> None -# El método 'get' soporta un argumento por defecto cuando el valor no existe. -dicc_lleno.get("uno", 4) #=> 1 -dicc_lleno.get("cuatro", 4) #=> 4 - -# El método 'setdefault' es una manera segura de añadir nuevos pares -# llave-valor en un diccionario -dicc_lleno.setdefault("cinco", 5) #dicc_lleno["cinco"] es puesto con valor 5 -dicc_lleno.setdefault("cinco", 6) #dicc_lleno["cinco"] todavía es 5 - - -# Sets (conjuntos) almacenan ... bueno, conjuntos -conjunto_vacio = set() -# Inicializar un conjunto con montón de valores -un_conjunto = set([1,2,2,3,4]) # un_conjunto ahora es set([1, 2, 3, 4]) - -# Desde Python 2.7, {} puede ser usado para declarar un conjunto -conjunto_lleno = {1, 2, 2, 3, 4} # => {1 2 3 4} - -# Añade más valores a un conjunto -conjunto_lleno.add(5) # conjunto_lleno ahora es {1, 2, 3, 4, 5} - -# Haz intersección de conjuntos con & -otro_conjunto = {3, 4, 5, 6} -conjunto_lleno & otro_conjunto #=> {3, 4, 5} - -# Haz unión de conjuntos con | -conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} - -# Haz diferencia de conjuntos con - -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# Chequea la existencia en un conjunto con 'in' -2 in conjunto_lleno #=> True -10 in conjunto_lleno #=> False - - -#################################################### -## 3. Control de Flujo -#################################################### - -# Hagamos sólo una variable -una_variable = 5 - -# Aquí está una declaración de un 'if'. ¡La indentación es importante en Python! -# imprime "una_variable es menor que 10" -if una_variable > 10: - print "una_variable es completamente mas grande que 10." -elif una_variable < 10: # Este condición 'elif' es opcional. - print "una_variable es mas chica que 10." -else: # Esto también es opcional. - print "una_variable es de hecho 10." - - -""" -For itera sobre listas -imprime: - perro es un mamifero - gato es un mamifero - raton es un mamifero -""" -for animal in ["perro", "gato", "raton"]: - # Puedes usar % para interpolar strings formateados - print "%s es un mamifero" % animal - -""" -`range(número)` retorna una lista de números -desde cero hasta el número dado -imprime: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -While itera hasta que una condición no se cumple. -imprime: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # versión corta de x = x + 1 - -# Maneja excepciones con un bloque try/except - -# Funciona desde Python 2.6 en adelante: -try: - # Usa raise para levantar un error - raise IndexError("Este es un error de indice") -except IndexError as e: - pass # Pass no hace nada. Usualmente harias alguna recuperacion aqui. - - -#################################################### -## 4. Funciones -#################################################### - -# Usa 'def' para crear nuevas funciones -def add(x, y): - print "x es %s y y es %s" % (x, y) - return x + y # Retorna valores con una la declaración return - -# Llamando funciones con parámetros -add(5, 6) #=> imprime "x es 5 y y es 6" y retorna 11 - -# Otra forma de llamar funciones es con argumentos de palabras claves -add(y=6, x=5) # Argumentos de palabra clave pueden ir en cualquier orden. - -# Puedes definir funciones que tomen un número variable de argumentos -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# Puedes definir funciones que toman un número variable de argumentos -# de palabras claves -def keyword_args(**kwargs): - return kwargs - -# Llamémosla para ver que sucede -keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"} - -# Puedes hacer ambas a la vez si quieres -def todos_los_argumentos(*args, **kwargs): - print args - print kwargs -""" -todos_los_argumentos(1, 2, a=3, b=4) imprime: - (1, 2) - {"a": 3, "b": 4} -""" - -# ¡Cuando llames funciones, puedes hacer lo opuesto a varargs/kwargs! -# Usa * para expandir tuplas y usa ** para expandir argumentos de palabras claves. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -todos_los_argumentos(*args) # es equivalente a foo(1, 2, 3, 4) -todos_los_argumentos(**kwargs) # es equivalente a foo(a=3, b=4) -todos_los_argumentos(*args, **kwargs) # es equivalente a foo(1, 2, 3, 4, a=3, b=4) - -# Python tiene funciones de primera clase -def crear_suma(x): - def suma(y): - return x + y - return suma - -sumar_10 = crear_suma(10) -sumar_10(3) #=> 13 - -# También hay funciones anónimas -(lambda x: x > 2)(3) #=> True - -# Hay funciones integradas de orden superior -map(sumar_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# Podemos usar listas por comprensión para mapeos y filtros agradables -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] - -#################################################### -## 5. Clases -#################################################### - -# Heredamos de object para obtener una clase. -class Humano(object): - - # Un atributo de clase es compartido por todas las instancias de esta clase - especie = "H. sapiens" - - # Constructor básico, se llama al instanciar la clase. - def __init__(self, nombre): - # Asigna el argumento al atributo nombre de la instancia - self.nombre = nombre - - # Un método de instancia. Todos los metodos toman self como primer argumento - def decir(self, msg): - return "%s: %s" % (self.nombre, msg) - - # Un metodo de clase es compartido a través de todas las instancias - # Son llamados con la clase como primer argumento - @classmethod - def get_especie(cls): - return cls.especie - - # Un metodo estático es llamado sin la clase o instancia como referencia - @staticmethod - def roncar(): - return "*roncar*" - - -# Instancia una clase -i = Humano(nombre="Ian") -print i.decir("hi") # imprime "Ian: hi" - -j = Humano("Joel") -print j.decir("hello") #imprime "Joel: hello" - -# Llama nuestro método de clase -i.get_especie() #=> "H. sapiens" - -# Cambia los atributos compartidos -Humano.especie = "H. neanderthalensis" -i.get_especie() #=> "H. neanderthalensis" -j.get_especie() #=> "H. neanderthalensis" - -# Llama al método estático -Humano.roncar() #=> "*roncar*" - - -#################################################### -## 6. Módulos -#################################################### - -# Puedes importar módulos -import math -print math.sqrt(16) #=> 4.0 - -# Puedes obtener funciones específicas desde un módulo -from math import ceil, floor -print ceil(3.7) #=> 4.0 -print floor(3.7) #=> 3.0 - -# Puedes importar todas las funciones de un módulo -# Precaución: Esto no es recomendable -from math import * - -# Puedes acortar los nombres de los módulos -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Los módulos de Python son sólo archivos ordinarios de Python. -# Puedes escribir tus propios módulos e importarlos. El nombre del módulo -# es el mismo del nombre del archivo. - -# Puedes encontrar que funciones y atributos definen un módulo. -import math -dir(math) - - -#################################################### -## 7. Avanzado -#################################################### - -# Los generadores permiten evaluación perezosa -def duplicar_numeros(iterable): - for i in iterable: - yield i + i - -# Un generador crea valores sobre la marcha -# En vez de generar y devolver todos los valores de una vez, crea un valor -# en cada iteración. En este ejemplo los valores mayores que 15 no serán -# procesados en duplicar_numeros. -# Nota: xrange es un generador que hace lo mismo que range. -# Crear una lista de 1 a 900000000 lleva mucho tiempo y ocupa mucho espacio. -# xrange crea un generador, mientras que range crea toda la lista. -# Añadimos un guión bajo a los nombres de variable que coinciden con palabras -# reservadas de python. -xrange_ = xrange(1, 900000000) - -# duplica todos los números hasta que encuentra un resultado >= 30 -for i in duplicar_numeros(xrange_): - print i - if i >= 30: - break - -# Decoradores -# en este ejemplo pedir rodea a hablar -# Si por_favor es True se cambiará el mensaje. -from functools import wraps - - -def pedir(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, por_favor = target_function(*args, **kwargs) - if por_favor: - return "{} {}".format(msg, "¡Por favor! Soy pobre :(") - return msg - - return wrapper - - -@pedir -def hablar(por_favor=False): - msg = "¿Me puedes comprar una cerveza?" - return msg, por_favor - -print hablar() # ¿Me puedes comprar una cerveza? -print hablar(por_favor=True) # ¿Me puedes comprar una cerveza? ¡Por favor! Soy pobre :( -``` - -## ¿Listo para más? - -### Gratis y en línea - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2.6/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) - -### Encuadernados - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/es-es/pythonlegacy-es.html.markdown b/es-es/pythonlegacy-es.html.markdown new file mode 100644 index 00000000..2b8f498a --- /dev/null +++ b/es-es/pythonlegacy-es.html.markdown @@ -0,0 +1,562 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Camilo Garrido", "http://www.twitter.com/hirohope"] + - ["Fabio Souto", "http://fabiosouto.me"] +lang: es-es +filename: learnpython-es.py +--- + +Python fue creado por Guido Van Rossum en el principio de los 90. Ahora es uno +de los lenguajes más populares que existen. Me enamoré de Python por su claridad sintáctica. +Es básicamente pseudocódigo ejecutable. + +¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google] + +Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser aplicable a Python 2.x. ¡Pronto un recorrido por Python 3! + +```python +# Comentarios de una línea comienzan con una almohadilla (o signo gato) +""" Strings multilínea pueden escribirse + usando tres "'s, y comúnmente son usados + como comentarios. +""" + +#################################################### +## 1. Tipos de datos primitivos y operadores. +#################################################### + +# Tienes números +3 #=> 3 + +# Evidentemente puedes realizar operaciones matemáticas +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# La división es un poco complicada. Es división entera y toma la parte entera +# de los resultados automáticamente. +5 / 2 #=> 2 + +# Para arreglar la división necesitamos aprender sobre 'floats' +# (números de coma flotante). +2.0 # Esto es un 'float' +11.0 / 4.0 #=> 2.75 ahhh...mucho mejor + +# Resultado de la división de enteros truncada para positivos y negativos +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # funciona con números de coma flotante +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# El operador módulo devuelve el resto de una división entre enteros +7 % 3 # => 1 + +# Exponenciación (x elevado a y) +2**4 # => 16 + +# Refuerza la precedencia con paréntesis +(1 + 3) * 2 #=> 8 + +# Operadores booleanos +# Nota: "and" y "or" son sensibles a mayúsculas +True and False #=> False +False or True #=> True + +# Podemos usar operadores booleanos con números enteros +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Niega con 'not' +not True #=> False +not False #=> True + +# Igualdad es == +1 == 1 #=> True +2 == 1 #=> False + +# Desigualdad es != +1 != 1 #=> False +2 != 1 #=> True + +# Más comparaciones +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# ¡Las comparaciones pueden ser concatenadas! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Strings se crean con " o ' +"Esto es un string." +'Esto también es un string' + +# ¡Strings también pueden ser sumados! +"Hola " + "mundo!" #=> "Hola mundo!" + +# Un string puede ser tratado como una lista de caracteres +"Esto es un string"[0] #=> 'E' + +# % pueden ser usados para formatear strings, como esto: +"%s pueden ser %s" % ("strings", "interpolados") + +# Una forma más reciente de formatear strings es el método 'format'. +# Este método es la forma preferida +"{0} pueden ser {1}".format("strings", "formateados") +# Puedes usar palabras clave si no quieres contar. +"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") + +# None es un objeto +None #=> None + +# No uses el símbolo de igualdad `==` para comparar objetos con None +# Usa `is` en lugar de +"etc" is None #=> False +None is None #=> True + +# El operador 'is' prueba la identidad del objeto. Esto no es +# muy útil cuando se trata de datos primitivos, pero es +# muy útil cuando se trata de objetos. + +# None, 0, y strings/listas vacíos(as) todas se evalúan como False. +# Todos los otros valores son True +bool(0) #=> False +bool("") #=> False + + +#################################################### +## 2. Variables y Colecciones +#################################################### + +# Imprimir es muy fácil +print "Soy Python. ¡Encantado de conocerte!" + + +# No hay necesidad de declarar las variables antes de asignarlas. +una_variable = 5 # La convención es usar guiones_bajos_con_minúsculas +una_variable #=> 5 + +# Acceder a variables no asignadas previamente es una excepción. +# Ve Control de Flujo para aprender más sobre el manejo de excepciones. +otra_variable # Levanta un error de nombre + +# 'if' puede ser usado como una expresión +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Las listas almacenan secuencias +lista = [] +# Puedes empezar con una lista prellenada +otra_lista = [4, 5, 6] + +# Añadir cosas al final de una lista con 'append' +lista.append(1) # lista ahora es [1] +lista.append(2) # lista ahora es [1, 2] +lista.append(4) # lista ahora es [1, 2, 4] +lista.append(3) # lista ahora es [1, 2, 4, 3] +# Remueve del final de la lista con 'pop' +lista.pop() #=> 3 y lista ahora es [1, 2, 4] +# Pongámoslo de vuelta +lista.append(3) # Nuevamente lista ahora es [1, 2, 4, 3]. + +# Accede a una lista como lo harías con cualquier arreglo +lista[0] #=> 1 +# Mira el último elemento +lista[-1] #=> 3 + +# Mirar fuera de los límites es un error 'IndexError' +lista[4] # Levanta la excepción IndexError + +# Puedes mirar por rango con la sintáxis de trozo. +# (Es un rango cerrado/abierto para ustedes los matemáticos.) +lista[1:3] #=> [2, 4] +# Omite el inicio +lista[2:] #=> [4, 3] +# Omite el final +lista[:3] #=> [1, 2, 4] + +# Remueve elementos arbitrarios de una lista con 'del' +del lista[2] # lista ahora es [1, 2, 3] + +# Puedes sumar listas +lista + otra_lista #=> [1, 2, 3, 4, 5, 6] - Nota: lista y otra_lista no se tocan + +# Concatenar listas con 'extend' +lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6] + +# Chequea la existencia en una lista con +1 in lista #=> True + +# Examina el tamaño de una lista con 'len' +len(lista) #=> 6 + + +# Las tuplas son como las listas, pero son inmutables. +tupla = (1, 2, 3) +tupla[0] #=> 1 +tupla[0] = 3 # Levanta un error TypeError + +# También puedes hacer todas esas cosas que haces con listas +len(tupla) #=> 3 +tupla + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tupla[:2] #=> (1, 2) +2 in tupla #=> True + +# Puedes desempacar tuplas (o listas) en variables +a, b, c = (1, 2, 3) # a ahora es 1, b ahora es 2 y c ahora es 3 +# Tuplas son creadas por defecto si omites los paréntesis +d, e, f = 4, 5, 6 +# Ahora mira que fácil es intercambiar dos valores +e, d = d, e # d ahora es 5 y e ahora es 4 + + +# Diccionarios almacenan mapeos +dicc_vacio = {} +# Aquí está un diccionario prellenado +dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} + +# Busca valores con [] +dicc_lleno["uno"] #=> 1 + +# Obtén todas las llaves como una lista +dicc_lleno.keys() #=> ["tres", "dos", "uno"] +# Nota - El orden de las llaves del diccionario no está garantizada. +# Tus resultados podrían no ser los mismos del ejemplo. + +# Obtén todos los valores como una lista +dicc_lleno.values() #=> [3, 2, 1] +# Nota - Lo mismo que con las llaves, no se garantiza el orden. + +# Chequea la existencia de una llave en el diccionario con 'in' +"uno" in dicc_lleno #=> True +1 in dicc_lleno #=> False + +# Buscar una llave inexistente deriva en KeyError +dicc_lleno["cuatro"] # KeyError + +# Usa el método 'get' para evitar la excepción KeyError +dicc_lleno.get("uno") #=> 1 +dicc_lleno.get("cuatro") #=> None +# El método 'get' soporta un argumento por defecto cuando el valor no existe. +dicc_lleno.get("uno", 4) #=> 1 +dicc_lleno.get("cuatro", 4) #=> 4 + +# El método 'setdefault' es una manera segura de añadir nuevos pares +# llave-valor en un diccionario +dicc_lleno.setdefault("cinco", 5) #dicc_lleno["cinco"] es puesto con valor 5 +dicc_lleno.setdefault("cinco", 6) #dicc_lleno["cinco"] todavía es 5 + + +# Sets (conjuntos) almacenan ... bueno, conjuntos +conjunto_vacio = set() +# Inicializar un conjunto con montón de valores +un_conjunto = set([1,2,2,3,4]) # un_conjunto ahora es set([1, 2, 3, 4]) + +# Desde Python 2.7, {} puede ser usado para declarar un conjunto +conjunto_lleno = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Añade más valores a un conjunto +conjunto_lleno.add(5) # conjunto_lleno ahora es {1, 2, 3, 4, 5} + +# Haz intersección de conjuntos con & +otro_conjunto = {3, 4, 5, 6} +conjunto_lleno & otro_conjunto #=> {3, 4, 5} + +# Haz unión de conjuntos con | +conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} + +# Haz diferencia de conjuntos con - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Chequea la existencia en un conjunto con 'in' +2 in conjunto_lleno #=> True +10 in conjunto_lleno #=> False + + +#################################################### +## 3. Control de Flujo +#################################################### + +# Hagamos sólo una variable +una_variable = 5 + +# Aquí está una declaración de un 'if'. ¡La indentación es importante en Python! +# imprime "una_variable es menor que 10" +if una_variable > 10: + print "una_variable es completamente mas grande que 10." +elif una_variable < 10: # Este condición 'elif' es opcional. + print "una_variable es mas chica que 10." +else: # Esto también es opcional. + print "una_variable es de hecho 10." + + +""" +For itera sobre listas +imprime: + perro es un mamifero + gato es un mamifero + raton es un mamifero +""" +for animal in ["perro", "gato", "raton"]: + # Puedes usar % para interpolar strings formateados + print "%s es un mamifero" % animal + +""" +`range(número)` retorna una lista de números +desde cero hasta el número dado +imprime: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +While itera hasta que una condición no se cumple. +imprime: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # versión corta de x = x + 1 + +# Maneja excepciones con un bloque try/except + +# Funciona desde Python 2.6 en adelante: +try: + # Usa raise para levantar un error + raise IndexError("Este es un error de indice") +except IndexError as e: + pass # Pass no hace nada. Usualmente harias alguna recuperacion aqui. + + +#################################################### +## 4. Funciones +#################################################### + +# Usa 'def' para crear nuevas funciones +def add(x, y): + print "x es %s y y es %s" % (x, y) + return x + y # Retorna valores con una la declaración return + +# Llamando funciones con parámetros +add(5, 6) #=> imprime "x es 5 y y es 6" y retorna 11 + +# Otra forma de llamar funciones es con argumentos de palabras claves +add(y=6, x=5) # Argumentos de palabra clave pueden ir en cualquier orden. + +# Puedes definir funciones que tomen un número variable de argumentos +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Puedes definir funciones que toman un número variable de argumentos +# de palabras claves +def keyword_args(**kwargs): + return kwargs + +# Llamémosla para ver que sucede +keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"} + +# Puedes hacer ambas a la vez si quieres +def todos_los_argumentos(*args, **kwargs): + print args + print kwargs +""" +todos_los_argumentos(1, 2, a=3, b=4) imprime: + (1, 2) + {"a": 3, "b": 4} +""" + +# ¡Cuando llames funciones, puedes hacer lo opuesto a varargs/kwargs! +# Usa * para expandir tuplas y usa ** para expandir argumentos de palabras claves. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +todos_los_argumentos(*args) # es equivalente a foo(1, 2, 3, 4) +todos_los_argumentos(**kwargs) # es equivalente a foo(a=3, b=4) +todos_los_argumentos(*args, **kwargs) # es equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# Python tiene funciones de primera clase +def crear_suma(x): + def suma(y): + return x + y + return suma + +sumar_10 = crear_suma(10) +sumar_10(3) #=> 13 + +# También hay funciones anónimas +(lambda x: x > 2)(3) #=> True + +# Hay funciones integradas de orden superior +map(sumar_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Podemos usar listas por comprensión para mapeos y filtros agradables +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#################################################### +## 5. Clases +#################################################### + +# Heredamos de object para obtener una clase. +class Humano(object): + + # Un atributo de clase es compartido por todas las instancias de esta clase + especie = "H. sapiens" + + # Constructor básico, se llama al instanciar la clase. + def __init__(self, nombre): + # Asigna el argumento al atributo nombre de la instancia + self.nombre = nombre + + # Un método de instancia. Todos los metodos toman self como primer argumento + def decir(self, msg): + return "%s: %s" % (self.nombre, msg) + + # Un metodo de clase es compartido a través de todas las instancias + # Son llamados con la clase como primer argumento + @classmethod + def get_especie(cls): + return cls.especie + + # Un metodo estático es llamado sin la clase o instancia como referencia + @staticmethod + def roncar(): + return "*roncar*" + + +# Instancia una clase +i = Humano(nombre="Ian") +print i.decir("hi") # imprime "Ian: hi" + +j = Humano("Joel") +print j.decir("hello") #imprime "Joel: hello" + +# Llama nuestro método de clase +i.get_especie() #=> "H. sapiens" + +# Cambia los atributos compartidos +Humano.especie = "H. neanderthalensis" +i.get_especie() #=> "H. neanderthalensis" +j.get_especie() #=> "H. neanderthalensis" + +# Llama al método estático +Humano.roncar() #=> "*roncar*" + + +#################################################### +## 6. Módulos +#################################################### + +# Puedes importar módulos +import math +print math.sqrt(16) #=> 4.0 + +# Puedes obtener funciones específicas desde un módulo +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Puedes importar todas las funciones de un módulo +# Precaución: Esto no es recomendable +from math import * + +# Puedes acortar los nombres de los módulos +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Los módulos de Python son sólo archivos ordinarios de Python. +# Puedes escribir tus propios módulos e importarlos. El nombre del módulo +# es el mismo del nombre del archivo. + +# Puedes encontrar que funciones y atributos definen un módulo. +import math +dir(math) + + +#################################################### +## 7. Avanzado +#################################################### + +# Los generadores permiten evaluación perezosa +def duplicar_numeros(iterable): + for i in iterable: + yield i + i + +# Un generador crea valores sobre la marcha +# En vez de generar y devolver todos los valores de una vez, crea un valor +# en cada iteración. En este ejemplo los valores mayores que 15 no serán +# procesados en duplicar_numeros. +# Nota: xrange es un generador que hace lo mismo que range. +# Crear una lista de 1 a 900000000 lleva mucho tiempo y ocupa mucho espacio. +# xrange crea un generador, mientras que range crea toda la lista. +# Añadimos un guión bajo a los nombres de variable que coinciden con palabras +# reservadas de python. +xrange_ = xrange(1, 900000000) + +# duplica todos los números hasta que encuentra un resultado >= 30 +for i in duplicar_numeros(xrange_): + print i + if i >= 30: + break + +# Decoradores +# en este ejemplo pedir rodea a hablar +# Si por_favor es True se cambiará el mensaje. +from functools import wraps + + +def pedir(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, por_favor = target_function(*args, **kwargs) + if por_favor: + return "{} {}".format(msg, "¡Por favor! Soy pobre :(") + return msg + + return wrapper + + +@pedir +def hablar(por_favor=False): + msg = "¿Me puedes comprar una cerveza?" + return msg, por_favor + +print hablar() # ¿Me puedes comprar una cerveza? +print hablar(por_favor=True) # ¿Me puedes comprar una cerveza? ¡Por favor! Soy pobre :( +``` + +## ¿Listo para más? + +### Gratis y en línea + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### Encuadernados + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown deleted file mode 100644 index 0ae410de..00000000 --- a/fr-fr/python-fr.html.markdown +++ /dev/null @@ -1,488 +0,0 @@ ---- -language: python -filename: learnpython-fr.py -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["Sylvain Zyssman", "https://github.com/sylzys"] - - ["Nami-Doc", "https://github.com/Nami-Doc"] -lang: fr-fr ---- - -Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des langages de programmation les plus populaires. -Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiquement du pseudo-code exécutable. - -Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service] - -N.B. : Cet article s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x. Python 2.7 est en fin de vie et ne sera plus maintenu à partir de 2020, il est donc recommandé d'apprendre Python avec Python 3. Pour Python 3.x, il existe un autre [tutoriel pour Python 3](http://learnxinyminutes.com/docs/fr-fr/python3-fr/). - -```python -# Une ligne simple de commentaire commence par un dièse -""" Les lignes de commentaires multipes peuvent être écrites - en utilisant 3 guillemets ("), et sont souvent utilisées - pour les commentaires -""" - -#################################################### -## 1. Types Primaires et Opérateurs -#################################################### - -# Les nombres -3 #=> 3 - -# Les calculs produisent les résultats mathématiques escomptés -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 - -# La division est un peu spéciale. C'est une division d'entiers, et Python arrondi le résultat par défaut automatiquement. -5 / 2 #=> 2 - -# Pour corriger ce problème, on utilise les float. -2.0 # Voici un float -11.0 / 4.0 #=> 2.75 ahhh... beaucoup mieux - -# Forcer la priorité avec les parenthèses -(1 + 3) * 2 #=> 8 - -# Les valeurs booléenes sont de type primitif -True -False - -# Pour la négation, on utilise "not" -not True #=> False -not False #=> True - -# Pour l'égalité, == -1 == 1 #=> True -2 == 1 #=> False - -# L'inégalité est symbolisée par != -1 != 1 #=> False -2 != 1 #=> True - -# D'autres comparateurs -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True - -# On peut enchaîner les comparateurs ! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False - -# Les chaînes de caractères sont créées avec " ou ' -"C'est une chaîne." -'C\'est aussi une chaîne.' - -# On peut aussi les "additioner" ! -"Hello " + "world!" #=> "Hello world!" - -# Une chaîne peut être traitée comme une liste de caractères -"C'est une chaîne"[0] #=> 'C' - -# % peut être utilisé pour formatter des chaîne, comme ceci: -"%s can be %s" % ("strings", "interpolated") - -# Une autre manière de formatter les chaînes de caractères est d'utiliser la méthode 'format' -# C'est la méthode à privilégier -"{0} peut être {1}".format("La chaîne", "formattée") -# On peut utiliser des mot-clés au lieu des chiffres. -"{name} veut manger des {food}".format(name="Bob", food="lasagnes") - -# None est un objet -None #=> None - -# Ne pas utiliser le symbole d'inégalité "==" pour comparer des objet à None -# Il faut utiliser "is" -"etc" is None #=> False -None is None #=> True - -# L'opérateur 'is' teste l'identité de l'objet. -# Ce n'est pas très utilisé avec les types primitifs, mais cela peut être très utile -# lorsque l'on utilise des objets. - -# None, 0, et les chaînes de caractères vides valent False. -# Toutes les autres valeurs valent True -0 == False #=> True -"" == False #=> True - - -#################################################### -## 2. Variables et Collections -#################################################### - -# Afficher du texte, c'est facile -print "Je suis Python. Enchanté!" - - -# Il n'y a pas besoin de déclarer les variables avant de les assigner. -some_var = 5 # La convention veut que l'on utilise des minuscules_avec_underscores -some_var #=> 5 - -# Accéder à une variable non assignée lève une exception -# Voyez les structures de contrôle pour en apprendre plus sur la gestion des exceptions. -some_other_var # Lève une exception - -# 'if' peut être utilisé comme expression -"yahoo!" if 3 > 2 else 2 #=> "yahoo!" - -# Listes -li = [] -# On peut remplir liste dès l'instanciation -other_li = [4, 5, 6] - -# On ajoute des éléments avec 'append' -li.append(1) #li contient [1] -li.append(2) #li contient [1, 2] -li.append(4) #li contient [1, 2, 4] -li.append(3) #li contient [1, 2, 4, 3] - -# Et on les supprime avec 'pop' -li.pop() #=> 3 et li contient [1, 2, 4] -# Remettons-le dans la liste -li.append(3) # li contient [1, 2, 4, 3] de nouveau. - -# On accède aux éléments d'une liste comme à ceux un tableau. -li[0] #=> 1 -# Le dernier élément -li[-1] #=> 3 - -# Accèder aux indices hors limite lève une exception -li[4] # Lève un 'IndexError' - -# On peut accèder à des rangs de valeurs avec la syntaxe "slice" -# (C'est un rang de type 'fermé/ouvert' pour les plus matheux) -li[1:3] #=> [2, 4] -# Sans spécifier de fin de rang, on "saute" le début de la liste -li[2:] #=> [4, 3] -# Sans spécifier de début de rang, on "saute" la fin de la liste -li[:3] #=> [1, 2, 4] - -# Retirer un élément spécifique dee la liste avec "del" -del li[2] # li contient [1, 2, 3] - -# On peut additionner des listes entre elles -li + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li et other_li existent toujours à part entière - -# Concaténer des listes avec "extend()" -li.extend(other_li) # li vaut maintenant [1, 2, 3, 4, 5, 6] - -# Vérifier l'existence d'un élément dans une liste avec "in" -1 in li #=> True - -# Récupérer la longueur avec "len()" -len(li) #=> 6 - - -# Les "tuples" sont comme des listes, mais sont immuables. -tup = (1, 2, 3) -tup[0] #=> 1 -tup[0] = 3 # Lève un 'TypeError' - -# Mais vous pouvez faire tout ceci sur les tuples: -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True - -# Vous pouvez "dé-packager" les tuples (ou les listes) dans des variables -a, b, c = (1, 2, 3) # a vaut maintenant 1, b vaut maintenant 2 and c vaut maintenant 3 -# Sans parenthèses, un tuple est créé par défaut -d, e, f = 4, 5, 6 -# Voyez maintenant comme il est facile d'inverser 2 valeurs -e, d = d, e # d is now 5 and e is now 4 - - -# Dictionnaires -empty_dict = {} -# Un dictionnaire pré-rempli -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Trouver des valeurs avec [] -filled_dict["one"] #=> 1 - -# Récupérer toutes les clés sous forme de liste avec "keys()" -filled_dict.keys() #=> ["three", "two", "one"] -# Note - l'ordre des clés du dictionnaire n'est pas garanti. -# Vos résultats peuvent différer de ceux ci-dessus. - -# Récupérer toutes les valeurs sous forme de liste avec "values()" -filled_dict.values() #=> [3, 2, 1] -# Note - Même remarque qu'au-dessus concernant l'ordre des valeurs. - -# Vérifier l'existence d'une clé dans le dictionnaire avec "in" -"one" in filled_dict #=> True -1 in filled_dict #=> False - -# Chercher une clé non existante lève une 'KeyError' -filled_dict["four"] # KeyError - -# Utiliser la méthode "get()" pour éviter 'KeyError' -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None -# La méthode get() prend un argument par défaut quand la valeur est inexistante -filled_dict.get("one", 4) #=> 1 -filled_dict.get("four", 4) #=> 4 - -# La méthode "setdefault()" permet d'ajouter de manière sécuris une paire clé-valeur dans le dictionnnaire -filled_dict.setdefault("five", 5) #filled_dict["five"] vaut 5 -filled_dict.setdefault("five", 6) #filled_dict["five"] is toujours 5 - - -# Les sets stockent ... des sets -empty_set = set() -# On initialise un "set()" avec tout un tas de valeurs -some_set = set([1,2,2,3,4]) # some_set vaut maintenant set([1, 2, 3, 4]) - -# Depuis Python 2.7, {} peut être utilisé pour déclarer un 'set' -filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} - -# Ajouter plus d'éléments au set -filled_set.add(5) # filled_set contient maintenant {1, 2, 3, 4, 5} - -# Intersection de sets avec & -other_set = {3, 4, 5, 6} -filled_set & other_set #=> {3, 4, 5} - -# Union de sets avec | -filled_set | other_set #=> {1, 2, 3, 4, 5, 6} - -# Différence de sets avec - -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# Vérifier l'existence d'une valeur dans un set avec "in" -2 in filled_set #=> True -10 in filled_set #=> False - - -#################################################### -## 3. Structure de contrôle -#################################################### - -# Initialisons une variable -some_var = 5 - -# Voici une condition 'if'. L'indentation est significative en Python ! -# Affiche "some_var est inférieur à 10" -if some_var > 10: - print "some_var est supérieur à 10." -elif some_var < 10: # La clause elif est optionnelle - print "some_var iinférieur à 10." -else: # La clause else également - print "some_var vaut 10." - - -""" -Les boucles "for" permettent d'itérer sur les listes -Affiche: - chien : mammifère - chat : mammifère - souris : mammifère -""" -for animal in ["chien", "chat", "souris"]: - # On peut utiliser % pour l'interpolation des chaînes formattées - print "%s : mammifère" % animal - -""" -"range(number)" retourne une liste de nombres -de 0 au nombre donné -Affiche: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -Les boucles "while" boucle jusqu'à ce que leur condition ne soit plus vraie -Affiche: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # Raccourci pour x = x + 1 - -# Gérer les exceptions avec un bloc try/except - -# Fonctionne pour Python 2.6 et ultérieur: -try: - # Utiliser "raise" pour lever une exception - raise IndexError("This is an index error") -except IndexError as e: - pass # Pass ne prend pas d'arguments. Généralement, on gère l'erreur ici. - - -#################################################### -## 4. Fonctions -#################################################### - -# Utiliser "def" pour créer une nouvelle fonction -def add(x, y): - print "x vaut %s et y vaur %s" % (x, y) - return x + y # Renvoi de valeur avec 'return' - -# Appeller une fonction avec des paramètres -add(5, 6) #=> Affichet "x is 5 et y vaut 6" et renvoie 11 - -# Une autre manière d'appeller une fonction, avec les arguments -add(y=6, x=5) # Les arguments peuvent venir dans n'importe quel ordre. - -# On peut définir une foncion qui prend un nombre variable de paramètres -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# On peut également définir une fonction qui prend un nombre -# variable d'arguments -def keyword_args(**kwargs): - return kwargs - -# Appelons-là et voyons ce qu'il se passe -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} - -# On peut faire les deux à la fois si on le souhaite -def all_the_args(*args, **kwargs): - print args - print kwargs -""" -all_the_args(1, 2, a=3, b=4) affiche: - (1, 2) - {"a": 3, "b": 4} -""" - -# En appellant les fonctions, on peut faire l'inverse des paramètres / arguments ! -# Utiliser * pour développer les paramètres, et ** pour développer les arguments -params = (1, 2, 3, 4) -args = {"a": 3, "b": 4} -all_the_args(*args) # equivaut à foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivaut à foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivaut à foo(1, 2, 3, 4, a=3, b=4) - -# Python a des fonctions de première classe -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) #=> 13 - -# Mais également des fonctions anonymes -(lambda x: x > 2)(3) #=> True - -# On trouve aussi des fonctions intégrées plus évoluées -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# On peut utiliser la syntaxe des liste pour construire les "maps" et les "filters" -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] - -#################################################### -## 5. Classes -#################################################### - -# Une classe est un objet -class Human(object): - - # Un attribut de classe. Il est partagé par toutes les instances de cette classe. - species = "H. sapiens" - - # Initialiseur basique - def __init__(self, name): - # Assigne le paramètre à l'attribut de l'instance de classe. - self.name = name - - # Une méthode de l'instance. Toutes les méthodes prennent "self" comme 1er paramètre. - def say(self, msg): - return "%s: %s" % (self.name, msg) - - # Une méthode de classe est partagée par toutes les instances. - # On les appelle avec le nom de la classe en premier paramètre - @classmethod - def get_species(cls): - return cls.species - - # Une méthode statique est appellée sans référence à une classe ou à une instance - @staticmethod - def grunt(): - return "*grunt*" - - -# Instancier une classe -i = Human(name="Ian") -print i.say("hi") # Affiche "Ian: hi" - -j = Human("Joel") -print j.say("hello") #Affiche "Joel: hello" - -# Appeller notre méthode de classe -i.get_species() #=> "H. sapiens" - -# Changer les attributs partagés -Human.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" - -# Appeller la méthode statique -Human.grunt() #=> "*grunt*" - - -#################################################### -## 6. Modules -#################################################### - -# On peut importer des modules -import math -print math.sqrt(16) #=> 4.0 - -# Et récupérer des fonctions spécifiques d'un module -from math import ceil, floor -print ceil(3.7) #=> 4.0 -print floor(3.7) #=> 3.0 - -# Récuperer toutes les fonctions d'un module -# Attention, ce n'est pas recommandé. -from math import * - -# On peut raccourcir le nom d'un module -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Les modules Python sont juste des fichiers Python ordinaires. -# On peut écrire ses propres modules et les importer. -# Le nom du module doit être le même que le nom du fichier. - -# On peut trouver quelle fonction et attributs déterminent un module -import math -dir(math) - - -``` - -## Prêt à aller plus loin? - -### En ligne gratuitement - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2.6/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) - -### Format papier - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/fr-fr/pythonlegacy-fr.html.markdown b/fr-fr/pythonlegacy-fr.html.markdown new file mode 100644 index 00000000..0ae410de --- /dev/null +++ b/fr-fr/pythonlegacy-fr.html.markdown @@ -0,0 +1,488 @@ +--- +language: python +filename: learnpython-fr.py +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Sylvain Zyssman", "https://github.com/sylzys"] + - ["Nami-Doc", "https://github.com/Nami-Doc"] +lang: fr-fr +--- + +Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des langages de programmation les plus populaires. +Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiquement du pseudo-code exécutable. + +Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service] + +N.B. : Cet article s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x. Python 2.7 est en fin de vie et ne sera plus maintenu à partir de 2020, il est donc recommandé d'apprendre Python avec Python 3. Pour Python 3.x, il existe un autre [tutoriel pour Python 3](http://learnxinyminutes.com/docs/fr-fr/python3-fr/). + +```python +# Une ligne simple de commentaire commence par un dièse +""" Les lignes de commentaires multipes peuvent être écrites + en utilisant 3 guillemets ("), et sont souvent utilisées + pour les commentaires +""" + +#################################################### +## 1. Types Primaires et Opérateurs +#################################################### + +# Les nombres +3 #=> 3 + +# Les calculs produisent les résultats mathématiques escomptés +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# La division est un peu spéciale. C'est une division d'entiers, et Python arrondi le résultat par défaut automatiquement. +5 / 2 #=> 2 + +# Pour corriger ce problème, on utilise les float. +2.0 # Voici un float +11.0 / 4.0 #=> 2.75 ahhh... beaucoup mieux + +# Forcer la priorité avec les parenthèses +(1 + 3) * 2 #=> 8 + +# Les valeurs booléenes sont de type primitif +True +False + +# Pour la négation, on utilise "not" +not True #=> False +not False #=> True + +# Pour l'égalité, == +1 == 1 #=> True +2 == 1 #=> False + +# L'inégalité est symbolisée par != +1 != 1 #=> False +2 != 1 #=> True + +# D'autres comparateurs +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# On peut enchaîner les comparateurs ! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Les chaînes de caractères sont créées avec " ou ' +"C'est une chaîne." +'C\'est aussi une chaîne.' + +# On peut aussi les "additioner" ! +"Hello " + "world!" #=> "Hello world!" + +# Une chaîne peut être traitée comme une liste de caractères +"C'est une chaîne"[0] #=> 'C' + +# % peut être utilisé pour formatter des chaîne, comme ceci: +"%s can be %s" % ("strings", "interpolated") + +# Une autre manière de formatter les chaînes de caractères est d'utiliser la méthode 'format' +# C'est la méthode à privilégier +"{0} peut être {1}".format("La chaîne", "formattée") +# On peut utiliser des mot-clés au lieu des chiffres. +"{name} veut manger des {food}".format(name="Bob", food="lasagnes") + +# None est un objet +None #=> None + +# Ne pas utiliser le symbole d'inégalité "==" pour comparer des objet à None +# Il faut utiliser "is" +"etc" is None #=> False +None is None #=> True + +# L'opérateur 'is' teste l'identité de l'objet. +# Ce n'est pas très utilisé avec les types primitifs, mais cela peut être très utile +# lorsque l'on utilise des objets. + +# None, 0, et les chaînes de caractères vides valent False. +# Toutes les autres valeurs valent True +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Variables et Collections +#################################################### + +# Afficher du texte, c'est facile +print "Je suis Python. Enchanté!" + + +# Il n'y a pas besoin de déclarer les variables avant de les assigner. +some_var = 5 # La convention veut que l'on utilise des minuscules_avec_underscores +some_var #=> 5 + +# Accéder à une variable non assignée lève une exception +# Voyez les structures de contrôle pour en apprendre plus sur la gestion des exceptions. +some_other_var # Lève une exception + +# 'if' peut être utilisé comme expression +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Listes +li = [] +# On peut remplir liste dès l'instanciation +other_li = [4, 5, 6] + +# On ajoute des éléments avec 'append' +li.append(1) #li contient [1] +li.append(2) #li contient [1, 2] +li.append(4) #li contient [1, 2, 4] +li.append(3) #li contient [1, 2, 4, 3] + +# Et on les supprime avec 'pop' +li.pop() #=> 3 et li contient [1, 2, 4] +# Remettons-le dans la liste +li.append(3) # li contient [1, 2, 4, 3] de nouveau. + +# On accède aux éléments d'une liste comme à ceux un tableau. +li[0] #=> 1 +# Le dernier élément +li[-1] #=> 3 + +# Accèder aux indices hors limite lève une exception +li[4] # Lève un 'IndexError' + +# On peut accèder à des rangs de valeurs avec la syntaxe "slice" +# (C'est un rang de type 'fermé/ouvert' pour les plus matheux) +li[1:3] #=> [2, 4] +# Sans spécifier de fin de rang, on "saute" le début de la liste +li[2:] #=> [4, 3] +# Sans spécifier de début de rang, on "saute" la fin de la liste +li[:3] #=> [1, 2, 4] + +# Retirer un élément spécifique dee la liste avec "del" +del li[2] # li contient [1, 2, 3] + +# On peut additionner des listes entre elles +li + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li et other_li existent toujours à part entière + +# Concaténer des listes avec "extend()" +li.extend(other_li) # li vaut maintenant [1, 2, 3, 4, 5, 6] + +# Vérifier l'existence d'un élément dans une liste avec "in" +1 in li #=> True + +# Récupérer la longueur avec "len()" +len(li) #=> 6 + + +# Les "tuples" sont comme des listes, mais sont immuables. +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Lève un 'TypeError' + +# Mais vous pouvez faire tout ceci sur les tuples: +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Vous pouvez "dé-packager" les tuples (ou les listes) dans des variables +a, b, c = (1, 2, 3) # a vaut maintenant 1, b vaut maintenant 2 and c vaut maintenant 3 +# Sans parenthèses, un tuple est créé par défaut +d, e, f = 4, 5, 6 +# Voyez maintenant comme il est facile d'inverser 2 valeurs +e, d = d, e # d is now 5 and e is now 4 + + +# Dictionnaires +empty_dict = {} +# Un dictionnaire pré-rempli +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Trouver des valeurs avec [] +filled_dict["one"] #=> 1 + +# Récupérer toutes les clés sous forme de liste avec "keys()" +filled_dict.keys() #=> ["three", "two", "one"] +# Note - l'ordre des clés du dictionnaire n'est pas garanti. +# Vos résultats peuvent différer de ceux ci-dessus. + +# Récupérer toutes les valeurs sous forme de liste avec "values()" +filled_dict.values() #=> [3, 2, 1] +# Note - Même remarque qu'au-dessus concernant l'ordre des valeurs. + +# Vérifier l'existence d'une clé dans le dictionnaire avec "in" +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Chercher une clé non existante lève une 'KeyError' +filled_dict["four"] # KeyError + +# Utiliser la méthode "get()" pour éviter 'KeyError' +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# La méthode get() prend un argument par défaut quand la valeur est inexistante +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# La méthode "setdefault()" permet d'ajouter de manière sécuris une paire clé-valeur dans le dictionnnaire +filled_dict.setdefault("five", 5) #filled_dict["five"] vaut 5 +filled_dict.setdefault("five", 6) #filled_dict["five"] is toujours 5 + + +# Les sets stockent ... des sets +empty_set = set() +# On initialise un "set()" avec tout un tas de valeurs +some_set = set([1,2,2,3,4]) # some_set vaut maintenant set([1, 2, 3, 4]) + +# Depuis Python 2.7, {} peut être utilisé pour déclarer un 'set' +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Ajouter plus d'éléments au set +filled_set.add(5) # filled_set contient maintenant {1, 2, 3, 4, 5} + +# Intersection de sets avec & +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Union de sets avec | +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Différence de sets avec - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Vérifier l'existence d'une valeur dans un set avec "in" +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Structure de contrôle +#################################################### + +# Initialisons une variable +some_var = 5 + +# Voici une condition 'if'. L'indentation est significative en Python ! +# Affiche "some_var est inférieur à 10" +if some_var > 10: + print "some_var est supérieur à 10." +elif some_var < 10: # La clause elif est optionnelle + print "some_var iinférieur à 10." +else: # La clause else également + print "some_var vaut 10." + + +""" +Les boucles "for" permettent d'itérer sur les listes +Affiche: + chien : mammifère + chat : mammifère + souris : mammifère +""" +for animal in ["chien", "chat", "souris"]: + # On peut utiliser % pour l'interpolation des chaînes formattées + print "%s : mammifère" % animal + +""" +"range(number)" retourne une liste de nombres +de 0 au nombre donné +Affiche: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +Les boucles "while" boucle jusqu'à ce que leur condition ne soit plus vraie +Affiche: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Raccourci pour x = x + 1 + +# Gérer les exceptions avec un bloc try/except + +# Fonctionne pour Python 2.6 et ultérieur: +try: + # Utiliser "raise" pour lever une exception + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass ne prend pas d'arguments. Généralement, on gère l'erreur ici. + + +#################################################### +## 4. Fonctions +#################################################### + +# Utiliser "def" pour créer une nouvelle fonction +def add(x, y): + print "x vaut %s et y vaur %s" % (x, y) + return x + y # Renvoi de valeur avec 'return' + +# Appeller une fonction avec des paramètres +add(5, 6) #=> Affichet "x is 5 et y vaut 6" et renvoie 11 + +# Une autre manière d'appeller une fonction, avec les arguments +add(y=6, x=5) # Les arguments peuvent venir dans n'importe quel ordre. + +# On peut définir une foncion qui prend un nombre variable de paramètres +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# On peut également définir une fonction qui prend un nombre +# variable d'arguments +def keyword_args(**kwargs): + return kwargs + +# Appelons-là et voyons ce qu'il se passe +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# On peut faire les deux à la fois si on le souhaite +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) affiche: + (1, 2) + {"a": 3, "b": 4} +""" + +# En appellant les fonctions, on peut faire l'inverse des paramètres / arguments ! +# Utiliser * pour développer les paramètres, et ** pour développer les arguments +params = (1, 2, 3, 4) +args = {"a": 3, "b": 4} +all_the_args(*args) # equivaut à foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivaut à foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivaut à foo(1, 2, 3, 4, a=3, b=4) + +# Python a des fonctions de première classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Mais également des fonctions anonymes +(lambda x: x > 2)(3) #=> True + +# On trouve aussi des fonctions intégrées plus évoluées +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# On peut utiliser la syntaxe des liste pour construire les "maps" et les "filters" +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#################################################### +## 5. Classes +#################################################### + +# Une classe est un objet +class Human(object): + + # Un attribut de classe. Il est partagé par toutes les instances de cette classe. + species = "H. sapiens" + + # Initialiseur basique + def __init__(self, name): + # Assigne le paramètre à l'attribut de l'instance de classe. + self.name = name + + # Une méthode de l'instance. Toutes les méthodes prennent "self" comme 1er paramètre. + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Une méthode de classe est partagée par toutes les instances. + # On les appelle avec le nom de la classe en premier paramètre + @classmethod + def get_species(cls): + return cls.species + + # Une méthode statique est appellée sans référence à une classe ou à une instance + @staticmethod + def grunt(): + return "*grunt*" + + +# Instancier une classe +i = Human(name="Ian") +print i.say("hi") # Affiche "Ian: hi" + +j = Human("Joel") +print j.say("hello") #Affiche "Joel: hello" + +# Appeller notre méthode de classe +i.get_species() #=> "H. sapiens" + +# Changer les attributs partagés +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Appeller la méthode statique +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Modules +#################################################### + +# On peut importer des modules +import math +print math.sqrt(16) #=> 4.0 + +# Et récupérer des fonctions spécifiques d'un module +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Récuperer toutes les fonctions d'un module +# Attention, ce n'est pas recommandé. +from math import * + +# On peut raccourcir le nom d'un module +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Les modules Python sont juste des fichiers Python ordinaires. +# On peut écrire ses propres modules et les importer. +# Le nom du module doit être le même que le nom du fichier. + +# On peut trouver quelle fonction et attributs déterminent un module +import math +dir(math) + + +``` + +## Prêt à aller plus loin? + +### En ligne gratuitement + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### Format papier + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/hu-hu/python-hu.html.markdown b/hu-hu/python-hu.html.markdown deleted file mode 100644 index 01f1c414..00000000 --- a/hu-hu/python-hu.html.markdown +++ /dev/null @@ -1,816 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] - - ["Amin Bandali", "https://aminb.org"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["evuez", "http://github.com/evuez"] - - ["asyne", "https://github.com/justblah"] - - ["habi", "http://github.com/habi"] -translators: - - ["Tamás Diószegi", "https://github.com/ditam"] -filename: learnpython-hu.py -lang: hu-hu ---- - -A Python nyelvet Guido Van Rossum alkotta meg a 90-es évek elején. Manapság az -egyik legnépszerűbb programozási nyelv. Én a tiszta szintaxisa miatt szerettem -bele. Tulajdonképpen futtatható pszeudokód. - -Szívesen fogadok visszajelzéseket! Elérsz itt: [@louiedinh](http://twitter.com/louiedinh) -vagy pedig a louiedinh [kukac] [google email szolgáltatása] címen. - -Figyelem: ez a leírás a Python 2.7 verziójára vonatkozok, illetve -általánosságban a 2.x verziókra. A Python 2.7 azonban már csak 2020-ig lesz -támogatva, ezért kezdőknek ajánlott, hogy a Python 3-mal kezdjék az -ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python3/) -ajánlott. - -Lehetséges olyan Python kódot írni, ami egyszerre kompatibilis a 2.7 és a 3.x -verziókkal is, a Python [`__future__` imports](https://docs.python.org/2/library/__future__.html) használatával. -A `__future__` import használata esetén Python 3-ban írhatod a kódot, ami -Python 2 alatt is futni fog, így ismét a fenti Python 3 bemutató ajánlott. - -```python - -# Az egysoros kommentek kettőskereszttel kezdődnek - -""" Többsoros stringeket három darab " közé - fogva lehet írni, ezeket gyakran használják - több soros kommentként. -""" - -#################################################### -# 1. Egyszerű adattípusok és operátorok -#################################################### - -# Használhatsz számokat -3 # => 3 - -# Az alapműveletek meglepetésektől mentesek -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7 - -# Az osztás kicsit trükkös. Egész osztást végez, és a hányados alsó egész része -# lesz az eredmény -5 / 2 # => 2 - -# Az osztás kijavításához a (lebegőpontos) float típust kell használnunk -2.0 # Ez egy float -11.0 / 4.0 # => 2.75 áh... máris jobb - -# Az egész osztás a negatív számok esetén is az alsó egész részt eredményezi -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # floatok esetén is --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Ha importáljuk a division modult (ld. 6. Modulok rész), -# akkor a '/' jellel pontos osztást tudunk végezni. -from __future__ import division - -11 / 4 # => 2.75 ...sima osztás -11 // 4 # => 2 ...egész osztás - -# Modulo művelet -7 % 3 # => 1 - -# Hatványozás (x az y. hatványra) -2 ** 4 # => 16 - -# A precedencia zárójelekkel befolyásolható -(1 + 3) * 2 # => 8 - -# Logikai operátorok -# Megjegyzés: az "and" és "or" csak kisbetűkkel helyes -True and False # => False -False or True # => True - -# A logikai operátorok egészeken is használhatóak -0 and 2 # => 0 --5 or 0 # => -5 -0 == False # => True -2 == True # => False -1 == True # => True - -# Negálni a not kulcsszóval lehet -not True # => False -not False # => True - -# Egyenlőségvizsgálat == -1 == 1 # => True -2 == 1 # => False - -# Egyenlőtlenség != -1 != 1 # => False -2 != 1 # => True - -# További összehasonlítások -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Az összehasonlítások láncolhatóak! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# Stringeket " vagy ' jelek közt lehet megadni -"Ez egy string." -'Ez egy másik string.' - -# A stringek összeadhatóak! -"Hello " + "world!" # => "Hello world!" -# '+' jel nélkül is összeadhatóak -"Hello " "world!" # => "Hello world!" - -# ... illetve szorozhatóak -"Hello" * 3 # => "HelloHelloHello" - -# Kezelhető karakterek indexelhető listájaként -"This is a string"[0] # => 'T' - -# A string hosszát a len függvény adja meg -len("This is a string") # => 16 - -# String formázáshoz a % jel használható -# A Python 3.1-gyel a % már deprecated jelölésű, és később eltávolításra fog -# kerülni, de azért jó tudni, hogyan működik. -x = 'alma' -y = 'citrom' -z = "A kosárban levő elemek: %s és %s" % (x, y) - -# A string formázás újabb módja a format metódus használatával történik. -# Jelenleg ez a javasolt megoldás. -"{} egy {} szöveg".format("Ez", "helytartó") -"A {0} pedig {1}".format("string", "formázható") -# Ha nem akarsz számolgatni, nevesíthetőek a pozíciók. -"{name} kedvence a {food}".format(name="Bob", food="lasagna") - -# None egy objektum -None # => None - -# A None-nal való összehasonlításhoz ne használd a "==" jelet, -# használd az "is" kulcsszót helyette -"etc" is None # => False -None is None # => True - -# Az 'is' operátor objektum egyezést vizsgál. -# Primitív típusok esetén ez nem túl hasznos, -# objektumok esetén azonban annál inkább. - -# Bármilyen objektum használható logikai kontextusban. -# A következő értékek hamis-ra értékelődnek ki (ún. "falsey" értékek): -# - None -# - bármelyik szám típus 0 értéke (pl. 0, 0L, 0.0, 0j) -# - üres sorozatok (pl. '', (), []) -# - üres konténerek (pl., {}, set()) -# - egyes felhasználó által definiált osztályok példányai bizonyos szabályok szerint, -# ld: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ -# -# Minden egyéb érték "truthy" (a bool() függvénynek átadva igazra értékelődnek ki) -bool(0) # => False -bool("") # => False - - -#################################################### -# 2. Változók és kollekciók -#################################################### - -# Létezik egy print utasítás -print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! - -# Így lehet egyszerűen bemenetet kérni a konzolról: -input_string_var = raw_input( - "Enter some data: ") # Visszatér a megadott stringgel -input_var = input("Enter some data: ") # Kiértékeli a bemenetet python kódként -# Vigyázat: a fentiek miatt az input() metódust körültekintően kell használni -# Megjegyzés: Python 3-ban az input() már deprecated, és a raw_input() lett input()-ra átnevezve - -# A változókat nem szükséges a használat előtt deklarálni -some_var = 5 # Konvenció szerint a névben kisbetu_es_alulvonas -some_var # => 5 - -# Érték nélküli változóra hivatkozás hibát dob. -# Lásd a Control Flow szekciót a kivételkezelésről. -some_other_var # name error hibát dob - -# az if használható kifejezésként -# a C nyelv '?:' ternáris operátorával egyenértékűen -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# A listákban sorozatok tárolhatóak -li = [] -# Már inicializáláskor megadhatóak elemek -other_li = [4, 5, 6] - -# A lista végére az append metódus rak új elemet -li.append(1) # li jelenleg [1] -li.append(2) # li jelenleg [1, 2] -li.append(4) # li jelenleg [1, 2, 4] -li.append(3) # li jelenleg [1, 2, 4, 3] -# A végéről a pop metódus távolít el elemet -li.pop() # => 3 és li jelenleg [1, 2, 4] -# Rakjuk vissza -li.append(3) # li jelenleg [1, 2, 4, 3], újra. - -# A lista elemeket tömb indexeléssel lehet hivatkozni -li[0] # => 1 -# A már inicializált értékekhez a = jellel lehet új értéket rendelni -li[0] = 42 -li[0] # => 42 -li[0] = 1 # csak visszaállítjuk az eredeti értékére -# Így is lehet az utolsó elemre hivatkozni -li[-1] # => 3 - -# A túlindexelés eredménye IndexError -li[4] # IndexError hibát dob - -# A lista részeit a slice szintaxissal lehet kimetszeni -# (Matekosoknak ez egy zárt/nyitott intervallum.) -li[1:3] # => [2, 4] -# A lista eleje kihagyható így -li[2:] # => [4, 3] -# Kihagyható a vége -li[:3] # => [1, 2, 4] -# Minden második elem kiválasztása -li[::2] # =>[1, 4] -# A lista egy másolata, fordított sorrendben -li[::-1] # => [3, 4, 2, 1] -# A fentiek kombinációival bonyolultabb slice parancsok is képezhetőek -# li[start:end:step] - -# Listaelemek a "del" paranccsal törölhetőek -del li[2] # li jelenleg [1, 2, 3] - -# A listák összeadhatóak -li + other_li # => [1, 2, 3, 4, 5, 6] -# Megjegyzés: az eredeti li és other_li értékei változatlanok - -# Összefőzhetőek (konkatenálhatóak) az "extend()" paranccsal -li.extend(other_li) # li jelenleg [1, 2, 3, 4, 5, 6] - -# Egy elem első előfordulásának eltávolítása -li.remove(2) # li jelenleg [1, 3, 4, 5, 6] -li.remove(2) # ValueError hibát dob, mivel a 2 nem szerepel már a listában - -# Elemek beszúrhatóak tetszőleges helyre -li.insert(1, 2) # li jelenleg [1, 2, 3, 4, 5, 6], ismét - -# Egy elem első előfordulási helye -li.index(2) # => 1 -li.index(7) # ValueError hibát dob, mivel a 7 nem szerepel a listában - -# Egy listában egy elem előfordulása az "in" szóval ellenőrizhető -1 in li # => True - -# A lista hossza a "len()" függvénnyel -len(li) # => 6 - -# Az N-esek ("tuple") hasonlítanak a listákhoz, de nem módosíthatóak -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # TypeError hibát dob - -# Az összes lista-műveletet ezeken is használható -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Az N-esek (és listák) kicsomagolhatóak külön változókba -a, b, c = (1, 2, 3) # az a így 1, a b 2 és a c pedig 3 -d, e, f = 4, 5, 6 # a zárójel elhagyható -# Ha elhagyod a zárójeleket, alapértelmezés szerint tuple képződik -g = 4, 5, 6 # => (4, 5, 6) -# Nézd, milyen egyszerű két értéket megcserélni -e, d = d, e # d most már 5 és az e 4 - -# A Dictionary típusokban hozzárendelések (kulcs-érték párok) tárolhatók -empty_dict = {} -# Ez pedig rögtön értékekkel van inicializálva -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Egy dictionary értékei [] jelek közt indexelhetőek -filled_dict["one"] # => 1 - -# A "keys()" metódus visszatér a kulcsok listájával -filled_dict.keys() # => ["three", "two", "one"] -# Megjegyzés: egy dictionary párjainak sorrendje nem garantált -# Lehet, hogy már a fenti példán is más sorrendben kaptad meg az elemeket. - -# Az értékek listája a "values()" metódussal kérhető le -filled_dict.values() # => [3, 2, 1] -# ld. a fenti megjegyzést az elemek sorrendjéről. - -# Az összes kulcs-érték pár megkapható N-esek listájaként az "items()" metódussal -filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] - -# Az "in" kulcssszóval ellenőrizhető, hogy egy kulcs szerepel-e a dictionary-ben -"one" in filled_dict # => True -1 in filled_dict # => False - -# Nem létező kulcs hivatkozása KeyError hibát dob -filled_dict["four"] # KeyError - -# A "get()" metódus használatával elkerülhető a KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# A metódusnak megadható egy alapértelmezett visszatérési érték is, hiányzó értékek esetén -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 -# Megjegyzés: ettől még filled_dict.get("four") => None -# (vagyis a get nem állítja be az alapértelmezett értéket a dictionary-ben) - -# A kulcsokhoz értékek a listákhoz hasonló szintaxissal rendelhetőek: -filled_dict["four"] = 4 # ez után filled_dict["four"] => 4 - -# A "setdefault()" metódus csak akkor állít be egy értéket, ha az adott kulcshoz még nem volt más megadva -filled_dict.setdefault("five", 5) # filled_dict["five"] beállítva 5-re -filled_dict.setdefault("five", 6) # filled_dict["five"] még mindig 5 - -# Egy halmaz ("set") olyan, mint egy lista, de egy elemet csak egyszer tárolhat -empty_set = set() -# Inicializáljuk ezt a halmazt néhány elemmel -some_set = set([1, 2, 2, 3, 4]) # some_set jelenleg set([1, 2, 3, 4]) - -# A sorrend itt sem garantált, még ha néha rendezettnek is tűnhet -another_set = set([4, 3, 2, 2, 1]) # another_set jelenleg set([1, 2, 3, 4]) - -# Python 2.7 óta már {} jelek közt is lehet halmazt definiálni -filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} - -# Új halmaz-elemek hozzáadása -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} - -# Halmaz metszés a & operátorral -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# Halmaz unió | operátorral -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Halmaz különbség - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Szimmetrikus differencia ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Vizsgáljuk, hogy a bal oldali halmaz magában foglalja-e a jobb oldalit -{1, 2} >= {1, 2, 3} # => False - -# Vizsgáljuk, hogy a bal oldali halmaz részhalmaza-e a jobb oldalinak -{1, 2} <= {1, 2, 3} # => True - -# Halmazbeli elemek jelenléte az in kulcssszóval vizsgálható -2 in filled_set # => True -10 in filled_set # => False - - -#################################################### -# 3. Control Flow -#################################################### - -# Legyen egy változónk -some_var = 5 - -# Ez egy if elágazás. A behúzás mértéke (az indentáció) jelentéssel bír a nyelvben! -# Ez a kód ezt fogja kiírni: "some_var kisebb 10-nél" -if some_var > 10: - print "some_var nagyobb, mint 10." -elif some_var < 10: # Az elif kifejezés nem kötelező az if szerkezetben. - print "some_var kisebb 10-nél" -else: # Ez sem kötelező. - print "some_var kereken 10." - -""" -For ciklusokkal végigiterálhatunk listákon -a kimenet: - A(z) kutya emlős - A(z) macska emlős - A(z) egér emlős -""" -for animal in ["kutya", "macska", "egér"]: - # A {0} kifejezéssel formázzuk a stringet, ld. korábban. - print "A(z) {0} emlős".format(animal) - -""" -"range(number)" visszatér számok listájával 0-től number-ig -a kimenet: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -"range(lower, upper)" visszatér a lower és upper közti számok listájával -a kimenet: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print i - -""" -A while ciklus a feltétel hamissá válásáig fut. -a kimenet: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # Rövidítés az x = x + 1 kifejezésre - -# A kivételek try/except blokkokkal kezelhetőek - -# Python 2.6-tól felfele: -try: - # A "raise" szóval lehet hibát dobni - raise IndexError("Ez egy index error") -except IndexError as e: - pass # A pass egy üres helytartó művelet. Itt hívnánk a hibakezelő kódunkat. -except (TypeError, NameError): - pass # Ha szükséges, egyszerre több hiba típus is kezelhető -else: # Az except blokk után opcionálisan megadható - print "Minden rendben!" # Csak akkor fut le, ha fentebb nem voltak hibák -finally: # Mindenképpen lefut - print "Itt felszabadíthatjuk az erőforrásokat például" - -# Az erőforrások felszabadításához try/finally helyett a with használható -with open("myfile.txt") as f: - for line in f: - print line - - -#################################################### -# 4. Függvények -#################################################### - -# A "def" szóval hozhatunk létre új függvényt -def add(x, y): - print "x is {0} and y is {1}".format(x, y) - return x + y # A return szóval tudunk értékeket visszaadni - - -# Így hívunk függvényt paraméterekkel -add(5, 6) # => a konzol kimenet "x is 5 and y is 6", a visszatérési érték 11 - -# Nevesített paraméterekkel (ún. "keyword arguments") is hívhatunk egy függvényt -add(y=6, x=5) # Ez esetben a sorrendjük nem számít - - -# Változó számú paramétert fogadó függvény így definiálható. -# A * használatával a paramétereket egy N-esként kapjuk meg. -def varargs(*args): - return args - - -varargs(1, 2, 3) # => (1, 2, 3) - - -# Változó számú nevesített paramétert fogadó függvény is megadható, -# a ** használatával a paramétereket egy dictionary-ként kapjuk meg -def keyword_args(**kwargs): - return kwargs - - -# Nézzük meg, mi történik -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# A két módszer egyszerre is használható -def all_the_args(*args, **kwargs): - print args - print kwargs - - -""" -all_the_args(1, 2, a=3, b=4) kimenete: - (1, 2) - {"a": 3, "b": 4} -""" - -# Függvények hívásakor a fenti args és kwargs módszerek inverze használható -# A * karakter kifejt egy listát külön paraméterekbe, a ** egy dictionary-t nevesített paraméterekbe. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # egyenértékű: foo(1, 2, 3, 4) -all_the_args(**kwargs) # egyenértékű: foo(a=3, b=4) -all_the_args(*args, **kwargs) # egyenértékű: foo(1, 2, 3, 4, a=3, b=4) - - -# A fenti arg és kwarg paraméterek továbbadhatóak egyéb függvényeknek, -# a * illetve ** operátorokkal kifejtve -def pass_all_the_args(*args, **kwargs): - all_the_args(*args, **kwargs) - print varargs(*args) - print keyword_args(**kwargs) - - -# Függvény scope -x = 5 - - -def set_x(num): - # A lokális x változó nem ugyanaz, mint a globális x - x = num # => 43 - print x # => 43 - - -def set_global_x(num): - global x - print x # => 5 - x = num # a globális x-et 6-ra állítjuk - print x # => 6 - - -set_x(43) -set_global_x(6) - - -# A pythonban a függvény elsőrendű (ún. "first class") típus -def create_adder(x): - def adder(y): - return x + y - - return adder - - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Névtelen függvények is definiálhatóak -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# Léteznek beépített magasabb rendű függvények -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] - -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# A listaképző kifejezések ("list comprehensions") jól használhatóak a map és filter függvényekkel -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# halmaz és dictionary képzők is léteznek -{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'} -{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -# 5. Osztályok -#################################################### - -# Az object osztály egy alosztályát képezzük -class Human(object): - # Osztály szintű mező: az osztály összes példányában azonos - species = "H. sapiens" - - # Ez a függvény meghívódik az osztály példányosításakor. - # Megjegyzés: a dupla aláhúzás a név előtt és után egy konvenció a python - # előre definiált, a nyelv által belsőleg használt, de a felhasználó által - # is látható objektumok és mezők neveire. - # Ne vezessünk be új, ilyen elnevezési sémát használó neveket! - def __init__(self, name): - # A paramétert értékül adjuk a példány name attribútumának - self.name = name - - # Inicializálunk egy mezőt - self.age = 0 - - # Példány metódus. Minden metódus első paramétere a "self", a példány maga - def say(self, msg): - return "{0}: {1}".format(self.name, msg) - - # Egy osztálymetódus az osztály összes példány közt meg van osztva. - # Hívásukkor az első paraméter mindig a hívó osztály. - @classmethod - def get_species(cls): - return cls.species - - # Egy statikus metódus osztály és példányreferencia nélkül hívódik - @staticmethod - def grunt(): - return "*grunt*" - - # Egy property jelölésű függvény olyan, mint egy getter. - # Használatával az age mező egy csak-olvasható attribútummá válik. - @property - def age(self): - return self._age - - # Így lehet settert megadni egy mezőhöz - @age.setter - def age(self, age): - self._age = age - - # Így lehet egy mező törlését engedélyezni - @age.deleter - def age(self): - del self._age - - -# Példányosítsuk az osztályt -i = Human(name="Ian") -print i.say("hi") # kimenet: "Ian: hi" - -j = Human("Joel") -print j.say("hello") # kimenet: "Joel: hello" - -# Hívjuk az osztály metódusunkat -i.get_species() # => "H. sapiens" - -# Változtassuk meg az osztály szintű attribútumot -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# Hívjuk meg a statikus metódust -Human.grunt() # => "*grunt*" - -# Adjunk új értéket a mezőnek -i.age = 42 - -# Kérjük le a mező értékét -i.age # => 42 - -# Töröljük a mezőt -del i.age -i.age # => AttributeError hibát dob - -#################################################### -# 6. Modulok -#################################################### - -# Modulokat így lehet importálni -import math - -print math.sqrt(16) # => 4.0 - -# Lehetséges csak bizonyos függvényeket importálni egy modulból -from math import ceil, floor - -print ceil(3.7) # => 4.0 -print floor(3.7) # => 3.0 - -# Egy modul összes függvénye is importálható -# Vigyázat: ez nem ajánlott. -from math import * - -# A modulok nevei lerövidíthetőek -import math as m - -math.sqrt(16) == m.sqrt(16) # => True -# Meggyőződhetünk róla, hogy a függvények valóban azonosak -from math import sqrt - -math.sqrt == m.sqrt == sqrt # => True - -# A Python modulok egyszerű fájlok. -# Írhatsz sajátot és importálhatod is. -# A modul neve azonos a tartalmazó fájl nevével. - -# Így lehet megtekinteni, milyen mezőket és függvényeket definiál egy modul. -import math - -dir(math) - - -# Ha van egy math.py nevű Python scripted a jelenleg futó scripttel azonos -# mappában, a math.py fájl lesz betöltve a beépített Python modul helyett. -# A lokális mappa prioritást élvez a beépített könyvtárak felett. - - -#################################################### -# 7. Haladóknak -#################################################### - -# Generátorok -# Egy generátor értékeket "generál" amikor kérik, a helyett, hogy előre eltárolná őket. - -# A következő metódus (ez még NEM egy generátor) megduplázza a kapott iterable elemeit, -# és eltárolja őket. Nagy méretű iterable esetén ez nagyon sok helyet foglalhat! -def double_numbers(iterable): - double_arr = [] - for i in iterable: - double_arr.append(i + i) - return double_arr - - -# A következő kód futtatásakor az összes szám kétszeresét kiszámítanánk, és visszaadnánk -# ezt a nagy listát a ciklus vezérléséhez. -for value in double_numbers(range(1000000)): # `test_non_generator` - print value - if value > 5: - break - - -# Használjunk inkább egy generátort, ami "legenerálja" a soron következő elemet, -# amikor azt kérik tőle -def double_numbers_generator(iterable): - for i in iterable: - yield i + i - - -# A lenti kód mindig csak a soron következő számot generálja a logikai vizsgálat előtt. -# Így amikor az érték eléri a > 5 határt, megszakítjuk a ciklust, és a lista számainak -# nagy részénél megspóroltuk a duplázás műveletet (ez sokkal gyorsabb így!). -for value in double_numbers_generator(xrange(1000000)): # `test_generator` - print value - if value > 5: - break - -# Feltűnt, hogy a `test_non_generator` esetén `range`, a `test_generator` esetén -# pedig `xrange` volt a segédfüggvény neve? Ahogy `double_numbers_generator` a -# generátor változata a `double_numbers` függvénynek, úgy az `xrange` a `range` -# generátor megfelelője, csak akkor generálja le a következő számot, amikor kérjük -# - esetünkben a ciklus következő iterációjakor - -# A lista képzéshez hasonlóan generátor képzőket is használhatunk -# ("generator comprehensions"). -values = (-x for x in [1, 2, 3, 4, 5]) -for x in values: - print(x) # kimenet: -1 -2 -3 -4 -5 - -# Egy generátor összes generált elemét listaként is elkérhetjük: -values = (-x for x in [1, 2, 3, 4, 5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - -# Dekorátorok -# A dekorátor egy magasabb rendű függvény, aminek bemenete és kimenete is egy függvény. -# A lenti egyszerű példában az add_apples dekorátor a dekorált get_fruits függvény -# kimenetébe beszúrja az 'Apple' elemet. -def add_apples(func): - def get_fruits(): - fruits = func() - fruits.append('Apple') - return fruits - return get_fruits - -@add_apples -def get_fruits(): - return ['Banana', 'Mango', 'Orange'] - -# A kimenet tartalmazza az 'Apple' elemet: -# Banana, Mango, Orange, Apple -print ', '.join(get_fruits()) - -# Ebben a példában a beg dekorátorral látjuk el a say függvényt. -# Beg meghívja say-t. Ha a say_please paraméter igaz, akkor -# megváltoztatja az eredmény mondatot. -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print say() # Can you buy me a beer? -print say(say_please=True) # Can you buy me a beer? Please! I am poor :( -``` - -## Még több érdekel? - -### Ingyenes online tartalmak - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [LearnPython](http://www.learnpython.org/) -* [Fullstack Python](https://www.fullstackpython.com/) - -### Könyvek - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/hu-hu/pythonlegacy-hu.html.markdown b/hu-hu/pythonlegacy-hu.html.markdown new file mode 100644 index 00000000..01f1c414 --- /dev/null +++ b/hu-hu/pythonlegacy-hu.html.markdown @@ -0,0 +1,816 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "https://aminb.org"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] + - ["asyne", "https://github.com/justblah"] + - ["habi", "http://github.com/habi"] +translators: + - ["Tamás Diószegi", "https://github.com/ditam"] +filename: learnpython-hu.py +lang: hu-hu +--- + +A Python nyelvet Guido Van Rossum alkotta meg a 90-es évek elején. Manapság az +egyik legnépszerűbb programozási nyelv. Én a tiszta szintaxisa miatt szerettem +bele. Tulajdonképpen futtatható pszeudokód. + +Szívesen fogadok visszajelzéseket! Elérsz itt: [@louiedinh](http://twitter.com/louiedinh) +vagy pedig a louiedinh [kukac] [google email szolgáltatása] címen. + +Figyelem: ez a leírás a Python 2.7 verziójára vonatkozok, illetve +általánosságban a 2.x verziókra. A Python 2.7 azonban már csak 2020-ig lesz +támogatva, ezért kezdőknek ajánlott, hogy a Python 3-mal kezdjék az +ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python3/) +ajánlott. + +Lehetséges olyan Python kódot írni, ami egyszerre kompatibilis a 2.7 és a 3.x +verziókkal is, a Python [`__future__` imports](https://docs.python.org/2/library/__future__.html) használatával. +A `__future__` import használata esetén Python 3-ban írhatod a kódot, ami +Python 2 alatt is futni fog, így ismét a fenti Python 3 bemutató ajánlott. + +```python + +# Az egysoros kommentek kettőskereszttel kezdődnek + +""" Többsoros stringeket három darab " közé + fogva lehet írni, ezeket gyakran használják + több soros kommentként. +""" + +#################################################### +# 1. Egyszerű adattípusok és operátorok +#################################################### + +# Használhatsz számokat +3 # => 3 + +# Az alapműveletek meglepetésektől mentesek +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# Az osztás kicsit trükkös. Egész osztást végez, és a hányados alsó egész része +# lesz az eredmény +5 / 2 # => 2 + +# Az osztás kijavításához a (lebegőpontos) float típust kell használnunk +2.0 # Ez egy float +11.0 / 4.0 # => 2.75 áh... máris jobb + +# Az egész osztás a negatív számok esetén is az alsó egész részt eredményezi +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # floatok esetén is +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Ha importáljuk a division modult (ld. 6. Modulok rész), +# akkor a '/' jellel pontos osztást tudunk végezni. +from __future__ import division + +11 / 4 # => 2.75 ...sima osztás +11 // 4 # => 2 ...egész osztás + +# Modulo művelet +7 % 3 # => 1 + +# Hatványozás (x az y. hatványra) +2 ** 4 # => 16 + +# A precedencia zárójelekkel befolyásolható +(1 + 3) * 2 # => 8 + +# Logikai operátorok +# Megjegyzés: az "and" és "or" csak kisbetűkkel helyes +True and False # => False +False or True # => True + +# A logikai operátorok egészeken is használhatóak +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Negálni a not kulcsszóval lehet +not True # => False +not False # => True + +# Egyenlőségvizsgálat == +1 == 1 # => True +2 == 1 # => False + +# Egyenlőtlenség != +1 != 1 # => False +2 != 1 # => True + +# További összehasonlítások +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Az összehasonlítások láncolhatóak! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Stringeket " vagy ' jelek közt lehet megadni +"Ez egy string." +'Ez egy másik string.' + +# A stringek összeadhatóak! +"Hello " + "world!" # => "Hello world!" +# '+' jel nélkül is összeadhatóak +"Hello " "world!" # => "Hello world!" + +# ... illetve szorozhatóak +"Hello" * 3 # => "HelloHelloHello" + +# Kezelhető karakterek indexelhető listájaként +"This is a string"[0] # => 'T' + +# A string hosszát a len függvény adja meg +len("This is a string") # => 16 + +# String formázáshoz a % jel használható +# A Python 3.1-gyel a % már deprecated jelölésű, és később eltávolításra fog +# kerülni, de azért jó tudni, hogyan működik. +x = 'alma' +y = 'citrom' +z = "A kosárban levő elemek: %s és %s" % (x, y) + +# A string formázás újabb módja a format metódus használatával történik. +# Jelenleg ez a javasolt megoldás. +"{} egy {} szöveg".format("Ez", "helytartó") +"A {0} pedig {1}".format("string", "formázható") +# Ha nem akarsz számolgatni, nevesíthetőek a pozíciók. +"{name} kedvence a {food}".format(name="Bob", food="lasagna") + +# None egy objektum +None # => None + +# A None-nal való összehasonlításhoz ne használd a "==" jelet, +# használd az "is" kulcsszót helyette +"etc" is None # => False +None is None # => True + +# Az 'is' operátor objektum egyezést vizsgál. +# Primitív típusok esetén ez nem túl hasznos, +# objektumok esetén azonban annál inkább. + +# Bármilyen objektum használható logikai kontextusban. +# A következő értékek hamis-ra értékelődnek ki (ún. "falsey" értékek): +# - None +# - bármelyik szám típus 0 értéke (pl. 0, 0L, 0.0, 0j) +# - üres sorozatok (pl. '', (), []) +# - üres konténerek (pl., {}, set()) +# - egyes felhasználó által definiált osztályok példányai bizonyos szabályok szerint, +# ld: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# Minden egyéb érték "truthy" (a bool() függvénynek átadva igazra értékelődnek ki) +bool(0) # => False +bool("") # => False + + +#################################################### +# 2. Változók és kollekciók +#################################################### + +# Létezik egy print utasítás +print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! + +# Így lehet egyszerűen bemenetet kérni a konzolról: +input_string_var = raw_input( + "Enter some data: ") # Visszatér a megadott stringgel +input_var = input("Enter some data: ") # Kiértékeli a bemenetet python kódként +# Vigyázat: a fentiek miatt az input() metódust körültekintően kell használni +# Megjegyzés: Python 3-ban az input() már deprecated, és a raw_input() lett input()-ra átnevezve + +# A változókat nem szükséges a használat előtt deklarálni +some_var = 5 # Konvenció szerint a névben kisbetu_es_alulvonas +some_var # => 5 + +# Érték nélküli változóra hivatkozás hibát dob. +# Lásd a Control Flow szekciót a kivételkezelésről. +some_other_var # name error hibát dob + +# az if használható kifejezésként +# a C nyelv '?:' ternáris operátorával egyenértékűen +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# A listákban sorozatok tárolhatóak +li = [] +# Már inicializáláskor megadhatóak elemek +other_li = [4, 5, 6] + +# A lista végére az append metódus rak új elemet +li.append(1) # li jelenleg [1] +li.append(2) # li jelenleg [1, 2] +li.append(4) # li jelenleg [1, 2, 4] +li.append(3) # li jelenleg [1, 2, 4, 3] +# A végéről a pop metódus távolít el elemet +li.pop() # => 3 és li jelenleg [1, 2, 4] +# Rakjuk vissza +li.append(3) # li jelenleg [1, 2, 4, 3], újra. + +# A lista elemeket tömb indexeléssel lehet hivatkozni +li[0] # => 1 +# A már inicializált értékekhez a = jellel lehet új értéket rendelni +li[0] = 42 +li[0] # => 42 +li[0] = 1 # csak visszaállítjuk az eredeti értékére +# Így is lehet az utolsó elemre hivatkozni +li[-1] # => 3 + +# A túlindexelés eredménye IndexError +li[4] # IndexError hibát dob + +# A lista részeit a slice szintaxissal lehet kimetszeni +# (Matekosoknak ez egy zárt/nyitott intervallum.) +li[1:3] # => [2, 4] +# A lista eleje kihagyható így +li[2:] # => [4, 3] +# Kihagyható a vége +li[:3] # => [1, 2, 4] +# Minden második elem kiválasztása +li[::2] # =>[1, 4] +# A lista egy másolata, fordított sorrendben +li[::-1] # => [3, 4, 2, 1] +# A fentiek kombinációival bonyolultabb slice parancsok is képezhetőek +# li[start:end:step] + +# Listaelemek a "del" paranccsal törölhetőek +del li[2] # li jelenleg [1, 2, 3] + +# A listák összeadhatóak +li + other_li # => [1, 2, 3, 4, 5, 6] +# Megjegyzés: az eredeti li és other_li értékei változatlanok + +# Összefőzhetőek (konkatenálhatóak) az "extend()" paranccsal +li.extend(other_li) # li jelenleg [1, 2, 3, 4, 5, 6] + +# Egy elem első előfordulásának eltávolítása +li.remove(2) # li jelenleg [1, 3, 4, 5, 6] +li.remove(2) # ValueError hibát dob, mivel a 2 nem szerepel már a listában + +# Elemek beszúrhatóak tetszőleges helyre +li.insert(1, 2) # li jelenleg [1, 2, 3, 4, 5, 6], ismét + +# Egy elem első előfordulási helye +li.index(2) # => 1 +li.index(7) # ValueError hibát dob, mivel a 7 nem szerepel a listában + +# Egy listában egy elem előfordulása az "in" szóval ellenőrizhető +1 in li # => True + +# A lista hossza a "len()" függvénnyel +len(li) # => 6 + +# Az N-esek ("tuple") hasonlítanak a listákhoz, de nem módosíthatóak +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # TypeError hibát dob + +# Az összes lista-műveletet ezeken is használható +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Az N-esek (és listák) kicsomagolhatóak külön változókba +a, b, c = (1, 2, 3) # az a így 1, a b 2 és a c pedig 3 +d, e, f = 4, 5, 6 # a zárójel elhagyható +# Ha elhagyod a zárójeleket, alapértelmezés szerint tuple képződik +g = 4, 5, 6 # => (4, 5, 6) +# Nézd, milyen egyszerű két értéket megcserélni +e, d = d, e # d most már 5 és az e 4 + +# A Dictionary típusokban hozzárendelések (kulcs-érték párok) tárolhatók +empty_dict = {} +# Ez pedig rögtön értékekkel van inicializálva +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Egy dictionary értékei [] jelek közt indexelhetőek +filled_dict["one"] # => 1 + +# A "keys()" metódus visszatér a kulcsok listájával +filled_dict.keys() # => ["three", "two", "one"] +# Megjegyzés: egy dictionary párjainak sorrendje nem garantált +# Lehet, hogy már a fenti példán is más sorrendben kaptad meg az elemeket. + +# Az értékek listája a "values()" metódussal kérhető le +filled_dict.values() # => [3, 2, 1] +# ld. a fenti megjegyzést az elemek sorrendjéről. + +# Az összes kulcs-érték pár megkapható N-esek listájaként az "items()" metódussal +filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] + +# Az "in" kulcssszóval ellenőrizhető, hogy egy kulcs szerepel-e a dictionary-ben +"one" in filled_dict # => True +1 in filled_dict # => False + +# Nem létező kulcs hivatkozása KeyError hibát dob +filled_dict["four"] # KeyError + +# A "get()" metódus használatával elkerülhető a KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# A metódusnak megadható egy alapértelmezett visszatérési érték is, hiányzó értékek esetén +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 +# Megjegyzés: ettől még filled_dict.get("four") => None +# (vagyis a get nem állítja be az alapértelmezett értéket a dictionary-ben) + +# A kulcsokhoz értékek a listákhoz hasonló szintaxissal rendelhetőek: +filled_dict["four"] = 4 # ez után filled_dict["four"] => 4 + +# A "setdefault()" metódus csak akkor állít be egy értéket, ha az adott kulcshoz még nem volt más megadva +filled_dict.setdefault("five", 5) # filled_dict["five"] beállítva 5-re +filled_dict.setdefault("five", 6) # filled_dict["five"] még mindig 5 + +# Egy halmaz ("set") olyan, mint egy lista, de egy elemet csak egyszer tárolhat +empty_set = set() +# Inicializáljuk ezt a halmazt néhány elemmel +some_set = set([1, 2, 2, 3, 4]) # some_set jelenleg set([1, 2, 3, 4]) + +# A sorrend itt sem garantált, még ha néha rendezettnek is tűnhet +another_set = set([4, 3, 2, 2, 1]) # another_set jelenleg set([1, 2, 3, 4]) + +# Python 2.7 óta már {} jelek közt is lehet halmazt definiálni +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Új halmaz-elemek hozzáadása +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Halmaz metszés a & operátorral +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Halmaz unió | operátorral +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Halmaz különbség - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Szimmetrikus differencia ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Vizsgáljuk, hogy a bal oldali halmaz magában foglalja-e a jobb oldalit +{1, 2} >= {1, 2, 3} # => False + +# Vizsgáljuk, hogy a bal oldali halmaz részhalmaza-e a jobb oldalinak +{1, 2} <= {1, 2, 3} # => True + +# Halmazbeli elemek jelenléte az in kulcssszóval vizsgálható +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +# 3. Control Flow +#################################################### + +# Legyen egy változónk +some_var = 5 + +# Ez egy if elágazás. A behúzás mértéke (az indentáció) jelentéssel bír a nyelvben! +# Ez a kód ezt fogja kiírni: "some_var kisebb 10-nél" +if some_var > 10: + print "some_var nagyobb, mint 10." +elif some_var < 10: # Az elif kifejezés nem kötelező az if szerkezetben. + print "some_var kisebb 10-nél" +else: # Ez sem kötelező. + print "some_var kereken 10." + +""" +For ciklusokkal végigiterálhatunk listákon +a kimenet: + A(z) kutya emlős + A(z) macska emlős + A(z) egér emlős +""" +for animal in ["kutya", "macska", "egér"]: + # A {0} kifejezéssel formázzuk a stringet, ld. korábban. + print "A(z) {0} emlős".format(animal) + +""" +"range(number)" visszatér számok listájával 0-től number-ig +a kimenet: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(lower, upper)" visszatér a lower és upper közti számok listájával +a kimenet: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +A while ciklus a feltétel hamissá válásáig fut. +a kimenet: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Rövidítés az x = x + 1 kifejezésre + +# A kivételek try/except blokkokkal kezelhetőek + +# Python 2.6-tól felfele: +try: + # A "raise" szóval lehet hibát dobni + raise IndexError("Ez egy index error") +except IndexError as e: + pass # A pass egy üres helytartó művelet. Itt hívnánk a hibakezelő kódunkat. +except (TypeError, NameError): + pass # Ha szükséges, egyszerre több hiba típus is kezelhető +else: # Az except blokk után opcionálisan megadható + print "Minden rendben!" # Csak akkor fut le, ha fentebb nem voltak hibák +finally: # Mindenképpen lefut + print "Itt felszabadíthatjuk az erőforrásokat például" + +# Az erőforrások felszabadításához try/finally helyett a with használható +with open("myfile.txt") as f: + for line in f: + print line + + +#################################################### +# 4. Függvények +#################################################### + +# A "def" szóval hozhatunk létre új függvényt +def add(x, y): + print "x is {0} and y is {1}".format(x, y) + return x + y # A return szóval tudunk értékeket visszaadni + + +# Így hívunk függvényt paraméterekkel +add(5, 6) # => a konzol kimenet "x is 5 and y is 6", a visszatérési érték 11 + +# Nevesített paraméterekkel (ún. "keyword arguments") is hívhatunk egy függvényt +add(y=6, x=5) # Ez esetben a sorrendjük nem számít + + +# Változó számú paramétert fogadó függvény így definiálható. +# A * használatával a paramétereket egy N-esként kapjuk meg. +def varargs(*args): + return args + + +varargs(1, 2, 3) # => (1, 2, 3) + + +# Változó számú nevesített paramétert fogadó függvény is megadható, +# a ** használatával a paramétereket egy dictionary-ként kapjuk meg +def keyword_args(**kwargs): + return kwargs + + +# Nézzük meg, mi történik +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# A két módszer egyszerre is használható +def all_the_args(*args, **kwargs): + print args + print kwargs + + +""" +all_the_args(1, 2, a=3, b=4) kimenete: + (1, 2) + {"a": 3, "b": 4} +""" + +# Függvények hívásakor a fenti args és kwargs módszerek inverze használható +# A * karakter kifejt egy listát külön paraméterekbe, a ** egy dictionary-t nevesített paraméterekbe. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # egyenértékű: foo(1, 2, 3, 4) +all_the_args(**kwargs) # egyenértékű: foo(a=3, b=4) +all_the_args(*args, **kwargs) # egyenértékű: foo(1, 2, 3, 4, a=3, b=4) + + +# A fenti arg és kwarg paraméterek továbbadhatóak egyéb függvényeknek, +# a * illetve ** operátorokkal kifejtve +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + + +# Függvény scope +x = 5 + + +def set_x(num): + # A lokális x változó nem ugyanaz, mint a globális x + x = num # => 43 + print x # => 43 + + +def set_global_x(num): + global x + print x # => 5 + x = num # a globális x-et 6-ra állítjuk + print x # => 6 + + +set_x(43) +set_global_x(6) + + +# A pythonban a függvény elsőrendű (ún. "first class") típus +def create_adder(x): + def adder(y): + return x + y + + return adder + + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Névtelen függvények is definiálhatóak +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Léteznek beépített magasabb rendű függvények +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# A listaképző kifejezések ("list comprehensions") jól használhatóak a map és filter függvényekkel +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# halmaz és dictionary képzők is léteznek +{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'} +{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +# 5. Osztályok +#################################################### + +# Az object osztály egy alosztályát képezzük +class Human(object): + # Osztály szintű mező: az osztály összes példányában azonos + species = "H. sapiens" + + # Ez a függvény meghívódik az osztály példányosításakor. + # Megjegyzés: a dupla aláhúzás a név előtt és után egy konvenció a python + # előre definiált, a nyelv által belsőleg használt, de a felhasználó által + # is látható objektumok és mezők neveire. + # Ne vezessünk be új, ilyen elnevezési sémát használó neveket! + def __init__(self, name): + # A paramétert értékül adjuk a példány name attribútumának + self.name = name + + # Inicializálunk egy mezőt + self.age = 0 + + # Példány metódus. Minden metódus első paramétere a "self", a példány maga + def say(self, msg): + return "{0}: {1}".format(self.name, msg) + + # Egy osztálymetódus az osztály összes példány közt meg van osztva. + # Hívásukkor az első paraméter mindig a hívó osztály. + @classmethod + def get_species(cls): + return cls.species + + # Egy statikus metódus osztály és példányreferencia nélkül hívódik + @staticmethod + def grunt(): + return "*grunt*" + + # Egy property jelölésű függvény olyan, mint egy getter. + # Használatával az age mező egy csak-olvasható attribútummá válik. + @property + def age(self): + return self._age + + # Így lehet settert megadni egy mezőhöz + @age.setter + def age(self, age): + self._age = age + + # Így lehet egy mező törlését engedélyezni + @age.deleter + def age(self): + del self._age + + +# Példányosítsuk az osztályt +i = Human(name="Ian") +print i.say("hi") # kimenet: "Ian: hi" + +j = Human("Joel") +print j.say("hello") # kimenet: "Joel: hello" + +# Hívjuk az osztály metódusunkat +i.get_species() # => "H. sapiens" + +# Változtassuk meg az osztály szintű attribútumot +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Hívjuk meg a statikus metódust +Human.grunt() # => "*grunt*" + +# Adjunk új értéket a mezőnek +i.age = 42 + +# Kérjük le a mező értékét +i.age # => 42 + +# Töröljük a mezőt +del i.age +i.age # => AttributeError hibát dob + +#################################################### +# 6. Modulok +#################################################### + +# Modulokat így lehet importálni +import math + +print math.sqrt(16) # => 4.0 + +# Lehetséges csak bizonyos függvényeket importálni egy modulból +from math import ceil, floor + +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 + +# Egy modul összes függvénye is importálható +# Vigyázat: ez nem ajánlott. +from math import * + +# A modulok nevei lerövidíthetőek +import math as m + +math.sqrt(16) == m.sqrt(16) # => True +# Meggyőződhetünk róla, hogy a függvények valóban azonosak +from math import sqrt + +math.sqrt == m.sqrt == sqrt # => True + +# A Python modulok egyszerű fájlok. +# Írhatsz sajátot és importálhatod is. +# A modul neve azonos a tartalmazó fájl nevével. + +# Így lehet megtekinteni, milyen mezőket és függvényeket definiál egy modul. +import math + +dir(math) + + +# Ha van egy math.py nevű Python scripted a jelenleg futó scripttel azonos +# mappában, a math.py fájl lesz betöltve a beépített Python modul helyett. +# A lokális mappa prioritást élvez a beépített könyvtárak felett. + + +#################################################### +# 7. Haladóknak +#################################################### + +# Generátorok +# Egy generátor értékeket "generál" amikor kérik, a helyett, hogy előre eltárolná őket. + +# A következő metódus (ez még NEM egy generátor) megduplázza a kapott iterable elemeit, +# és eltárolja őket. Nagy méretű iterable esetén ez nagyon sok helyet foglalhat! +def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + return double_arr + + +# A következő kód futtatásakor az összes szám kétszeresét kiszámítanánk, és visszaadnánk +# ezt a nagy listát a ciklus vezérléséhez. +for value in double_numbers(range(1000000)): # `test_non_generator` + print value + if value > 5: + break + + +# Használjunk inkább egy generátort, ami "legenerálja" a soron következő elemet, +# amikor azt kérik tőle +def double_numbers_generator(iterable): + for i in iterable: + yield i + i + + +# A lenti kód mindig csak a soron következő számot generálja a logikai vizsgálat előtt. +# Így amikor az érték eléri a > 5 határt, megszakítjuk a ciklust, és a lista számainak +# nagy részénél megspóroltuk a duplázás műveletet (ez sokkal gyorsabb így!). +for value in double_numbers_generator(xrange(1000000)): # `test_generator` + print value + if value > 5: + break + +# Feltűnt, hogy a `test_non_generator` esetén `range`, a `test_generator` esetén +# pedig `xrange` volt a segédfüggvény neve? Ahogy `double_numbers_generator` a +# generátor változata a `double_numbers` függvénynek, úgy az `xrange` a `range` +# generátor megfelelője, csak akkor generálja le a következő számot, amikor kérjük +# - esetünkben a ciklus következő iterációjakor + +# A lista képzéshez hasonlóan generátor képzőket is használhatunk +# ("generator comprehensions"). +values = (-x for x in [1, 2, 3, 4, 5]) +for x in values: + print(x) # kimenet: -1 -2 -3 -4 -5 + +# Egy generátor összes generált elemét listaként is elkérhetjük: +values = (-x for x in [1, 2, 3, 4, 5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + +# Dekorátorok +# A dekorátor egy magasabb rendű függvény, aminek bemenete és kimenete is egy függvény. +# A lenti egyszerű példában az add_apples dekorátor a dekorált get_fruits függvény +# kimenetébe beszúrja az 'Apple' elemet. +def add_apples(func): + def get_fruits(): + fruits = func() + fruits.append('Apple') + return fruits + return get_fruits + +@add_apples +def get_fruits(): + return ['Banana', 'Mango', 'Orange'] + +# A kimenet tartalmazza az 'Apple' elemet: +# Banana, Mango, Orange, Apple +print ', '.join(get_fruits()) + +# Ebben a példában a beg dekorátorral látjuk el a say függvényt. +# Beg meghívja say-t. Ha a say_please paraméter igaz, akkor +# megváltoztatja az eredmény mondatot. +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print say() # Can you buy me a beer? +print say(say_please=True) # Can you buy me a beer? Please! I am poor :( +``` + +## Még több érdekel? + +### Ingyenes online tartalmak + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [LearnPython](http://www.learnpython.org/) +* [Fullstack Python](https://www.fullstackpython.com/) + +### Könyvek + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/it-it/python-it.html.markdown b/it-it/python-it.html.markdown deleted file mode 100644 index 794e7a70..00000000 --- a/it-it/python-it.html.markdown +++ /dev/null @@ -1,778 +0,0 @@ ---- -language: python -filename: learnpython-it.py -contributors: - - ["Louie Dinh", "http://ldinh.ca"] - - ["Amin Bandali", "http://aminbandali.com"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["evuez", "http://github.com/evuez"] -translators: - - ["Ale46", "http://github.com/Ale46/"] - - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] -lang: it-it ---- -Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari -linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente -pseudocodice eseguibile. - -Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service] - -Nota: questo articolo è riferito a Python 2.7 in modo specifico, ma dovrebbe andar -bene anche per Python 2.x. Python 2.7 sta raggiungendo il "fine vita", ovvero non sarà -più supportato nel 2020. Quindi è consigliato imparare Python utilizzando Python 3. -Per maggiori informazioni su Python 3.x, dai un'occhiata al [tutorial di Python 3](http://learnxinyminutes.com/docs/python3/). - -E' possibile anche scrivere codice compatibile sia con Python 2.7 che con Python 3.x, -utilizzando [il modulo `__future__`](https://docs.python.org/2/library/__future__.html) di Python. -Il modulo `__future__` permette di scrivere codice in Python 3, che può essere eseguito -utilizzando Python 2: cosa aspetti a vedere il tutorial di Python 3? - -```python - -# I commenti su una sola linea iniziano con un cancelletto - -""" Più stringhe possono essere scritte - usando tre ", e sono spesso usate - come commenti -""" - -#################################################### -## 1. Tipi di dati primitivi ed Operatori -#################################################### - -# Hai i numeri -3 # => 3 - -# La matematica è quello che vi aspettereste -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7 - -# La divisione è un po' complicata. E' una divisione fra interi in cui viene -# restituito in automatico il risultato intero. -5 / 2 # => 2 - -# Per le divisioni con la virgola abbiamo bisogno di parlare delle variabili floats. -2.0 # Questo è un float -11.0 / 4.0 # => 2.75 ahhh...molto meglio - -# Il risultato di una divisione fra interi troncati positivi e negativi -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # funziona anche per i floats --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# E' possibile importare il modulo "division" (vedi la sezione 6 di questa guida, Moduli) -# per effettuare la divisione normale usando solo '/'. -from __future__ import division -11/4 # => 2.75 ...divisione normale -11//4 # => 2 ...divisione troncata - -# Operazione Modulo -7 % 3 # => 1 - -# Elevamento a potenza (x alla y-esima potenza) -2**4 # => 16 - -# Forzare le precedenze con le parentesi -(1 + 3) * 2 # => 8 - -# Operatori Booleani -# Nota "and" e "or" sono case-sensitive -True and False #=> False -False or True #=> True - -# Note sull'uso di operatori Bool con interi -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True - -# nega con not -not True # => False -not False # => True - -# Uguaglianza è == -1 == 1 # => True -2 == 1 # => False - -# Disuguaglianza è != -1 != 1 # => False -2 != 1 # => True - -# Altri confronti -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# I confronti possono essere concatenati! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# Le stringhe sono create con " o ' -"Questa è una stringa." -'Anche questa è una stringa.' - -# Anche le stringhe possono essere sommate! -"Ciao " + "mondo!" # => Ciao mondo!" -# Le stringhe possono essere sommate anche senza '+' -"Ciao " "mondo!" # => Ciao mondo!" - -# ... oppure moltiplicate -"Hello" * 3 # => "HelloHelloHello" - -# Una stringa può essere considerata come una lista di caratteri -"Questa è una stringa"[0] # => 'Q' - -# Per sapere la lunghezza di una stringa -len("Questa è una stringa") # => 20 - -# Formattazione delle stringhe con % -# Anche se l'operatore % per le stringe sarà deprecato con Python 3.1, e verrà rimosso -# successivamente, può comunque essere utile sapere come funziona -x = 'mela' -y = 'limone' -z = "La cesta contiene una %s e un %s" % (x,y) - -# Un nuovo modo per fomattare le stringhe è il metodo format. -# Questo metodo è quello consigliato -"{} è un {}".format("Questo", "test") -"{0} possono essere {1}".format("le stringhe", "formattate") -# Puoi usare delle parole chiave se non vuoi contare -"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="lasagna") - -# None è un oggetto -None # => None - -# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None -# Usa "is" invece -"etc" is None # => False -None is None # => True - -# L'operatore 'is' testa l'identità di un oggetto. Questo non è -# molto utile quando non hai a che fare con valori primitivi, ma lo è -# quando hai a che fare con oggetti. - -# Qualunque oggetto può essere usato nei test booleani -# I seguenti valori sono considerati falsi: -# - None -# - Lo zero, come qualunque tipo numerico (quindi 0, 0L, 0.0, 0.j) -# - Sequenze vuote (come '', (), []) -# - Contenitori vuoti (tipo {}, set()) -# - Istanze di classi definite dall'utente, che soddisfano certi criteri -# vedi: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ -# -# Tutti gli altri valori sono considerati veri: la funzione bool() usata su di loro, ritorna True. -bool(0) # => False -bool("") # => False - - -#################################################### -## 2. Variabili e Collections -#################################################### - -# Python ha una funzione di stampa -print "Sono Python. Piacere di conoscerti!" # => Sono Python. Piacere di conoscerti! - -# Un modo semplice per ricevere dati in input dalla riga di comando -variabile_stringa_input = raw_input("Inserisci del testo: ") # Ritorna i dati letti come stringa -variabile_input = input("Inserisci del testo: ") # Interpreta i dati letti come codice python -# Attenzione: bisogna stare attenti quando si usa input() -# Nota: In python 3, input() è deprecato, e raw_input() si chiama input() - -# Non c'è bisogno di dichiarare una variabile per assegnarle un valore -una_variabile = 5 # Convenzionalmente si usa caratteri_minuscoli_con_underscores -una_variabile # => 5 - -# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione. -# Dai un'occhiata al Control Flow per imparare di più su come gestire le eccezioni. -un_altra_variabile # Genera un errore di nome - -# if può essere usato come un'espressione -# E' l'equivalente dell'operatore ternario in C -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# Liste immagazzinano sequenze -li = [] -# Puoi partire con una lista pre-riempita -altra_li = [4, 5, 6] - -# Aggiungi cose alla fine di una lista con append -li.append(1) # li ora è [1] -li.append(2) # li ora è [1, 2] -li.append(4) # li ora è [1, 2, 4] -li.append(3) # li ora è [1, 2, 4, 3] -# Rimuovi dalla fine della lista con pop -li.pop() # => 3 e li ora è [1, 2, 4] -# Rimettiamolo a posto -li.append(3) # li ora è [1, 2, 4, 3] di nuovo. - -# Accedi ad una lista come faresti con un array -li[0] # => 1 -# Assegna nuovo valore agli indici che sono già stati inizializzati con = -li[0] = 42 -li[0] # => 42 -li[0] = 1 # Nota: è resettato al valore iniziale -# Guarda l'ultimo elemento -li[-1] # => 3 - -# Guardare al di fuori dei limiti è un IndexError -li[4] # Genera IndexError - -# Puoi guardare gli intervalli con la sintassi slice (a fetta). -# (E' un intervallo chiuso/aperto per voi tipi matematici.) -li[1:3] # => [2, 4] -# Ometti l'inizio -li[2:] # => [4, 3] -# Ometti la fine -li[:3] # => [1, 2, 4] -# Seleziona ogni seconda voce -li[::2] # =>[1, 4] -# Copia al contrario della lista -li[::-1] # => [3, 4, 2, 1] -# Usa combinazioni per fare slices avanzate -# li[inizio:fine:passo] - -# Rimuovi arbitrariamente elementi da una lista con "del" -del li[2] # li è ora [1, 2, 3] -# Puoi sommare le liste -li + altra_li # => [1, 2, 3, 4, 5, 6] -# Nota: i valori per li ed altra_li non sono modificati. - -# Concatena liste con "extend()" -li.extend(altra_li) # Ora li è [1, 2, 3, 4, 5, 6] - -# Rimuove la prima occorrenza di un elemento -li.remove(2) # Ora li è [1, 3, 4, 5, 6] -li.remove(2) # Emette un ValueError, poichè 2 non è contenuto nella lista - -# Inserisce un elemento all'indice specificato -li.insert(1, 2) # li è di nuovo [1, 2, 3, 4, 5, 6] - -# Ritorna l'indice della prima occorrenza dell'elemento fornito -li.index(2) # => 1 -li.index(7) # Emette un ValueError, poichè 7 non è contenuto nella lista - -# Controlla l'esistenza di un valore in una lista con "in" -1 in li # => True - -# Esamina la lunghezza con "len()" -len(li) # => 6 - - -# Tuple sono come le liste ma immutabili. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Genera un TypeError - -# Puoi fare tutte queste cose da lista anche sulle tuple -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Puoi scompattare le tuple (o liste) in variabili -a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 and c è ora 3 -d, e, f = 4, 5, 6 # puoi anche omettere le parentesi -# Le tuple sono create di default se non usi le parentesi -g = 4, 5, 6 # => (4, 5, 6) -# Guarda come è facile scambiare due valori -e, d = d, e # d è ora 5 ed e è ora 4 - - -# Dizionari immagazzinano mappature -empty_dict = {} -# Questo è un dizionario pre-riempito -filled_dict = {"uno": 1, "due": 2, "tre": 3} - -# Accedi ai valori con [] -filled_dict["uno"] # => 1 - -# Ottieni tutte le chiavi come una lista con "keys()" -filled_dict.keys() # => ["tre", "due", "uno"] -# Nota - Nei dizionari l'ordine delle chiavi non è garantito. -# Il tuo risultato potrebbe non essere uguale a questo. - -# Ottieni tutt i valori come una lista con "values()" -filled_dict.values() # => [3, 2, 1] -# Nota - Come sopra riguardo l'ordinamento delle chiavi. - -# Ottieni tutte le coppie chiave-valore, sotto forma di lista di tuple, utilizzando "items()" -filled_dicts.items() # => [("uno", 1), ("due", 2), ("tre", 3)] - -# Controlla l'esistenza delle chiavi in un dizionario con "in" -"uno" in filled_dict # => True -1 in filled_dict # => False - -# Cercando una chiave non esistente è un KeyError -filled_dict["quattro"] # KeyError - -# Usa il metodo "get()" per evitare KeyError -filled_dict.get("uno") # => 1 -filled_dict.get("quattro") # => None -# Il metodo get supporta un argomento di default quando il valore è mancante -filled_dict.get("uno", 4) # => 1 -filled_dict.get("quattro", 4) # => 4 -# nota che filled_dict.get("quattro") è ancora => None -# (get non imposta il valore nel dizionario) - -# imposta il valore di una chiave con una sintassi simile alle liste -filled_dict["quattro"] = 4 # ora, filled_dict["quattro"] => 4 - -# "setdefault()" aggiunge al dizionario solo se la chiave data non è presente -filled_dict.setdefault("five", 5) # filled_dict["five"] è impostato a 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] è ancora 5 - - -# Sets immagazzina ... sets (che sono come le liste, ma non possono contenere doppioni) -empty_set = set() -# Inizializza un "set()" con un po' di valori -some_set = set([1, 2, 2, 3, 4]) # some_set è ora set([1, 2, 3, 4]) - -# l'ordine non è garantito, anche se a volta può sembrare ordinato -another_set = set([4, 3, 2, 2, 1]) # another_set è ora set([1, 2, 3, 4]) - -# Da Python 2.7, {} può essere usato per dichiarare un set -filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} - -# Aggiungere elementi ad un set -filled_set.add(5) # filled_set è ora {1, 2, 3, 4, 5} - -# Fai intersezioni su un set con & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# Fai unioni su set con | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Fai differenze su set con - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Effettua la differenza simmetrica con ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Controlla se il set a sinistra contiene quello a destra -{1, 2} >= {1, 2, 3} # => False - -# Controlla se il set a sinistra è un sottoinsieme di quello a destra -{1, 2} <= {1, 2, 3} # => True - -# Controlla l'esistenza in un set con in -2 in filled_set # => True -10 in filled_set # => False - - -#################################################### -## 3. Control Flow -#################################################### - -# Dichiariamo una variabile -some_var = 5 - -# Questo è un controllo if. L'indentazione è molto importante in python! -# stampa "some_var è più piccola di 10" -if some_var > 10: - print "some_var è decisamente più grande di 10." -elif some_var < 10: # Questa clausola elif è opzionale. - print "some_var è più piccola di 10." -else: # Anche questo è opzionale. - print "some_var è precisamente 10." - - -""" -I cicli for iterano sulle liste -stampa: - cane è un mammifero - gatto è un mammifero - topo è un mammifero -""" -for animale in ["cane", "gatto", "topo"]: - # Puoi usare {0} per interpolare le stringhe formattate. (Vedi di seguito.) - print "{0} è un mammifero".format(animale) - -""" -"range(numero)" restituisce una lista di numeri -da zero al numero dato -stampa: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -"range(lower, upper)" restituisce una lista di numeri -dal più piccolo (lower) al più grande (upper) -stampa: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print i - -""" -I cicli while vengono eseguiti finchè una condizione viene a mancare -stampa: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # Forma compatta per x = x + 1 - -# Gestisci le eccezioni con un blocco try/except - -# Funziona da Python 2.6 in su: -try: - # Usa "raise" per generare un errore - raise IndexError("Questo è un errore di indice") -except IndexError as e: - pass # Pass è solo una non-operazione. Solitamente vorrai fare un recupero. -except (TypeError, NameError): - pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario. -else: # Clausola opzionale al blocco try/except. Deve seguire tutti i blocchi except - print "Tutto ok!" # Viene eseguita solo se il codice dentro try non genera eccezioni -finally: # Eseguito sempre - print "Possiamo liberare risorse qui" - -# Invece di try/finally per liberare risorse puoi usare il metodo with -with open("myfile.txt") as f: - for line in f: - print line - -#################################################### -## 4. Funzioni -#################################################### - -# Usa "def" per creare nuove funzioni -def aggiungi(x, y): - print "x è {0} e y è {1}".format(x, y) - return x + y # Restituisce valori con il metodo return - -# Chiamare funzioni con parametri -aggiungi(5, 6) # => stampa "x è 5 e y è 6" e restituisce 11 - -# Un altro modo per chiamare funzioni è con parole chiave come argomenti -aggiungi(y=6, x=5) # Le parole chiave come argomenti possono arrivare in ogni ordine. - - -# Puoi definire funzioni che accettano un numero variabile di argomenti posizionali -# che verranno interpretati come tuple usando il * -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - - -# Puoi definire funzioni che accettano un numero variabile di parole chiave -# come argomento, che saranno interpretati come un dizionario usando ** -def keyword_args(**kwargs): - return kwargs - -# Chiamiamola per vedere cosa succede -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# Puoi farle entrambi in una volta, se ti va -def all_the_args(*args, **kwargs): - print args - print kwargs -""" -all_the_args(1, 2, a=3, b=4) stampa: - (1, 2) - {"a": 3, "b": 4} -""" - -# Quando chiami funzioni, puoi fare l'opposto di args/kwargs! -# Usa * per sviluppare gli argomenti posizionale ed usa ** per espandere gli argomenti parola chiave -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalente a foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalente a foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) - -# puoi passare args e kwargs insieme alle altre funzioni che accettano args/kwargs -# sviluppandoli, rispettivamente, con * e ** -def pass_all_the_args(*args, **kwargs): - all_the_args(*args, **kwargs) - print varargs(*args) - print keyword_args(**kwargs) - -# Funzioni Scope -x = 5 - -def set_x(num): - # La variabile locale x non è uguale alla variabile globale x - x = num # => 43 - print x # => 43 - -def set_global_x(num): - global x - print x # => 5 - x = num # la variabile globable x è ora 6 - print x # => 6 - -set_x(43) -set_global_x(6) - -# Python ha funzioni di prima classe -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Ci sono anche funzioni anonime -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# Esse sono incluse in funzioni di alto livello -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] - -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# Possiamo usare la comprensione delle liste per mappe e filtri -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# Puoi fare anche la comprensione di set e dizionari -{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'} -{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -## 5. Classi -#################################################### - -# Usiamo una sottoclasse da un oggetto per avere una classe. -class Human(object): - - # Un attributo della classe. E' condiviso da tutte le istanze delle classe - species = "H. sapiens" - - # Costruttore base, richiamato quando la classe viene inizializzata. - # Si noti che il doppio leading e gli underscore finali denotano oggetti - # o attributi che sono usati da python ma che vivono nello spazio dei nome controllato - # dall'utente. Non dovresti usare nomi di questo genere. - def __init__(self, name): - # Assegna l'argomento all'attributo name dell'istanza - self.name = name - - # Inizializza una proprietà - self.age = 0 - - # Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento - def say(self, msg): - return "{0}: {1}".format(self.name, msg) - - # Un metodo della classe è condiviso fra tutte le istanze - # Sono chiamate con la classe chiamante come primo argomento - @classmethod - def get_species(cls): - return cls.species - - # Un metodo statico è chiamato senza una classe od una istanza di riferimento - @staticmethod - def grunt(): - return "*grunt*" - - # Una proprietà è come un metodo getter. - # Trasforma il metodo age() in un attributo in sola lettura, che ha lo stesso nome - @property - def age(self): - return self._age - - # Questo metodo permette di modificare la proprietà - @age.setter - def age(self, age): - self._age = age - - # Questo metodo permette di cancellare la proprietà - @age.deleter - def age(self): - del self._age - -# Instanziare una classe -i = Human(name="Ian") -print i.say("hi") # stampa "Ian: hi" - -j = Human("Joel") -print j.say("hello") # stampa "Joel: hello" - -# Chiamare metodi della classe -i.get_species() # => "H. sapiens" - -# Cambiare l'attributo condiviso -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# Chiamare il metodo condiviso -Human.grunt() # => "*grunt*" - -# Aggiorna la proprietà -i.age = 42 - -# Ritorna il valore della proprietà -i.age # => 42 - -# Cancella la proprietà -del i.age -i.age # => Emette un AttributeError - - -#################################################### -## 6. Moduli -#################################################### - -# Puoi importare moduli -import math -print math.sqrt(16) # => 4.0 - -# Puoi ottenere specifiche funzione da un modulo -from math import ceil, floor -print ceil(3.7) # => 4.0 -print floor(3.7) # => 3.0 - -# Puoi importare tutte le funzioni da un modulo -# Attenzione: questo non è raccomandato -from math import * - -# Puoi abbreviare i nomi dei moduli -import math as m -math.sqrt(16) == m.sqrt(16) # => True -# puoi anche verificare che le funzioni sono equivalenti -from math import sqrt -math.sqrt == m.sqrt == sqrt # => True - -# I moduli di Python sono normali file python. Ne puoi -# scrivere di tuoi ed importarli. Il nome del modulo -# è lo stesso del nome del file. - -# Potete scoprire quali funzioni e attributi -# definiscono un modulo -import math -dir(math) - -# Se nella cartella corrente hai uno script chiamato math.py, -# Python caricherà quello invece del modulo math. -# Questo succede perchè la cartella corrente ha priorità -# sulle librerie standard di Python - - -#################################################### -## 7. Avanzate -#################################################### - -# Generatori -# Un generatore appunto "genera" valori solo quando vengono richiesti, -# invece di memorizzarli tutti subito fin dall'inizio - -# Il metodo seguente (che NON è un generatore) raddoppia tutti i valori e li memorizza -# dentro `double_arr`. Se gli oggetti iterabili sono grandi, il vettore risultato -# potrebbe diventare enorme! -def double_numbers(iterable): - double_arr = [] - for i in iterable: - double_arr.append(i + i) - -# Eseguendo il seguente codice, noi andiamo a raddoppiare prima tutti i valori, e poi -# li ritorniamo tutti e andiamo a controllare la condizione -for value in double_numbers(range(1000000)): # `test_senza_generatore` - print value - if value > 5: - break - -# Invece, potremmo usare un generatore per "generare" il valore raddoppiato non -# appena viene richiesto -def double_numbers_generator(iterable): - for i in iterable: - yield i + i - -# Utilizzando lo stesso test di prima, stavolta però con un generatore, ci permette -# di iterare sui valori e raddoppiarli uno alla volta, non appena vengono richiesti dalla -# logica del programma. Per questo, non appena troviamo un valore > 5, usciamo dal ciclo senza -# bisogno di raddoppiare la maggior parte dei valori del range (MOLTO PIU VELOCE!) -for value in double_numbers_generator(xrange(1000000)): # `test_generatore` - print value - if value > 5: - break - -# Nota: hai notato l'uso di `range` in `test_senza_generatore` e `xrange` in `test_generatore`? -# Proprio come `double_numbers_generator` è la versione col generatore di `double_numbers` -# Abbiamo `xrange` come versione col generatore di `range` -# `range` ritorna un array di 1000000 elementi -# `xrange` invece genera 1000000 valori quando lo richiediamo/iteriamo su di essi - -# Allo stesso modo della comprensione delle liste, puoi creare la comprensione -# dei generatori. -values = (-x for x in [1,2,3,4,5]) -for x in values: - print(x) # stampa -1 -2 -3 -4 -5 - -# Puoi anche fare il cast diretto di una comprensione di generatori ad una lista. -values = (-x for x in [1,2,3,4,5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - - -# Decoratori -# in questo esempio beg include say -# Beg chiamerà say. Se say_please è True allora cambierà il messaggio -# ritornato -from functools import wraps - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Per favore! Sono povero :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Puoi comprarmi una birra?" - return msg, say_please - - -print say() # Puoi comprarmi una birra? -print say(say_please=True) # Puoi comprarmi una birra? Per favore! Sono povero :( -``` - -## Pronto per qualcosa di più? - -### Gratis Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [LearnPython](http://www.learnpython.org/) -* [Fullstack Python](https://www.fullstackpython.com/) - -### Libri cartacei - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/it-it/pythonlegacy-it.html.markdown b/it-it/pythonlegacy-it.html.markdown new file mode 100644 index 00000000..794e7a70 --- /dev/null +++ b/it-it/pythonlegacy-it.html.markdown @@ -0,0 +1,778 @@ +--- +language: python +filename: learnpython-it.py +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "http://aminbandali.com"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] +translators: + - ["Ale46", "http://github.com/Ale46/"] + - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] +lang: it-it +--- +Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari +linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente +pseudocodice eseguibile. + +Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service] + +Nota: questo articolo è riferito a Python 2.7 in modo specifico, ma dovrebbe andar +bene anche per Python 2.x. Python 2.7 sta raggiungendo il "fine vita", ovvero non sarà +più supportato nel 2020. Quindi è consigliato imparare Python utilizzando Python 3. +Per maggiori informazioni su Python 3.x, dai un'occhiata al [tutorial di Python 3](http://learnxinyminutes.com/docs/python3/). + +E' possibile anche scrivere codice compatibile sia con Python 2.7 che con Python 3.x, +utilizzando [il modulo `__future__`](https://docs.python.org/2/library/__future__.html) di Python. +Il modulo `__future__` permette di scrivere codice in Python 3, che può essere eseguito +utilizzando Python 2: cosa aspetti a vedere il tutorial di Python 3? + +```python + +# I commenti su una sola linea iniziano con un cancelletto + +""" Più stringhe possono essere scritte + usando tre ", e sono spesso usate + come commenti +""" + +#################################################### +## 1. Tipi di dati primitivi ed Operatori +#################################################### + +# Hai i numeri +3 # => 3 + +# La matematica è quello che vi aspettereste +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# La divisione è un po' complicata. E' una divisione fra interi in cui viene +# restituito in automatico il risultato intero. +5 / 2 # => 2 + +# Per le divisioni con la virgola abbiamo bisogno di parlare delle variabili floats. +2.0 # Questo è un float +11.0 / 4.0 # => 2.75 ahhh...molto meglio + +# Il risultato di una divisione fra interi troncati positivi e negativi +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # funziona anche per i floats +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# E' possibile importare il modulo "division" (vedi la sezione 6 di questa guida, Moduli) +# per effettuare la divisione normale usando solo '/'. +from __future__ import division +11/4 # => 2.75 ...divisione normale +11//4 # => 2 ...divisione troncata + +# Operazione Modulo +7 % 3 # => 1 + +# Elevamento a potenza (x alla y-esima potenza) +2**4 # => 16 + +# Forzare le precedenze con le parentesi +(1 + 3) * 2 # => 8 + +# Operatori Booleani +# Nota "and" e "or" sono case-sensitive +True and False #=> False +False or True #=> True + +# Note sull'uso di operatori Bool con interi +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# nega con not +not True # => False +not False # => True + +# Uguaglianza è == +1 == 1 # => True +2 == 1 # => False + +# Disuguaglianza è != +1 != 1 # => False +2 != 1 # => True + +# Altri confronti +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# I confronti possono essere concatenati! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Le stringhe sono create con " o ' +"Questa è una stringa." +'Anche questa è una stringa.' + +# Anche le stringhe possono essere sommate! +"Ciao " + "mondo!" # => Ciao mondo!" +# Le stringhe possono essere sommate anche senza '+' +"Ciao " "mondo!" # => Ciao mondo!" + +# ... oppure moltiplicate +"Hello" * 3 # => "HelloHelloHello" + +# Una stringa può essere considerata come una lista di caratteri +"Questa è una stringa"[0] # => 'Q' + +# Per sapere la lunghezza di una stringa +len("Questa è una stringa") # => 20 + +# Formattazione delle stringhe con % +# Anche se l'operatore % per le stringe sarà deprecato con Python 3.1, e verrà rimosso +# successivamente, può comunque essere utile sapere come funziona +x = 'mela' +y = 'limone' +z = "La cesta contiene una %s e un %s" % (x,y) + +# Un nuovo modo per fomattare le stringhe è il metodo format. +# Questo metodo è quello consigliato +"{} è un {}".format("Questo", "test") +"{0} possono essere {1}".format("le stringhe", "formattate") +# Puoi usare delle parole chiave se non vuoi contare +"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="lasagna") + +# None è un oggetto +None # => None + +# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None +# Usa "is" invece +"etc" is None # => False +None is None # => True + +# L'operatore 'is' testa l'identità di un oggetto. Questo non è +# molto utile quando non hai a che fare con valori primitivi, ma lo è +# quando hai a che fare con oggetti. + +# Qualunque oggetto può essere usato nei test booleani +# I seguenti valori sono considerati falsi: +# - None +# - Lo zero, come qualunque tipo numerico (quindi 0, 0L, 0.0, 0.j) +# - Sequenze vuote (come '', (), []) +# - Contenitori vuoti (tipo {}, set()) +# - Istanze di classi definite dall'utente, che soddisfano certi criteri +# vedi: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# Tutti gli altri valori sono considerati veri: la funzione bool() usata su di loro, ritorna True. +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Variabili e Collections +#################################################### + +# Python ha una funzione di stampa +print "Sono Python. Piacere di conoscerti!" # => Sono Python. Piacere di conoscerti! + +# Un modo semplice per ricevere dati in input dalla riga di comando +variabile_stringa_input = raw_input("Inserisci del testo: ") # Ritorna i dati letti come stringa +variabile_input = input("Inserisci del testo: ") # Interpreta i dati letti come codice python +# Attenzione: bisogna stare attenti quando si usa input() +# Nota: In python 3, input() è deprecato, e raw_input() si chiama input() + +# Non c'è bisogno di dichiarare una variabile per assegnarle un valore +una_variabile = 5 # Convenzionalmente si usa caratteri_minuscoli_con_underscores +una_variabile # => 5 + +# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione. +# Dai un'occhiata al Control Flow per imparare di più su come gestire le eccezioni. +un_altra_variabile # Genera un errore di nome + +# if può essere usato come un'espressione +# E' l'equivalente dell'operatore ternario in C +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Liste immagazzinano sequenze +li = [] +# Puoi partire con una lista pre-riempita +altra_li = [4, 5, 6] + +# Aggiungi cose alla fine di una lista con append +li.append(1) # li ora è [1] +li.append(2) # li ora è [1, 2] +li.append(4) # li ora è [1, 2, 4] +li.append(3) # li ora è [1, 2, 4, 3] +# Rimuovi dalla fine della lista con pop +li.pop() # => 3 e li ora è [1, 2, 4] +# Rimettiamolo a posto +li.append(3) # li ora è [1, 2, 4, 3] di nuovo. + +# Accedi ad una lista come faresti con un array +li[0] # => 1 +# Assegna nuovo valore agli indici che sono già stati inizializzati con = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Nota: è resettato al valore iniziale +# Guarda l'ultimo elemento +li[-1] # => 3 + +# Guardare al di fuori dei limiti è un IndexError +li[4] # Genera IndexError + +# Puoi guardare gli intervalli con la sintassi slice (a fetta). +# (E' un intervallo chiuso/aperto per voi tipi matematici.) +li[1:3] # => [2, 4] +# Ometti l'inizio +li[2:] # => [4, 3] +# Ometti la fine +li[:3] # => [1, 2, 4] +# Seleziona ogni seconda voce +li[::2] # =>[1, 4] +# Copia al contrario della lista +li[::-1] # => [3, 4, 2, 1] +# Usa combinazioni per fare slices avanzate +# li[inizio:fine:passo] + +# Rimuovi arbitrariamente elementi da una lista con "del" +del li[2] # li è ora [1, 2, 3] +# Puoi sommare le liste +li + altra_li # => [1, 2, 3, 4, 5, 6] +# Nota: i valori per li ed altra_li non sono modificati. + +# Concatena liste con "extend()" +li.extend(altra_li) # Ora li è [1, 2, 3, 4, 5, 6] + +# Rimuove la prima occorrenza di un elemento +li.remove(2) # Ora li è [1, 3, 4, 5, 6] +li.remove(2) # Emette un ValueError, poichè 2 non è contenuto nella lista + +# Inserisce un elemento all'indice specificato +li.insert(1, 2) # li è di nuovo [1, 2, 3, 4, 5, 6] + +# Ritorna l'indice della prima occorrenza dell'elemento fornito +li.index(2) # => 1 +li.index(7) # Emette un ValueError, poichè 7 non è contenuto nella lista + +# Controlla l'esistenza di un valore in una lista con "in" +1 in li # => True + +# Esamina la lunghezza con "len()" +len(li) # => 6 + + +# Tuple sono come le liste ma immutabili. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Genera un TypeError + +# Puoi fare tutte queste cose da lista anche sulle tuple +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Puoi scompattare le tuple (o liste) in variabili +a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 and c è ora 3 +d, e, f = 4, 5, 6 # puoi anche omettere le parentesi +# Le tuple sono create di default se non usi le parentesi +g = 4, 5, 6 # => (4, 5, 6) +# Guarda come è facile scambiare due valori +e, d = d, e # d è ora 5 ed e è ora 4 + + +# Dizionari immagazzinano mappature +empty_dict = {} +# Questo è un dizionario pre-riempito +filled_dict = {"uno": 1, "due": 2, "tre": 3} + +# Accedi ai valori con [] +filled_dict["uno"] # => 1 + +# Ottieni tutte le chiavi come una lista con "keys()" +filled_dict.keys() # => ["tre", "due", "uno"] +# Nota - Nei dizionari l'ordine delle chiavi non è garantito. +# Il tuo risultato potrebbe non essere uguale a questo. + +# Ottieni tutt i valori come una lista con "values()" +filled_dict.values() # => [3, 2, 1] +# Nota - Come sopra riguardo l'ordinamento delle chiavi. + +# Ottieni tutte le coppie chiave-valore, sotto forma di lista di tuple, utilizzando "items()" +filled_dicts.items() # => [("uno", 1), ("due", 2), ("tre", 3)] + +# Controlla l'esistenza delle chiavi in un dizionario con "in" +"uno" in filled_dict # => True +1 in filled_dict # => False + +# Cercando una chiave non esistente è un KeyError +filled_dict["quattro"] # KeyError + +# Usa il metodo "get()" per evitare KeyError +filled_dict.get("uno") # => 1 +filled_dict.get("quattro") # => None +# Il metodo get supporta un argomento di default quando il valore è mancante +filled_dict.get("uno", 4) # => 1 +filled_dict.get("quattro", 4) # => 4 +# nota che filled_dict.get("quattro") è ancora => None +# (get non imposta il valore nel dizionario) + +# imposta il valore di una chiave con una sintassi simile alle liste +filled_dict["quattro"] = 4 # ora, filled_dict["quattro"] => 4 + +# "setdefault()" aggiunge al dizionario solo se la chiave data non è presente +filled_dict.setdefault("five", 5) # filled_dict["five"] è impostato a 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] è ancora 5 + + +# Sets immagazzina ... sets (che sono come le liste, ma non possono contenere doppioni) +empty_set = set() +# Inizializza un "set()" con un po' di valori +some_set = set([1, 2, 2, 3, 4]) # some_set è ora set([1, 2, 3, 4]) + +# l'ordine non è garantito, anche se a volta può sembrare ordinato +another_set = set([4, 3, 2, 2, 1]) # another_set è ora set([1, 2, 3, 4]) + +# Da Python 2.7, {} può essere usato per dichiarare un set +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Aggiungere elementi ad un set +filled_set.add(5) # filled_set è ora {1, 2, 3, 4, 5} + +# Fai intersezioni su un set con & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Fai unioni su set con | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Fai differenze su set con - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Effettua la differenza simmetrica con ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Controlla se il set a sinistra contiene quello a destra +{1, 2} >= {1, 2, 3} # => False + +# Controlla se il set a sinistra è un sottoinsieme di quello a destra +{1, 2} <= {1, 2, 3} # => True + +# Controlla l'esistenza in un set con in +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. Control Flow +#################################################### + +# Dichiariamo una variabile +some_var = 5 + +# Questo è un controllo if. L'indentazione è molto importante in python! +# stampa "some_var è più piccola di 10" +if some_var > 10: + print "some_var è decisamente più grande di 10." +elif some_var < 10: # Questa clausola elif è opzionale. + print "some_var è più piccola di 10." +else: # Anche questo è opzionale. + print "some_var è precisamente 10." + + +""" +I cicli for iterano sulle liste +stampa: + cane è un mammifero + gatto è un mammifero + topo è un mammifero +""" +for animale in ["cane", "gatto", "topo"]: + # Puoi usare {0} per interpolare le stringhe formattate. (Vedi di seguito.) + print "{0} è un mammifero".format(animale) + +""" +"range(numero)" restituisce una lista di numeri +da zero al numero dato +stampa: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(lower, upper)" restituisce una lista di numeri +dal più piccolo (lower) al più grande (upper) +stampa: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +I cicli while vengono eseguiti finchè una condizione viene a mancare +stampa: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Forma compatta per x = x + 1 + +# Gestisci le eccezioni con un blocco try/except + +# Funziona da Python 2.6 in su: +try: + # Usa "raise" per generare un errore + raise IndexError("Questo è un errore di indice") +except IndexError as e: + pass # Pass è solo una non-operazione. Solitamente vorrai fare un recupero. +except (TypeError, NameError): + pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario. +else: # Clausola opzionale al blocco try/except. Deve seguire tutti i blocchi except + print "Tutto ok!" # Viene eseguita solo se il codice dentro try non genera eccezioni +finally: # Eseguito sempre + print "Possiamo liberare risorse qui" + +# Invece di try/finally per liberare risorse puoi usare il metodo with +with open("myfile.txt") as f: + for line in f: + print line + +#################################################### +## 4. Funzioni +#################################################### + +# Usa "def" per creare nuove funzioni +def aggiungi(x, y): + print "x è {0} e y è {1}".format(x, y) + return x + y # Restituisce valori con il metodo return + +# Chiamare funzioni con parametri +aggiungi(5, 6) # => stampa "x è 5 e y è 6" e restituisce 11 + +# Un altro modo per chiamare funzioni è con parole chiave come argomenti +aggiungi(y=6, x=5) # Le parole chiave come argomenti possono arrivare in ogni ordine. + + +# Puoi definire funzioni che accettano un numero variabile di argomenti posizionali +# che verranno interpretati come tuple usando il * +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# Puoi definire funzioni che accettano un numero variabile di parole chiave +# come argomento, che saranno interpretati come un dizionario usando ** +def keyword_args(**kwargs): + return kwargs + +# Chiamiamola per vedere cosa succede +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# Puoi farle entrambi in una volta, se ti va +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) stampa: + (1, 2) + {"a": 3, "b": 4} +""" + +# Quando chiami funzioni, puoi fare l'opposto di args/kwargs! +# Usa * per sviluppare gli argomenti posizionale ed usa ** per espandere gli argomenti parola chiave +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalente a foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalente a foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# puoi passare args e kwargs insieme alle altre funzioni che accettano args/kwargs +# sviluppandoli, rispettivamente, con * e ** +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# Funzioni Scope +x = 5 + +def set_x(num): + # La variabile locale x non è uguale alla variabile globale x + x = num # => 43 + print x # => 43 + +def set_global_x(num): + global x + print x # => 5 + x = num # la variabile globable x è ora 6 + print x # => 6 + +set_x(43) +set_global_x(6) + +# Python ha funzioni di prima classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Ci sono anche funzioni anonime +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Esse sono incluse in funzioni di alto livello +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Possiamo usare la comprensione delle liste per mappe e filtri +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# Puoi fare anche la comprensione di set e dizionari +{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Classi +#################################################### + +# Usiamo una sottoclasse da un oggetto per avere una classe. +class Human(object): + + # Un attributo della classe. E' condiviso da tutte le istanze delle classe + species = "H. sapiens" + + # Costruttore base, richiamato quando la classe viene inizializzata. + # Si noti che il doppio leading e gli underscore finali denotano oggetti + # o attributi che sono usati da python ma che vivono nello spazio dei nome controllato + # dall'utente. Non dovresti usare nomi di questo genere. + def __init__(self, name): + # Assegna l'argomento all'attributo name dell'istanza + self.name = name + + # Inizializza una proprietà + self.age = 0 + + # Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento + def say(self, msg): + return "{0}: {1}".format(self.name, msg) + + # Un metodo della classe è condiviso fra tutte le istanze + # Sono chiamate con la classe chiamante come primo argomento + @classmethod + def get_species(cls): + return cls.species + + # Un metodo statico è chiamato senza una classe od una istanza di riferimento + @staticmethod + def grunt(): + return "*grunt*" + + # Una proprietà è come un metodo getter. + # Trasforma il metodo age() in un attributo in sola lettura, che ha lo stesso nome + @property + def age(self): + return self._age + + # Questo metodo permette di modificare la proprietà + @age.setter + def age(self, age): + self._age = age + + # Questo metodo permette di cancellare la proprietà + @age.deleter + def age(self): + del self._age + +# Instanziare una classe +i = Human(name="Ian") +print i.say("hi") # stampa "Ian: hi" + +j = Human("Joel") +print j.say("hello") # stampa "Joel: hello" + +# Chiamare metodi della classe +i.get_species() # => "H. sapiens" + +# Cambiare l'attributo condiviso +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Chiamare il metodo condiviso +Human.grunt() # => "*grunt*" + +# Aggiorna la proprietà +i.age = 42 + +# Ritorna il valore della proprietà +i.age # => 42 + +# Cancella la proprietà +del i.age +i.age # => Emette un AttributeError + + +#################################################### +## 6. Moduli +#################################################### + +# Puoi importare moduli +import math +print math.sqrt(16) # => 4.0 + +# Puoi ottenere specifiche funzione da un modulo +from math import ceil, floor +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 + +# Puoi importare tutte le funzioni da un modulo +# Attenzione: questo non è raccomandato +from math import * + +# Puoi abbreviare i nomi dei moduli +import math as m +math.sqrt(16) == m.sqrt(16) # => True +# puoi anche verificare che le funzioni sono equivalenti +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True + +# I moduli di Python sono normali file python. Ne puoi +# scrivere di tuoi ed importarli. Il nome del modulo +# è lo stesso del nome del file. + +# Potete scoprire quali funzioni e attributi +# definiscono un modulo +import math +dir(math) + +# Se nella cartella corrente hai uno script chiamato math.py, +# Python caricherà quello invece del modulo math. +# Questo succede perchè la cartella corrente ha priorità +# sulle librerie standard di Python + + +#################################################### +## 7. Avanzate +#################################################### + +# Generatori +# Un generatore appunto "genera" valori solo quando vengono richiesti, +# invece di memorizzarli tutti subito fin dall'inizio + +# Il metodo seguente (che NON è un generatore) raddoppia tutti i valori e li memorizza +# dentro `double_arr`. Se gli oggetti iterabili sono grandi, il vettore risultato +# potrebbe diventare enorme! +def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + +# Eseguendo il seguente codice, noi andiamo a raddoppiare prima tutti i valori, e poi +# li ritorniamo tutti e andiamo a controllare la condizione +for value in double_numbers(range(1000000)): # `test_senza_generatore` + print value + if value > 5: + break + +# Invece, potremmo usare un generatore per "generare" il valore raddoppiato non +# appena viene richiesto +def double_numbers_generator(iterable): + for i in iterable: + yield i + i + +# Utilizzando lo stesso test di prima, stavolta però con un generatore, ci permette +# di iterare sui valori e raddoppiarli uno alla volta, non appena vengono richiesti dalla +# logica del programma. Per questo, non appena troviamo un valore > 5, usciamo dal ciclo senza +# bisogno di raddoppiare la maggior parte dei valori del range (MOLTO PIU VELOCE!) +for value in double_numbers_generator(xrange(1000000)): # `test_generatore` + print value + if value > 5: + break + +# Nota: hai notato l'uso di `range` in `test_senza_generatore` e `xrange` in `test_generatore`? +# Proprio come `double_numbers_generator` è la versione col generatore di `double_numbers` +# Abbiamo `xrange` come versione col generatore di `range` +# `range` ritorna un array di 1000000 elementi +# `xrange` invece genera 1000000 valori quando lo richiediamo/iteriamo su di essi + +# Allo stesso modo della comprensione delle liste, puoi creare la comprensione +# dei generatori. +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # stampa -1 -2 -3 -4 -5 + +# Puoi anche fare il cast diretto di una comprensione di generatori ad una lista. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# Decoratori +# in questo esempio beg include say +# Beg chiamerà say. Se say_please è True allora cambierà il messaggio +# ritornato +from functools import wraps + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Per favore! Sono povero :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Puoi comprarmi una birra?" + return msg, say_please + + +print say() # Puoi comprarmi una birra? +print say(say_please=True) # Puoi comprarmi una birra? Per favore! Sono povero :( +``` + +## Pronto per qualcosa di più? + +### Gratis Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [LearnPython](http://www.learnpython.org/) +* [Fullstack Python](https://www.fullstackpython.com/) + +### Libri cartacei + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/ko-kr/python-kr.html.markdown b/ko-kr/python-kr.html.markdown deleted file mode 100644 index 0145754d..00000000 --- a/ko-kr/python-kr.html.markdown +++ /dev/null @@ -1,484 +0,0 @@ ---- -language: python -category: language -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -filename: learnpython-ko.py -translators: - - ["wikibook", "http://wikibook.co.kr"] -lang: ko-kr ---- - -파이썬은 귀도 반 로섬이 90년대에 만들었습니다. 파이썬은 현존하는 널리 사용되는 언어 중 하나입니다. -저는 문법적 명료함에 반해 파이썬을 사랑하게 됐습니다. 파이썬은 기본적으로 실행 가능한 의사코드입니다. - -피드백 주시면 정말 감사하겠습니다! [@louiedinh](http://twitter.com/louiedinh)나 -louiedinh [at] [구글의 이메일 서비스]를 통해 저에게 연락하시면 됩니다. - -참고: 이 글은 구체적으로 파이썬 2.7에 해당하는 내용을 담고 있습니다만 -파이썬 2.x에도 적용할 수 있을 것입니다. 파이썬 3을 다룬 튜토리얼도 곧 나올 테니 기대하세요! - -```python -# 한 줄짜리 주석은 해시로 시작합니다. -""" 여러 줄 문자열은 "를 세 개 써서 시작할 수 있고, - 주석으로 자주 사용됩니다. -""" - -#################################################### -## 1. 기본 자료형과 연산자 -#################################################### - -# 숫자 -3 #=> 3 - -# 수학 연산은 예상하신 대로입니다. -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 - -# 나눗셈은 약간 까다롭습니다. 정수로 나눈 다음 결과값을 자동으로 내림합니다. -5 / 2 #=> 2 - -# 나눗셈 문제를 해결하려면 float에 대해 알아야 합니다. -2.0 # 이것이 float입니다. -11.0 / 4.0 #=> 2.75 훨씬 낫네요 - -# 괄호를 이용해 연산자 우선순위를 지정합니다. -(1 + 3) * 2 #=> 8 - -# 불린(Boolean) 값은 기본형입니다. -True -False - -# not을 이용해 부정합니다. -not True #=> False -not False #=> True - -# 동일성 연산자는 ==입니다. -1 == 1 #=> True -2 == 1 #=> False - -# 불일치 연산자는 !=입니다. -1 != 1 #=> False -2 != 1 #=> True - -# 그밖의 비교 연산자는 다음과 같습니다. -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True - -# 비교 연산을 연결할 수도 있습니다! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False - -# 문자열은 "나 '로 생성합니다. -"This is a string." -'This is also a string.' - -# 문자열도 연결할 수 있습니다! -"Hello " + "world!" #=> "Hello world!" - -# 문자열은 문자로 구성된 리스트로 간주할 수 있습니다. -"This is a string"[0] #=> 'T' - -# %는 다음과 같이 문자열을 형식화하는 데 사용할 수 있습니다: -"%s can be %s" % ("strings", "interpolated") - -# 문자열을 형식화하는 새로운 방법은 format 메서드를 이용하는 것입니다. -# 이 메서드를 이용하는 방법이 더 선호됩니다. -"{0} can be {1}".format("strings", "formatted") -# 자릿수를 세기 싫다면 키워드를 이용해도 됩니다. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") - -# None은 객체입니다. -None #=> None - -# 객체와 None을 비교할 때는 동일성 연산자인 `==`를 사용해서는 안 됩니다. -# 대신 `is`를 사용하세요. -"etc" is None #=> False -None is None #=> True - -# 'is' 연산자는 객체의 식별자를 검사합니다. -# 기본형 값을 다룰 때는 이 연산자가 그다지 유용하지 않지만 -# 객체를 다룰 때는 매우 유용합니다. - -# None, 0, 빈 문자열/리스트는 모두 False로 평가됩니다. -# 그밖의 다른 값은 모두 True입니다 -0 == False #=> True -"" == False #=> True - - -#################################################### -## 2. 변수와 컬렉션 -#################################################### - -# 뭔가를 출력하는 것은 상당히 쉽습니다. -print "I'm Python. Nice to meet you!" - - -# 변수에 값을 할당하기 전에 변수를 반드시 선언하지 않아도 됩니다. -some_var = 5 # 명명관례는 '밑줄이_포함된_소문자'입니다. -some_var #=> 5 - -# 미할당된 변수에 접근하면 예외가 발생합니다. -# 예외 처리에 관해서는 '제어 흐름'을 참고하세요. -some_other_var # 이름 오류가 발생 - -# 표현식으로도 사용할 수 있습니다. -"yahoo!" if 3 > 2 else 2 #=> "yahoo!" - -# 리스트는 순차 항목을 저장합니다. -li = [] -# 미리 채워진 리스트로 시작할 수도 있습니다. -other_li = [4, 5, 6] - -# append를 이용해 리스트 끝에 항목을 추가합니다. -li.append(1) #li는 이제 [1]입니다. -li.append(2) #li는 이제 [1, 2]입니다. -li.append(4) #li는 이제 [1, 2, 4]입니다. -li.append(3) #li는 이제 [1, 2, 4, 3]입니다. -# pop을 이용해 끝에서부터 항목을 제거합니다. -li.pop() #=> 3이 반환되고 li는 이제 [1, 2, 4]입니다. -# 다시 넣어봅시다 -li.append(3) # li는 이제 다시 [1, 2, 4, 3]가 됩니다. - -# 배열에서 했던 것처럼 리스트에도 접근할 수 있습니다. -li[0] #=> 1 -# 마지막 요소를 봅시다. -li[-1] #=> 3 - -# 범위를 벗어나서 접근하면 IndexError가 발생합니다. -li[4] # IndexError가 발생 - -# 슬라이스 문법을 통해 범위를 지정해서 값을 조회할 수 있습니다. -# (이 문법을 통해 간편하게 범위를 지정할 수 있습니다.) -li[1:3] #=> [2, 4] -# 앞부분을 생략합니다. -li[2:] #=> [4, 3] -# 끝부분을 생략합니다. -li[:3] #=> [1, 2, 4] - -# del로 임의의 요소를 제거할 수 있습니다. -del li[2] # li is now [1, 2, 3] - -# 리스트를 추가할 수도 있습니다. -li + other_li #=> [1, 2, 3, 4, 5, 6] - 참고: li와 other_li는 그대로 유지됩니다. - -# extend로 리스트를 연결합니다. -li.extend(other_li) # 이제 li는 [1, 2, 3, 4, 5, 6]입니다. - -# in으로 리스트 안에서 특정 요소가 존재하는지 확인합니다. -1 in li #=> True - -# len으로 길이를 검사합니다. -len(li) #=> 6 - -# 튜플은 리스트와 비슷하지만 불변성을 띱니다. -tup = (1, 2, 3) -tup[0] #=> 1 -tup[0] = 3 # TypeError가 발생 - -# 튜플에 대해서도 리스트에서 할 수 있는 일들을 모두 할 수 있습니다. -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True - -# 튜플(또는 리스트)을 변수로 풀 수 있습니다. -a, b, c = (1, 2, 3) # 이제 a는 1, b는 2, c는 3입니다 -# 괄호를 빼면 기본적으로 튜플이 만들어집니다. -d, e, f = 4, 5, 6 -# 이제 두 값을 바꾸는 게 얼마나 쉬운지 확인해 보세요. -e, d = d, e # 이제 d는 5이고 e는 4입니다. - -# 딕셔너리는 매핑을 저장합니다. -empty_dict = {} -# 다음은 값을 미리 채운 딕셔너리입니다. -filled_dict = {"one": 1, "two": 2, "three": 3} - -# []를 이용해 값을 조회합니다. -filled_dict["one"] #=> 1 - -# 모든 키를 리스트로 구합니다. -filled_dict.keys() #=> ["three", "two", "one"] -# 참고 - 딕셔너리 키의 순서는 보장되지 않습니다. -# 따라서 결과가 이와 정확히 일치하지 않을 수도 있습니다. - -# 모든 값을 리스트로 구합니다. -filled_dict.values() #=> [3, 2, 1] -# 참고 - 키 순서와 관련해서 위에서 설명한 내용과 같습니다. - -# in으로 딕셔너리 안에 특정 키가 존재하는지 확인합니다. -"one" in filled_dict #=> True -1 in filled_dict #=> False - -# 존재하지 않는 키를 조회하면 KeyError가 발생합니다. -filled_dict["four"] # KeyError - -# get 메서드를 이용하면 KeyError가 발생하지 않습니다. -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None -# get 메서드는 값이 누락된 경우 기본 인자를 지원합니다. -filled_dict.get("one", 4) #=> 1 -filled_dict.get("four", 4) #=> 4 - -# setdefault 메서드는 딕셔너리에 새 키-값 쌍을 추가하는 안전한 방법입니다. -filled_dict.setdefault("five", 5) #filled_dict["five"]는 5로 설정됩니다. -filled_dict.setdefault("five", 6) #filled_dict["five"]는 여전히 5입니다. - - -# 세트는 집합을 저장합니다. -empty_set = set() -# 다수의 값으로 세트를 초기화합니다. -some_set = set([1,2,2,3,4]) # 이제 some_set는 set([1, 2, 3, 4])입니다. - -# 파이썬 2.7부터는 {}를 세트를 선언하는 데 사용할 수 있습니다. -filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} - -# 세트에 항목을 추가합니다. -filled_set.add(5) # 이제 filled_set는 {1, 2, 3, 4, 5}입니다. - -# &을 이용해 교집합을 만듭니다. -other_set = {3, 4, 5, 6} -filled_set & other_set #=> {3, 4, 5} - -# |를 이용해 합집합을 만듭니다. -filled_set | other_set #=> {1, 2, 3, 4, 5, 6} - -# -를 이용해 차집합을 만듭니다. -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# in으로 세트 안에 특정 요소가 존재하는지 검사합니다. -2 in filled_set #=> True -10 in filled_set #=> False - - -#################################################### -## 3. 제어 흐름 -#################################################### - -# 변수를 만들어 봅시다. -some_var = 5 - -# 다음은 if 문입니다. 파이썬에서는 들여쓰기가 대단히 중요합니다! -# 다음 코드를 실행하면 "some_var is smaller than 10"가 출력됩니다. -if some_var > 10: - print "some_var is totally bigger than 10." -elif some_var < 10: # elif 절은 선택사항입니다. - print "some_var is smaller than 10." -else: # 이 부분 역시 선택사항입니다. - print "some_var is indeed 10." - - -""" -for 루프는 리스트를 순회합니다. -아래 코드는 다음과 같은 내용을 출력합니다: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # %로 형식화된 문자열에 값을 채워넣을 수 있습니다. - print "%s is a mammal" % animal - -""" -`range(number)`는 숫자 리스트를 반환합니다. -이때 숫자 리스트의 범위는 0에서 지정한 숫자까지입니다. -아래 코드는 다음과 같은 내용을 출력합니다: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -while 루프는 조건이 더는 충족되지 않을 때까지 진행됩니다. -prints: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # x = x + 1의 축약형 - -# try/except 블록을 이용한 예외 처리 - -# 파이썬 2.6 및 상위 버전에서 동작하는 코드 -try: - # raise를 이용해 오류를 발생시킵니다 - raise IndexError("This is an index error") -except IndexError as e: - pass # pass는 단순 no-op 연산입니다. 보통 이곳에 복구 코드를 작성합니다. - - -#################################################### -## 4. 함수 -#################################################### - -# 새 함수를 만들 때 def를 사용합니다. -def add(x, y): - print "x is %s and y is %s" % (x, y) - return x + y # return 문을 이용해 값을 반환합니다. - -# 매개변수를 전달하면서 함수를 호출 -add(5, 6) #=> "x is 5 and y is 6"가 출력되고 11이 반환됨 - -# 함수를 호출하는 또 다른 방법은 키워드 인자를 지정하는 방법입니다. -add(y=6, x=5) # 키워드 인자는 순서에 구애받지 않습니다. - -# 위치 기반 인자를 임의 개수만큼 받는 함수를 정의할 수 있습니다. -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# 키워드 인자를 임의 개수만큼 받는 함수 또한 정의할 수 있습니다. -def keyword_args(**kwargs): - return kwargs - -# 이 함수를 호출해서 어떤 일이 일어나는지 확인해 봅시다. -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} - -# 원한다면 한 번에 두 가지 종류의 인자를 모두 받는 함수를 정의할 수도 있습니다. -def all_the_args(*args, **kwargs): - print args - print kwargs -""" -all_the_args(1, 2, a=3, b=4)를 실행하면 다음과 같은 내용이 출력됩니다: - (1, 2) - {"a": 3, "b": 4} -""" - -# 함수를 호출할 때 varargs/kwargs와 반대되는 일을 할 수 있습니다! -# *를 이용해 튜플을 확장하고 **를 이용해 kwargs를 확장합니다. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # foo(1, 2, 3, 4)와 같음 -all_the_args(**kwargs) # foo(a=3, b=4)와 같음 -all_the_args(*args, **kwargs) # foo(1, 2, 3, 4, a=3, b=4)와 같음 - -# 파이썬에는 일급 함수가 있습니다 -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) #=> 13 - -# 게다가 익명 함수도 있습니다. -(lambda x: x > 2)(3) #=> True - -# 내장된 고차 함수(high order function)도 있습니다. -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# 맵과 필터에 리스트 조건 제시법(list comprehensions)을 사용할 수 있습니다. -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] - -#################################################### -## 5. 클래스 -#################################################### - -# 클래스를 하나 만들기 위해 특정 객체의 하위 클래스를 만들 수 있습니다. -class Human(object): - - # 클래스 속성은 이 클래스의 모든 인스턴스에서 공유합니다. - species = "H. sapiens" - - # 기본 초기화자 - def __init__(self, name): - # 인자를 인스턴스의 name 속성에 할당합니다. - self.name = name - - # 모든 인스턴스 메서드에서는 self를 첫 번째 인자로 받습니다. - def say(self, msg): - return "%s: %s" % (self.name, msg) - - # 클래스 메서드는 모든 인스턴스에서 공유합니다. - # 클래스 메서드는 호출하는 클래스를 첫 번째 인자로 호출됩니다. - @classmethod - def get_species(cls): - return cls.species - - # 정적 메서드는 클래스나 인스턴스 참조 없이도 호출할 수 있습니다. - @staticmethod - def grunt(): - return "*grunt*" - - -# 클래스 인스턴스화 -i = Human(name="Ian") -print i.say("hi") # "Ian: hi"가 출력됨 - -j = Human("Joel") -print j.say("hello") # "Joel: hello"가 출력됨 - -# 클래스 메서드를 호출 -i.get_species() #=> "H. sapiens" - -# 공유 속성을 변경 -Human.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" - -# 정적 메서드를 호출 -Human.grunt() #=> "*grunt*" - - -#################################################### -## 6. 모듈 -#################################################### - -# 다음과 같이 모듈을 임포트할 수 있습니다. -import math -print math.sqrt(16) #=> 4.0 - -# 모듈의 특정 함수를 호출할 수 있습니다. -from math import ceil, floor -print ceil(3.7) #=> 4.0 -print floor(3.7) #=> 3.0 - -# 모듈의 모든 함수를 임포트할 수 있습니다. -# Warning: this is not recommended -from math import * - -# 모듈 이름을 축약해서 쓸 수 있습니다. -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# 파이썬 모듈은 평범한 파이썬 파일에 불과합니다. -# 직접 모듈을 작성해서 그것들을 임포트할 수 있습니다. -# 모듈의 이름은 파일의 이름과 같습니다. - -# 다음과 같은 코드로 모듈을 구성하는 함수와 속성을 확인할 수 있습니다. -import math -dir(math) - - -``` - -## 더 배울 준비가 되셨습니까? - -### 무료 온라인 참고자료 - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2.6/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) - -### 파이썬 관련 도서 - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/ko-kr/pythonlegacy-kr.html.markdown b/ko-kr/pythonlegacy-kr.html.markdown new file mode 100644 index 00000000..0145754d --- /dev/null +++ b/ko-kr/pythonlegacy-kr.html.markdown @@ -0,0 +1,484 @@ +--- +language: python +category: language +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +filename: learnpython-ko.py +translators: + - ["wikibook", "http://wikibook.co.kr"] +lang: ko-kr +--- + +파이썬은 귀도 반 로섬이 90년대에 만들었습니다. 파이썬은 현존하는 널리 사용되는 언어 중 하나입니다. +저는 문법적 명료함에 반해 파이썬을 사랑하게 됐습니다. 파이썬은 기본적으로 실행 가능한 의사코드입니다. + +피드백 주시면 정말 감사하겠습니다! [@louiedinh](http://twitter.com/louiedinh)나 +louiedinh [at] [구글의 이메일 서비스]를 통해 저에게 연락하시면 됩니다. + +참고: 이 글은 구체적으로 파이썬 2.7에 해당하는 내용을 담고 있습니다만 +파이썬 2.x에도 적용할 수 있을 것입니다. 파이썬 3을 다룬 튜토리얼도 곧 나올 테니 기대하세요! + +```python +# 한 줄짜리 주석은 해시로 시작합니다. +""" 여러 줄 문자열은 "를 세 개 써서 시작할 수 있고, + 주석으로 자주 사용됩니다. +""" + +#################################################### +## 1. 기본 자료형과 연산자 +#################################################### + +# 숫자 +3 #=> 3 + +# 수학 연산은 예상하신 대로입니다. +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# 나눗셈은 약간 까다롭습니다. 정수로 나눈 다음 결과값을 자동으로 내림합니다. +5 / 2 #=> 2 + +# 나눗셈 문제를 해결하려면 float에 대해 알아야 합니다. +2.0 # 이것이 float입니다. +11.0 / 4.0 #=> 2.75 훨씬 낫네요 + +# 괄호를 이용해 연산자 우선순위를 지정합니다. +(1 + 3) * 2 #=> 8 + +# 불린(Boolean) 값은 기본형입니다. +True +False + +# not을 이용해 부정합니다. +not True #=> False +not False #=> True + +# 동일성 연산자는 ==입니다. +1 == 1 #=> True +2 == 1 #=> False + +# 불일치 연산자는 !=입니다. +1 != 1 #=> False +2 != 1 #=> True + +# 그밖의 비교 연산자는 다음과 같습니다. +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# 비교 연산을 연결할 수도 있습니다! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# 문자열은 "나 '로 생성합니다. +"This is a string." +'This is also a string.' + +# 문자열도 연결할 수 있습니다! +"Hello " + "world!" #=> "Hello world!" + +# 문자열은 문자로 구성된 리스트로 간주할 수 있습니다. +"This is a string"[0] #=> 'T' + +# %는 다음과 같이 문자열을 형식화하는 데 사용할 수 있습니다: +"%s can be %s" % ("strings", "interpolated") + +# 문자열을 형식화하는 새로운 방법은 format 메서드를 이용하는 것입니다. +# 이 메서드를 이용하는 방법이 더 선호됩니다. +"{0} can be {1}".format("strings", "formatted") +# 자릿수를 세기 싫다면 키워드를 이용해도 됩니다. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") + +# None은 객체입니다. +None #=> None + +# 객체와 None을 비교할 때는 동일성 연산자인 `==`를 사용해서는 안 됩니다. +# 대신 `is`를 사용하세요. +"etc" is None #=> False +None is None #=> True + +# 'is' 연산자는 객체의 식별자를 검사합니다. +# 기본형 값을 다룰 때는 이 연산자가 그다지 유용하지 않지만 +# 객체를 다룰 때는 매우 유용합니다. + +# None, 0, 빈 문자열/리스트는 모두 False로 평가됩니다. +# 그밖의 다른 값은 모두 True입니다 +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. 변수와 컬렉션 +#################################################### + +# 뭔가를 출력하는 것은 상당히 쉽습니다. +print "I'm Python. Nice to meet you!" + + +# 변수에 값을 할당하기 전에 변수를 반드시 선언하지 않아도 됩니다. +some_var = 5 # 명명관례는 '밑줄이_포함된_소문자'입니다. +some_var #=> 5 + +# 미할당된 변수에 접근하면 예외가 발생합니다. +# 예외 처리에 관해서는 '제어 흐름'을 참고하세요. +some_other_var # 이름 오류가 발생 + +# 표현식으로도 사용할 수 있습니다. +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# 리스트는 순차 항목을 저장합니다. +li = [] +# 미리 채워진 리스트로 시작할 수도 있습니다. +other_li = [4, 5, 6] + +# append를 이용해 리스트 끝에 항목을 추가합니다. +li.append(1) #li는 이제 [1]입니다. +li.append(2) #li는 이제 [1, 2]입니다. +li.append(4) #li는 이제 [1, 2, 4]입니다. +li.append(3) #li는 이제 [1, 2, 4, 3]입니다. +# pop을 이용해 끝에서부터 항목을 제거합니다. +li.pop() #=> 3이 반환되고 li는 이제 [1, 2, 4]입니다. +# 다시 넣어봅시다 +li.append(3) # li는 이제 다시 [1, 2, 4, 3]가 됩니다. + +# 배열에서 했던 것처럼 리스트에도 접근할 수 있습니다. +li[0] #=> 1 +# 마지막 요소를 봅시다. +li[-1] #=> 3 + +# 범위를 벗어나서 접근하면 IndexError가 발생합니다. +li[4] # IndexError가 발생 + +# 슬라이스 문법을 통해 범위를 지정해서 값을 조회할 수 있습니다. +# (이 문법을 통해 간편하게 범위를 지정할 수 있습니다.) +li[1:3] #=> [2, 4] +# 앞부분을 생략합니다. +li[2:] #=> [4, 3] +# 끝부분을 생략합니다. +li[:3] #=> [1, 2, 4] + +# del로 임의의 요소를 제거할 수 있습니다. +del li[2] # li is now [1, 2, 3] + +# 리스트를 추가할 수도 있습니다. +li + other_li #=> [1, 2, 3, 4, 5, 6] - 참고: li와 other_li는 그대로 유지됩니다. + +# extend로 리스트를 연결합니다. +li.extend(other_li) # 이제 li는 [1, 2, 3, 4, 5, 6]입니다. + +# in으로 리스트 안에서 특정 요소가 존재하는지 확인합니다. +1 in li #=> True + +# len으로 길이를 검사합니다. +len(li) #=> 6 + +# 튜플은 리스트와 비슷하지만 불변성을 띱니다. +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # TypeError가 발생 + +# 튜플에 대해서도 리스트에서 할 수 있는 일들을 모두 할 수 있습니다. +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# 튜플(또는 리스트)을 변수로 풀 수 있습니다. +a, b, c = (1, 2, 3) # 이제 a는 1, b는 2, c는 3입니다 +# 괄호를 빼면 기본적으로 튜플이 만들어집니다. +d, e, f = 4, 5, 6 +# 이제 두 값을 바꾸는 게 얼마나 쉬운지 확인해 보세요. +e, d = d, e # 이제 d는 5이고 e는 4입니다. + +# 딕셔너리는 매핑을 저장합니다. +empty_dict = {} +# 다음은 값을 미리 채운 딕셔너리입니다. +filled_dict = {"one": 1, "two": 2, "three": 3} + +# []를 이용해 값을 조회합니다. +filled_dict["one"] #=> 1 + +# 모든 키를 리스트로 구합니다. +filled_dict.keys() #=> ["three", "two", "one"] +# 참고 - 딕셔너리 키의 순서는 보장되지 않습니다. +# 따라서 결과가 이와 정확히 일치하지 않을 수도 있습니다. + +# 모든 값을 리스트로 구합니다. +filled_dict.values() #=> [3, 2, 1] +# 참고 - 키 순서와 관련해서 위에서 설명한 내용과 같습니다. + +# in으로 딕셔너리 안에 특정 키가 존재하는지 확인합니다. +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# 존재하지 않는 키를 조회하면 KeyError가 발생합니다. +filled_dict["four"] # KeyError + +# get 메서드를 이용하면 KeyError가 발생하지 않습니다. +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# get 메서드는 값이 누락된 경우 기본 인자를 지원합니다. +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# setdefault 메서드는 딕셔너리에 새 키-값 쌍을 추가하는 안전한 방법입니다. +filled_dict.setdefault("five", 5) #filled_dict["five"]는 5로 설정됩니다. +filled_dict.setdefault("five", 6) #filled_dict["five"]는 여전히 5입니다. + + +# 세트는 집합을 저장합니다. +empty_set = set() +# 다수의 값으로 세트를 초기화합니다. +some_set = set([1,2,2,3,4]) # 이제 some_set는 set([1, 2, 3, 4])입니다. + +# 파이썬 2.7부터는 {}를 세트를 선언하는 데 사용할 수 있습니다. +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# 세트에 항목을 추가합니다. +filled_set.add(5) # 이제 filled_set는 {1, 2, 3, 4, 5}입니다. + +# &을 이용해 교집합을 만듭니다. +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# |를 이용해 합집합을 만듭니다. +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# -를 이용해 차집합을 만듭니다. +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# in으로 세트 안에 특정 요소가 존재하는지 검사합니다. +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. 제어 흐름 +#################################################### + +# 변수를 만들어 봅시다. +some_var = 5 + +# 다음은 if 문입니다. 파이썬에서는 들여쓰기가 대단히 중요합니다! +# 다음 코드를 실행하면 "some_var is smaller than 10"가 출력됩니다. +if some_var > 10: + print "some_var is totally bigger than 10." +elif some_var < 10: # elif 절은 선택사항입니다. + print "some_var is smaller than 10." +else: # 이 부분 역시 선택사항입니다. + print "some_var is indeed 10." + + +""" +for 루프는 리스트를 순회합니다. +아래 코드는 다음과 같은 내용을 출력합니다: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # %로 형식화된 문자열에 값을 채워넣을 수 있습니다. + print "%s is a mammal" % animal + +""" +`range(number)`는 숫자 리스트를 반환합니다. +이때 숫자 리스트의 범위는 0에서 지정한 숫자까지입니다. +아래 코드는 다음과 같은 내용을 출력합니다: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +while 루프는 조건이 더는 충족되지 않을 때까지 진행됩니다. +prints: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # x = x + 1의 축약형 + +# try/except 블록을 이용한 예외 처리 + +# 파이썬 2.6 및 상위 버전에서 동작하는 코드 +try: + # raise를 이용해 오류를 발생시킵니다 + raise IndexError("This is an index error") +except IndexError as e: + pass # pass는 단순 no-op 연산입니다. 보통 이곳에 복구 코드를 작성합니다. + + +#################################################### +## 4. 함수 +#################################################### + +# 새 함수를 만들 때 def를 사용합니다. +def add(x, y): + print "x is %s and y is %s" % (x, y) + return x + y # return 문을 이용해 값을 반환합니다. + +# 매개변수를 전달하면서 함수를 호출 +add(5, 6) #=> "x is 5 and y is 6"가 출력되고 11이 반환됨 + +# 함수를 호출하는 또 다른 방법은 키워드 인자를 지정하는 방법입니다. +add(y=6, x=5) # 키워드 인자는 순서에 구애받지 않습니다. + +# 위치 기반 인자를 임의 개수만큼 받는 함수를 정의할 수 있습니다. +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# 키워드 인자를 임의 개수만큼 받는 함수 또한 정의할 수 있습니다. +def keyword_args(**kwargs): + return kwargs + +# 이 함수를 호출해서 어떤 일이 일어나는지 확인해 봅시다. +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# 원한다면 한 번에 두 가지 종류의 인자를 모두 받는 함수를 정의할 수도 있습니다. +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4)를 실행하면 다음과 같은 내용이 출력됩니다: + (1, 2) + {"a": 3, "b": 4} +""" + +# 함수를 호출할 때 varargs/kwargs와 반대되는 일을 할 수 있습니다! +# *를 이용해 튜플을 확장하고 **를 이용해 kwargs를 확장합니다. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # foo(1, 2, 3, 4)와 같음 +all_the_args(**kwargs) # foo(a=3, b=4)와 같음 +all_the_args(*args, **kwargs) # foo(1, 2, 3, 4, a=3, b=4)와 같음 + +# 파이썬에는 일급 함수가 있습니다 +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# 게다가 익명 함수도 있습니다. +(lambda x: x > 2)(3) #=> True + +# 내장된 고차 함수(high order function)도 있습니다. +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# 맵과 필터에 리스트 조건 제시법(list comprehensions)을 사용할 수 있습니다. +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#################################################### +## 5. 클래스 +#################################################### + +# 클래스를 하나 만들기 위해 특정 객체의 하위 클래스를 만들 수 있습니다. +class Human(object): + + # 클래스 속성은 이 클래스의 모든 인스턴스에서 공유합니다. + species = "H. sapiens" + + # 기본 초기화자 + def __init__(self, name): + # 인자를 인스턴스의 name 속성에 할당합니다. + self.name = name + + # 모든 인스턴스 메서드에서는 self를 첫 번째 인자로 받습니다. + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # 클래스 메서드는 모든 인스턴스에서 공유합니다. + # 클래스 메서드는 호출하는 클래스를 첫 번째 인자로 호출됩니다. + @classmethod + def get_species(cls): + return cls.species + + # 정적 메서드는 클래스나 인스턴스 참조 없이도 호출할 수 있습니다. + @staticmethod + def grunt(): + return "*grunt*" + + +# 클래스 인스턴스화 +i = Human(name="Ian") +print i.say("hi") # "Ian: hi"가 출력됨 + +j = Human("Joel") +print j.say("hello") # "Joel: hello"가 출력됨 + +# 클래스 메서드를 호출 +i.get_species() #=> "H. sapiens" + +# 공유 속성을 변경 +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# 정적 메서드를 호출 +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. 모듈 +#################################################### + +# 다음과 같이 모듈을 임포트할 수 있습니다. +import math +print math.sqrt(16) #=> 4.0 + +# 모듈의 특정 함수를 호출할 수 있습니다. +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# 모듈의 모든 함수를 임포트할 수 있습니다. +# Warning: this is not recommended +from math import * + +# 모듈 이름을 축약해서 쓸 수 있습니다. +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# 파이썬 모듈은 평범한 파이썬 파일에 불과합니다. +# 직접 모듈을 작성해서 그것들을 임포트할 수 있습니다. +# 모듈의 이름은 파일의 이름과 같습니다. + +# 다음과 같은 코드로 모듈을 구성하는 함수와 속성을 확인할 수 있습니다. +import math +dir(math) + + +``` + +## 더 배울 준비가 되셨습니까? + +### 무료 온라인 참고자료 + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### 파이썬 관련 도서 + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/pl-pl/python-pl.html.markdown b/pl-pl/python-pl.html.markdown deleted file mode 100644 index 222f753f..00000000 --- a/pl-pl/python-pl.html.markdown +++ /dev/null @@ -1,640 +0,0 @@ ---- -name: python -category: language -language: python -filename: learnpython-pl.py -contributors: - - ["Louie Dinh", "http://ldinh.ca"] - - ["Amin Bandali", "http://aminbandali.com"] - - ["Andre Polykanine", "https://github.com/Oire"] -translators: - - ["Dominik Krzemiński", "https://github.com/dokato"] -lang: pl-pl ---- - -Python został opracowany przez Guido Van Rossuma na początku lat 90-tych. -Obecnie jest jednym z najbardziej popularnych języków programowania. -Zakochałem się w Pythonie dzięki porządkowi, jaki utrzymywany jest w kodzie. -To po prostu wykonywalny pseudokod. - -Zapraszam do kontaktu. Złapiecie nas na: -- kontakt polski: raymon92 [at] [google's email service] -- kontakt angielski: [@louiedinh](http://twitter.com/louiedinh) lub louiedinh [at] [google's email service] - -Uwaga: Ten artykuł odnosi się do wersji Pythona 2.7, ale powinien -działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stronie głównej. - -```python -# -*- coding: utf-8 -*- - -# Pojedyncze komentarze oznaczamy takim symbolem. - -""" Wielolinijkowe napisy zapisywane są przy użyciu - potrójnych cudzysłowów i często - wykorzystywane są jako komentarze. -""" - -#################################################### -## 1. Podstawowe typy danych i operatory -#################################################### - -# Liczby to liczby -3 # => 3 - -# Matematyka jest intuicyjna -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7 - -# Dzielenie może być kłopotliwe. Poniższe działanie to dzielenie -# całkowitoliczbowe(int) i wynik jest automatycznie zaokrąglany. -5 / 2 # => 2 - -# Aby to naprawić, musimy powiedzieć nieco o liczbach zmiennoprzecinkowych. -2.0 # To liczba zmiennoprzecinkowa, tzw. float -11.0 / 4.0 # => 2.75 ahhh...znacznie lepiej - -# Wynik dzielenia całkowitoliczbowego jest obcinany dla liczb -# dodatnich i ujemnych. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # działa też na floatach --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Operator modulo - wyznaczanie reszty z dzielenia -7 % 3 # => 1 - -# Potęgowanie (x do potęgi y-tej) -2**4 # => 16 - -# Wymuszanie pierwszeństwa w nawiasach -(1 + 3) * 2 # => 8 - -# Operacje logiczne -# Zauważ, że przy "and" i "or" trzeba zwracać uwagę na rozmiar liter -True and False #=> False # Fałsz -False or True #=> True # Prawda - -# Zauważ, że operatorów logicznych można używać z intami -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -k1 == True #=> True - -# aby zanegować, użyj "not" -not True # => False -not False # => True - -# Równość == -1 == 1 # => True -2 == 1 # => False - -# Nierówność != -1 != 1 # => False -2 != 1 # => True - -# Więcej porównań -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Porównania można układać w łańcuch! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# Napisy (typ string) tworzone są przy użyciu cudzysłowów " lub ' -"Jestem napisem." -'Ja też jestem napisem.' - -# Napisy można dodawać! -"Witaj " + "świecie!" # => "Witaj świecie!" - -# ... a nawet mnożyć -"Hej" * 3 # => "HejHejHej" - -# Napis może być traktowany jako lista znaków -"To napis"[0] # => 'T' - -# % może być używane do formatowania napisów: -"%s są %s" % ("napisy", "fajne") - -# Jednak nowszym sposobem formatowania jest metoda "format". -# Ta metoda jest obecnie polecana: -"{0} są {1}".format("napisy", "fajne") -# Jeśli nie chce ci się liczyć, użyj słów kluczowych. -"{imie} chce zjeść {jadlo}".format(imie="Bob", jadlo="makaron") - -# None jest obiektem -None # => None - -# Nie używaj "==" w celu porównania obiektów z None -# Zamiast tego użyj "is" -"etc" is None # => False -None is None # => True - -# Operator 'is' testuje identyczność obiektów. Nie jest to zbyt -# pożyteczne, gdy działamy tylko na prostych wartościach, -# ale przydaje się, gdy mamy do czynienia z obiektami. - -# None, 0 i pusty napis "" są odpowiednikami logicznego False. -# Wszystkie inne wartości są uznawane za prawdę (True) -bool(0) # => False -bool("") # => False - - -#################################################### -## 2. Zmienne i zbiory danych -#################################################### - -# Python ma instrukcję wypisującą "print" we wszystkich wersjach 2.x, ale -# została ona usunięta z wersji 3. -print "Jestem Python. Miło Cię poznać!" -# Python ma też funkcję "print" dostępną w wersjach 2.7 i 3... -# ale w 2.7 musisz dodać import (odkomentuj): -# from __future__ import print_function -print("Ja też jestem Python! ") - -# Nie trzeba deklarować zmiennych przed przypisaniem. -jakas_zmienna = 5 # Konwencja mówi: używaj małych liter i znaków podkreślenia _ -jakas_zmienna # => 5 - -# Próba dostępu do niezadeklarowanej zmiennej da błąd. -# Przejdź do sekcji Obsługa wyjątków, aby dowiedzieć się więcej... -inna_zmienna # Wyrzuca nazwę błędu - -# "if" może być użyte jako wyrażenie -"huraaa!" if 3 > 2 else 2 # => "huraaa!" - -# Listy: -li = [] -# Możesz zacząć od wypełnionej listy -inna_li = [4, 5, 6] - -# Dodaj na koniec, używając "append" -li.append(1) # li to teraz [1] -li.append(2) # li to teraz [1, 2] -li.append(4) # li to teraz [1, 2, 4] -li.append(3) # li to teraz [1, 2, 4, 3] -# Usuwanie z konca da "pop" -li.pop() # => 3 a li stanie się [1, 2, 4] -# Dodajmy ponownie -li.append(3) # li to znowu [1, 2, 4, 3]. - -# Dostęp do list jak do każdej tablicy -li[0] # => 1 -# Aby nadpisać wcześniej wypełnione miejsca w liście, użyj znaku = -li[0] = 42 -li[0] # => 42 -li[0] = 1 # Uwaga: ustawiamy starą wartość -# Tak podglądamy ostatni element -li[-1] # => 3 - -# Jeżeli wyjdziesz poza zakres... -li[4] # ... zobaczysz IndexError - -# Możesz też tworzyć wycinki. -li[1:3] # => [2, 4] -# Bez początku -li[2:] # => [4, 3] -# Omijamy koniec -li[:3] # => [1, 2, 4] -# Wybierz co drugi -li[::2] # =>[1, 4] -# Odwróć listę -li[::-1] # => [3, 4, 2, 1] -# Użyj kombinacji powyższych aby tworzyć bardziej skomplikowane wycinki -# li[poczatek:koniec:krok] - -# Usuń element używając "del" -del li[2] # li to teraz [1, 2, 3] - -# Listy można dodawać -li + inna_li # => [1, 2, 3, 4, 5, 6] -# Uwaga: wartości oryginalnych list li i inna_li się nie zmieniają. - -# Do łączenia list użyj "extend()" -li.extend(other_li) # li to teraz [1, 2, 3, 4, 5, 6] - -# Sprawdź, czy element jest w liście używając "in" -1 in li # => True - -# "len()" pokazuje długość listy -len(li) # => 6 - - -# Krotki (tuple) są jak listy, ale nie można ich modyfikować. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # wyrzuci TypeError - -# Ale wielu akcji dla list możesz używać przy krotkach -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Można rozpakować krotki i listy do poszczególych zmiennych -a, b, c = (1, 2, 3) # a to teraz 1, b jest 2, a c to 3 -# Jeżeli zapomnisz nawiasów, automatycznie tworzone są krotki -d, e, f = 4, 5, 6 -# Popatrz jak prosto zamienić wartości -e, d = d, e # d to teraz 5 a e to 4 - - -# Słowniki są również pożyteczne -pusty_slownik = {} -# Tu tworzymy wypełniony: -pelen_slownik = {"raz": 1, "dwa": 2, "trzy": 3} - -# Podglądany wartość -pelen_slownik["one"] # => 1 - -# Wypisz wszystkie klucze, używając "keys()" -pelen_slownik.keys() # => ["trzy", "dwa", "raz"] -# Uwaga: słowniki nie zapamiętują kolejności kluczy. - -# A teraz wszystkie wartości "values()" -pelen_slownik.values() # => [3, 2, 1] -# Uwaga: to samo dotyczy wartości. - -# Sprawdzanie czy klucz występuje w słowniku za pomocą "in" -"raz" in pelen_slownik # => True -1 in pelen_slownik # => False - -# Próba dobrania się do nieistniejącego klucza da KeyError -pelen_slownik["cztery"] # KeyError - -# Użyj metody "get()", aby uniknąć błędu KeyError -pelen_slownik.get("raz") # => 1 -pelen_slownik.get("cztery") # => None -# Metoda get zwraca domyślną wartość gdy brakuje klucza -pelen_slownik.get("one", 4) # => 1 -pelen_slownik.get("cztery", 4) # => 4 -# zauważ, że pelen_slownik.get("cztery") wciąż zwraca => None -# (get nie ustawia wartości słownika) - -# przypisz wartość do klucza podobnie jak w listach -pelen_slownik["cztery"] = 4 # teraz: pelen_slownik["cztery"] => 4 - -# "setdefault()" wstawia do słownika tylko jeśli nie było klucza -pelen_slownik.setdefault("piec", 5) # pelen_slownik["piec"] daje 5 -pelen_slownik.setdefault("piec", 6) # pelen_slownik["piec"] to wciąż 5 - - -# Teraz zbiory (set) - działają jak zwykłe listy, ale bez potórzeń -pusty_zbior = set() -# Inicjalizujemy "set()" pewnymi wartościami -jakis_zbior = set([1, 2, 2, 3, 4]) # jakis_zbior to teraz set([1, 2, 3, 4]) - -# kolejność nie jest zachowana, nawet gdy wydaje się posortowane -inny_zbior = set([4, 3, 2, 2, 1]) # inny_zbior to set([1, 2, 3, 4]) - -# Od Pythona 2.7 nawiasy klamrowe {} mogą być użyte do deklarowania zbioru -pelen_zbior = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} - -# Dodaj więcej elementów przez "add()" -pelen_zbior.add(5) # pelen_zbior is now {1, 2, 3, 4, 5} - -# Znajdź przecięcie (część wspólną) zbiorów, używając & -inny_zbior = {3, 4, 5, 6} -pelen_zbior & other_set # => {3, 4, 5} - -# Suma zbiorów | -pelen_zbior | other_set # => {1, 2, 3, 4, 5, 6} - -# Różnicę zbiorów da znak - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Sprawdzanie obecności w zbiorze: "in". -2 in pelen_zbior # => True -10 in pelen_zbior # => False - - -#################################################### -## 3. Kontrola przepływu -#################################################### - -# Tworzymy zmienną jakas_zm -jakas_zm = 5 - -# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia w Pythonie są ważne! -# Poniższy kod wypisze "jakas_zm jest mniejsza niż 10" -if jakas_zm > 10: - print("jakas_zm jest wieksza niż 10") -elif some_var < 10: # Opcjonalna klauzula elif - print("jakas_zm jest mniejsza niż 10") -else: # Również opcjonalna klauzula else - print("jakas_zm jest równa 10") - - -""" -Pętla for iteruje po elementach listy, wypisując: - pies to ssak - kot to ssak - mysz to ssak -""" -for zwierze in ["pies", "kot", "mysz"]: - # Użyj metody format, aby umieścić wartość zmiennej w ciągu - print("{0} to ssak".format(zwierze)) - -""" -"range(liczba)" zwraca listę liczb -z przedziału od zera do wskazanej liczby (bez niej): - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -While to pętla, która jest wykonywana, dopóki spełniony jest warunek: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Skrót od x = x + 1 - -# Wyjątki wyłapujemy, używając try i except - -# Działa w Pythonie 2.6 i wyższych: -try: - # Użyj "raise" aby wyrzucić wyjątek - raise IndexError("To błąd indeksu") -except IndexError as e: - pass # Pass to brak reakcji na błąd. Zwykle opisujesz tutaj, jak program ma się zachować w przypadku błędu. -except (TypeError, NameError): - pass # kilka wyjątków można przechwycić jednocześnie. -else: # Opcjonalna część bloku try/except. Musi wystąpić na końcu - print "Wszystko ok!" # Zadziała tylko, gdy program nie napotka wyjatku. - - -#################################################### -## 4. Funkcje -#################################################### - -# Użyj "def", aby stworzyć nową funkcję -def dodaj(x, y): - print("x to %s, a y to %s" % (x, y)) - return x + y # słowo kluczowe return zwraca wynik działania - -# Tak wywołuje się funkcję z parametrami: -dodaj(5, 6) # => wypisze "x to 5, a y to 6" i zwróci 11 - -# Innym sposobem jest wywołanie z parametrami nazwanymi. -dodaj(y=6, x=5) # tutaj kolejność podania nie ma znaczenia. - - -# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów pozycyjnych, -# które zostaną przekazana jako krotka, pisząc w definicji funkcji "*args" -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - - -# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów -# nazwanych kwargs, które zostaną przekazane jako słownik, pisząc w definicji funkcji "**kwargs" -def keyword_args(**kwargs): - return kwargs - -# Wywołajmy to i sprawdźmy co się dzieje -keyword_args(wielka="stopa", loch="ness") # => {"wielka": "stopa", "loch": "ness"} - - -# Możesz też przyjmować jednocześnie zmienną liczbę parametrów pozycyjnych i nazwanych -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) wypisze: - (1, 2) - {"a": 3, "b": 4} -""" - -# Użyj * aby rozwinąć parametry z krotki args -# i użyj ** aby rozwinąć parametry nazwane ze słownika kwargs. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # odpowiednik foo(1, 2, 3, 4) -all_the_args(**kwargs) # odpowiednik foo(a=3, b=4) -all_the_args(*args, **kwargs) # odpowiednik foo(1, 2, 3, 4, a=3, b=4) - -# Możesz podać parametry args i kwargs do funkcji równocześnie -# przez rozwinięcie odpowiednio * i ** -def pass_all_the_args(*args, **kwargs): - all_the_args(*args, **kwargs) - print varargs(*args) - print keyword_args(**kwargs) - -# Zasięg zmiennych -x = 5 - -def setX(num): - # Lokalna zmienna x nie jest tym samym co zmienna x - x = num # => 43 - print x # => 43 - -def setGlobalX(num): - global x - print x # => 5 - x = num # globalna zmienna to teraz 6 - print x # => 6 - -setX(43) -setGlobalX(6) - -# Można tworzyć funkcje wewnętrzne i zwrócić je jako wynik -def rob_dodawacz(x): - def dodawacz(y): - return x + y - return dodawacz - -dodaj_10 = rob_dodawacz(10) -dodaj_10(3) # => 13 - -# Są również funkcje anonimowe "lambda" -(lambda x: x > 2)(3) # => True - -# Python ma też wbudowane funkcje wyższego rzędu (przyjmujące inną funkcje jako parametr) -map(add_10, [1, 2, 3]) # => [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# Można używać wyrażeń listowych (list comprehensions) do mapowania i filtrowania -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - - -#################################################### -## 5. Klasy -#################################################### - -# Wszystkie klasy są podklasą object -class Czlowiek(object): - - # Atrybut klasy. Występuje we wszystkich instancjach klasy. - gatunek = "H. sapiens" - - # Podstawowa inicjalizacja - wywoływana podczas tworzenia instacji. - # Zauważ, że podwójne podkreślenia przed i za nazwą oznaczają - # specjalne obiekty lub atrybuty wykorzystywane wewnętrznie przez Pythona. - # Nie używaj ich we własnych metodach. - def __init__(self, nazwa): - # przypisz parametr "nazwa" do atrybutu instancji - self.nazwa = nazwa - - # Metoda instancji. Wszystkie metody przyjmują "self" jako pierwszy argument - def mow(self, wiadomosc): - return "%s: %s" % (self.nazwa, wiadomosc) - - # Metoda klasowa współdzielona przez instancje. - # Przyjmuje wywołującą klasę jako pierwszy argument. - @classmethod - def daj_gatunek(cls): - return cls.gatunek - - # Metoda statyczna jest wywoływana bez argumentów klasy czy instancji. - @staticmethod - def grunt(): - return "*grunt*" - - -# Instancja klasy -i = Czlowiek(name="Ian") -print(i.mow("cześć")) # wypisze "Ian: cześć" - -j = Czlowiek("Joel") -print(j.mow("cześć")) # wypisze "Joel: cześć" - -# Wywołujemy naszą metodę klasową -i.daj_gatunek() # => "H. sapiens" - -# Zmieniamy wspólny parametr -Czlowiek.gatunek = "H. neanderthalensis" -i.daj_gatunek() # => "H. neanderthalensis" -j.daj_gatunek() # => "H. neanderthalensis" - -# Wywołanie metody statycznej -Czlowiek.grunt() # => "*grunt*" - - -#################################################### -## 6. Moduły -#################################################### - -# Tak importuje się moduły: -import math -print(math.sqrt(16)) # => 4.0 - -# Można podać konkretne funkcje, np. ceil, floor z modułu math -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Można zaimportować wszystkie funkcje z danego modułu. -# Uwaga: nie jest to polecane, bo później w kodzie trudno połapać się, -# która funkcja pochodzi z którego modułu. -from math import * - -# Można skracać nazwy modułów. -import math as m -math.sqrt(16) == m.sqrt(16) # => True -# sprawdźmy czy funkcje są równoważne -from math import sqrt -math.sqrt == m.sqrt == sqrt # => True - -# Moduły Pythona to zwykłe skrypty napisane w tym języku. Możesz -# pisać własne i importować je. Nazwa modułu to nazwa pliku. - -# W ten sposób sprawdzisz jakie funkcje wchodzą w skład modułu. -import math -dir(math) - - -#################################################### -## 7. Zaawansowane -#################################################### - -# Generatory pomagają tworzyć tzw. "leniwy kod" -def podwojne_liczby(iterowalne): - for i in iterowalne: - yield i + i - -# Generatory tworzą wartości w locie. -# Zamiast generować wartości raz i zapisywać je (np. w liście), -# generator tworzy je na bieżąco, w wyniku iteracji. To oznacza, -# że w poniższym przykładzie wartości większe niż 15 nie będą przetworzone -# w funkcji "podwojne_liczby". -# Zauważ, że xrange to generator, który wykonuje tę samą operację co range. -# Stworzenie listy od 1 do 900000000 zajęłoby sporo czasu i pamięci, -# a xrange tworzy obiekt generatora zamiast budować całą listę jak range. - -# Aby odróżnić nazwę zmiennej od nazwy zarezerwowanej w Pythonie, używamy -# zwykle na końcu znaku podkreślenia -xrange_ = xrange(1, 900000000) - -# poniższa pętla będzie podwajać liczby aż do 30 -for i in podwojne_liczby(xrange_): - print(i) - if i >= 30: - break - - -# Dekoratory -# w tym przykładzie "beg" jest nakładką na "say" -# Beg wywołuje say. Jeśli say_please jest prawdziwe, wtedy zwracana wartość -# zostanie zmieniona - -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Proszę! Jestem spłukany :(") - return msg - return wrapper - - -@beg -def say(say_please=False): - msg = "Kupisz mi piwo?" - return msg, say_please - - -print(say()) # Kupisz mi piwo? -print(say(say_please=True)) # Kupisz mi piwo? Proszę! Jestem spłukany :( -``` - -## Gotowy na więcej? -### Polskie - -* [Zanurkuj w Pythonie](http://pl.wikibooks.org/wiki/Zanurkuj_w_Pythonie) -* [LearnPythonPl](http://www.learnpython.org/pl/) - -### Angielskie: -#### Darmowe źródła online - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2.6/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) - -#### Inne - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/pl-pl/pythonlegacy-pl.html.markdown b/pl-pl/pythonlegacy-pl.html.markdown new file mode 100644 index 00000000..222f753f --- /dev/null +++ b/pl-pl/pythonlegacy-pl.html.markdown @@ -0,0 +1,640 @@ +--- +name: python +category: language +language: python +filename: learnpython-pl.py +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "http://aminbandali.com"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Dominik Krzemiński", "https://github.com/dokato"] +lang: pl-pl +--- + +Python został opracowany przez Guido Van Rossuma na początku lat 90-tych. +Obecnie jest jednym z najbardziej popularnych języków programowania. +Zakochałem się w Pythonie dzięki porządkowi, jaki utrzymywany jest w kodzie. +To po prostu wykonywalny pseudokod. + +Zapraszam do kontaktu. Złapiecie nas na: +- kontakt polski: raymon92 [at] [google's email service] +- kontakt angielski: [@louiedinh](http://twitter.com/louiedinh) lub louiedinh [at] [google's email service] + +Uwaga: Ten artykuł odnosi się do wersji Pythona 2.7, ale powinien +działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stronie głównej. + +```python +# -*- coding: utf-8 -*- + +# Pojedyncze komentarze oznaczamy takim symbolem. + +""" Wielolinijkowe napisy zapisywane są przy użyciu + potrójnych cudzysłowów i często + wykorzystywane są jako komentarze. +""" + +#################################################### +## 1. Podstawowe typy danych i operatory +#################################################### + +# Liczby to liczby +3 # => 3 + +# Matematyka jest intuicyjna +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# Dzielenie może być kłopotliwe. Poniższe działanie to dzielenie +# całkowitoliczbowe(int) i wynik jest automatycznie zaokrąglany. +5 / 2 # => 2 + +# Aby to naprawić, musimy powiedzieć nieco o liczbach zmiennoprzecinkowych. +2.0 # To liczba zmiennoprzecinkowa, tzw. float +11.0 / 4.0 # => 2.75 ahhh...znacznie lepiej + +# Wynik dzielenia całkowitoliczbowego jest obcinany dla liczb +# dodatnich i ujemnych. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # działa też na floatach +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Operator modulo - wyznaczanie reszty z dzielenia +7 % 3 # => 1 + +# Potęgowanie (x do potęgi y-tej) +2**4 # => 16 + +# Wymuszanie pierwszeństwa w nawiasach +(1 + 3) * 2 # => 8 + +# Operacje logiczne +# Zauważ, że przy "and" i "or" trzeba zwracać uwagę na rozmiar liter +True and False #=> False # Fałsz +False or True #=> True # Prawda + +# Zauważ, że operatorów logicznych można używać z intami +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +k1 == True #=> True + +# aby zanegować, użyj "not" +not True # => False +not False # => True + +# Równość == +1 == 1 # => True +2 == 1 # => False + +# Nierówność != +1 != 1 # => False +2 != 1 # => True + +# Więcej porównań +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Porównania można układać w łańcuch! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Napisy (typ string) tworzone są przy użyciu cudzysłowów " lub ' +"Jestem napisem." +'Ja też jestem napisem.' + +# Napisy można dodawać! +"Witaj " + "świecie!" # => "Witaj świecie!" + +# ... a nawet mnożyć +"Hej" * 3 # => "HejHejHej" + +# Napis może być traktowany jako lista znaków +"To napis"[0] # => 'T' + +# % może być używane do formatowania napisów: +"%s są %s" % ("napisy", "fajne") + +# Jednak nowszym sposobem formatowania jest metoda "format". +# Ta metoda jest obecnie polecana: +"{0} są {1}".format("napisy", "fajne") +# Jeśli nie chce ci się liczyć, użyj słów kluczowych. +"{imie} chce zjeść {jadlo}".format(imie="Bob", jadlo="makaron") + +# None jest obiektem +None # => None + +# Nie używaj "==" w celu porównania obiektów z None +# Zamiast tego użyj "is" +"etc" is None # => False +None is None # => True + +# Operator 'is' testuje identyczność obiektów. Nie jest to zbyt +# pożyteczne, gdy działamy tylko na prostych wartościach, +# ale przydaje się, gdy mamy do czynienia z obiektami. + +# None, 0 i pusty napis "" są odpowiednikami logicznego False. +# Wszystkie inne wartości są uznawane za prawdę (True) +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Zmienne i zbiory danych +#################################################### + +# Python ma instrukcję wypisującą "print" we wszystkich wersjach 2.x, ale +# została ona usunięta z wersji 3. +print "Jestem Python. Miło Cię poznać!" +# Python ma też funkcję "print" dostępną w wersjach 2.7 i 3... +# ale w 2.7 musisz dodać import (odkomentuj): +# from __future__ import print_function +print("Ja też jestem Python! ") + +# Nie trzeba deklarować zmiennych przed przypisaniem. +jakas_zmienna = 5 # Konwencja mówi: używaj małych liter i znaków podkreślenia _ +jakas_zmienna # => 5 + +# Próba dostępu do niezadeklarowanej zmiennej da błąd. +# Przejdź do sekcji Obsługa wyjątków, aby dowiedzieć się więcej... +inna_zmienna # Wyrzuca nazwę błędu + +# "if" może być użyte jako wyrażenie +"huraaa!" if 3 > 2 else 2 # => "huraaa!" + +# Listy: +li = [] +# Możesz zacząć od wypełnionej listy +inna_li = [4, 5, 6] + +# Dodaj na koniec, używając "append" +li.append(1) # li to teraz [1] +li.append(2) # li to teraz [1, 2] +li.append(4) # li to teraz [1, 2, 4] +li.append(3) # li to teraz [1, 2, 4, 3] +# Usuwanie z konca da "pop" +li.pop() # => 3 a li stanie się [1, 2, 4] +# Dodajmy ponownie +li.append(3) # li to znowu [1, 2, 4, 3]. + +# Dostęp do list jak do każdej tablicy +li[0] # => 1 +# Aby nadpisać wcześniej wypełnione miejsca w liście, użyj znaku = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Uwaga: ustawiamy starą wartość +# Tak podglądamy ostatni element +li[-1] # => 3 + +# Jeżeli wyjdziesz poza zakres... +li[4] # ... zobaczysz IndexError + +# Możesz też tworzyć wycinki. +li[1:3] # => [2, 4] +# Bez początku +li[2:] # => [4, 3] +# Omijamy koniec +li[:3] # => [1, 2, 4] +# Wybierz co drugi +li[::2] # =>[1, 4] +# Odwróć listę +li[::-1] # => [3, 4, 2, 1] +# Użyj kombinacji powyższych aby tworzyć bardziej skomplikowane wycinki +# li[poczatek:koniec:krok] + +# Usuń element używając "del" +del li[2] # li to teraz [1, 2, 3] + +# Listy można dodawać +li + inna_li # => [1, 2, 3, 4, 5, 6] +# Uwaga: wartości oryginalnych list li i inna_li się nie zmieniają. + +# Do łączenia list użyj "extend()" +li.extend(other_li) # li to teraz [1, 2, 3, 4, 5, 6] + +# Sprawdź, czy element jest w liście używając "in" +1 in li # => True + +# "len()" pokazuje długość listy +len(li) # => 6 + + +# Krotki (tuple) są jak listy, ale nie można ich modyfikować. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # wyrzuci TypeError + +# Ale wielu akcji dla list możesz używać przy krotkach +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Można rozpakować krotki i listy do poszczególych zmiennych +a, b, c = (1, 2, 3) # a to teraz 1, b jest 2, a c to 3 +# Jeżeli zapomnisz nawiasów, automatycznie tworzone są krotki +d, e, f = 4, 5, 6 +# Popatrz jak prosto zamienić wartości +e, d = d, e # d to teraz 5 a e to 4 + + +# Słowniki są również pożyteczne +pusty_slownik = {} +# Tu tworzymy wypełniony: +pelen_slownik = {"raz": 1, "dwa": 2, "trzy": 3} + +# Podglądany wartość +pelen_slownik["one"] # => 1 + +# Wypisz wszystkie klucze, używając "keys()" +pelen_slownik.keys() # => ["trzy", "dwa", "raz"] +# Uwaga: słowniki nie zapamiętują kolejności kluczy. + +# A teraz wszystkie wartości "values()" +pelen_slownik.values() # => [3, 2, 1] +# Uwaga: to samo dotyczy wartości. + +# Sprawdzanie czy klucz występuje w słowniku za pomocą "in" +"raz" in pelen_slownik # => True +1 in pelen_slownik # => False + +# Próba dobrania się do nieistniejącego klucza da KeyError +pelen_slownik["cztery"] # KeyError + +# Użyj metody "get()", aby uniknąć błędu KeyError +pelen_slownik.get("raz") # => 1 +pelen_slownik.get("cztery") # => None +# Metoda get zwraca domyślną wartość gdy brakuje klucza +pelen_slownik.get("one", 4) # => 1 +pelen_slownik.get("cztery", 4) # => 4 +# zauważ, że pelen_slownik.get("cztery") wciąż zwraca => None +# (get nie ustawia wartości słownika) + +# przypisz wartość do klucza podobnie jak w listach +pelen_slownik["cztery"] = 4 # teraz: pelen_slownik["cztery"] => 4 + +# "setdefault()" wstawia do słownika tylko jeśli nie było klucza +pelen_slownik.setdefault("piec", 5) # pelen_slownik["piec"] daje 5 +pelen_slownik.setdefault("piec", 6) # pelen_slownik["piec"] to wciąż 5 + + +# Teraz zbiory (set) - działają jak zwykłe listy, ale bez potórzeń +pusty_zbior = set() +# Inicjalizujemy "set()" pewnymi wartościami +jakis_zbior = set([1, 2, 2, 3, 4]) # jakis_zbior to teraz set([1, 2, 3, 4]) + +# kolejność nie jest zachowana, nawet gdy wydaje się posortowane +inny_zbior = set([4, 3, 2, 2, 1]) # inny_zbior to set([1, 2, 3, 4]) + +# Od Pythona 2.7 nawiasy klamrowe {} mogą być użyte do deklarowania zbioru +pelen_zbior = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Dodaj więcej elementów przez "add()" +pelen_zbior.add(5) # pelen_zbior is now {1, 2, 3, 4, 5} + +# Znajdź przecięcie (część wspólną) zbiorów, używając & +inny_zbior = {3, 4, 5, 6} +pelen_zbior & other_set # => {3, 4, 5} + +# Suma zbiorów | +pelen_zbior | other_set # => {1, 2, 3, 4, 5, 6} + +# Różnicę zbiorów da znak - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Sprawdzanie obecności w zbiorze: "in". +2 in pelen_zbior # => True +10 in pelen_zbior # => False + + +#################################################### +## 3. Kontrola przepływu +#################################################### + +# Tworzymy zmienną jakas_zm +jakas_zm = 5 + +# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia w Pythonie są ważne! +# Poniższy kod wypisze "jakas_zm jest mniejsza niż 10" +if jakas_zm > 10: + print("jakas_zm jest wieksza niż 10") +elif some_var < 10: # Opcjonalna klauzula elif + print("jakas_zm jest mniejsza niż 10") +else: # Również opcjonalna klauzula else + print("jakas_zm jest równa 10") + + +""" +Pętla for iteruje po elementach listy, wypisując: + pies to ssak + kot to ssak + mysz to ssak +""" +for zwierze in ["pies", "kot", "mysz"]: + # Użyj metody format, aby umieścić wartość zmiennej w ciągu + print("{0} to ssak".format(zwierze)) + +""" +"range(liczba)" zwraca listę liczb +z przedziału od zera do wskazanej liczby (bez niej): + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +While to pętla, która jest wykonywana, dopóki spełniony jest warunek: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Skrót od x = x + 1 + +# Wyjątki wyłapujemy, używając try i except + +# Działa w Pythonie 2.6 i wyższych: +try: + # Użyj "raise" aby wyrzucić wyjątek + raise IndexError("To błąd indeksu") +except IndexError as e: + pass # Pass to brak reakcji na błąd. Zwykle opisujesz tutaj, jak program ma się zachować w przypadku błędu. +except (TypeError, NameError): + pass # kilka wyjątków można przechwycić jednocześnie. +else: # Opcjonalna część bloku try/except. Musi wystąpić na końcu + print "Wszystko ok!" # Zadziała tylko, gdy program nie napotka wyjatku. + + +#################################################### +## 4. Funkcje +#################################################### + +# Użyj "def", aby stworzyć nową funkcję +def dodaj(x, y): + print("x to %s, a y to %s" % (x, y)) + return x + y # słowo kluczowe return zwraca wynik działania + +# Tak wywołuje się funkcję z parametrami: +dodaj(5, 6) # => wypisze "x to 5, a y to 6" i zwróci 11 + +# Innym sposobem jest wywołanie z parametrami nazwanymi. +dodaj(y=6, x=5) # tutaj kolejność podania nie ma znaczenia. + + +# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów pozycyjnych, +# które zostaną przekazana jako krotka, pisząc w definicji funkcji "*args" +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów +# nazwanych kwargs, które zostaną przekazane jako słownik, pisząc w definicji funkcji "**kwargs" +def keyword_args(**kwargs): + return kwargs + +# Wywołajmy to i sprawdźmy co się dzieje +keyword_args(wielka="stopa", loch="ness") # => {"wielka": "stopa", "loch": "ness"} + + +# Możesz też przyjmować jednocześnie zmienną liczbę parametrów pozycyjnych i nazwanych +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) wypisze: + (1, 2) + {"a": 3, "b": 4} +""" + +# Użyj * aby rozwinąć parametry z krotki args +# i użyj ** aby rozwinąć parametry nazwane ze słownika kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # odpowiednik foo(1, 2, 3, 4) +all_the_args(**kwargs) # odpowiednik foo(a=3, b=4) +all_the_args(*args, **kwargs) # odpowiednik foo(1, 2, 3, 4, a=3, b=4) + +# Możesz podać parametry args i kwargs do funkcji równocześnie +# przez rozwinięcie odpowiednio * i ** +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# Zasięg zmiennych +x = 5 + +def setX(num): + # Lokalna zmienna x nie jest tym samym co zmienna x + x = num # => 43 + print x # => 43 + +def setGlobalX(num): + global x + print x # => 5 + x = num # globalna zmienna to teraz 6 + print x # => 6 + +setX(43) +setGlobalX(6) + +# Można tworzyć funkcje wewnętrzne i zwrócić je jako wynik +def rob_dodawacz(x): + def dodawacz(y): + return x + y + return dodawacz + +dodaj_10 = rob_dodawacz(10) +dodaj_10(3) # => 13 + +# Są również funkcje anonimowe "lambda" +(lambda x: x > 2)(3) # => True + +# Python ma też wbudowane funkcje wyższego rzędu (przyjmujące inną funkcje jako parametr) +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Można używać wyrażeń listowych (list comprehensions) do mapowania i filtrowania +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + + +#################################################### +## 5. Klasy +#################################################### + +# Wszystkie klasy są podklasą object +class Czlowiek(object): + + # Atrybut klasy. Występuje we wszystkich instancjach klasy. + gatunek = "H. sapiens" + + # Podstawowa inicjalizacja - wywoływana podczas tworzenia instacji. + # Zauważ, że podwójne podkreślenia przed i za nazwą oznaczają + # specjalne obiekty lub atrybuty wykorzystywane wewnętrznie przez Pythona. + # Nie używaj ich we własnych metodach. + def __init__(self, nazwa): + # przypisz parametr "nazwa" do atrybutu instancji + self.nazwa = nazwa + + # Metoda instancji. Wszystkie metody przyjmują "self" jako pierwszy argument + def mow(self, wiadomosc): + return "%s: %s" % (self.nazwa, wiadomosc) + + # Metoda klasowa współdzielona przez instancje. + # Przyjmuje wywołującą klasę jako pierwszy argument. + @classmethod + def daj_gatunek(cls): + return cls.gatunek + + # Metoda statyczna jest wywoływana bez argumentów klasy czy instancji. + @staticmethod + def grunt(): + return "*grunt*" + + +# Instancja klasy +i = Czlowiek(name="Ian") +print(i.mow("cześć")) # wypisze "Ian: cześć" + +j = Czlowiek("Joel") +print(j.mow("cześć")) # wypisze "Joel: cześć" + +# Wywołujemy naszą metodę klasową +i.daj_gatunek() # => "H. sapiens" + +# Zmieniamy wspólny parametr +Czlowiek.gatunek = "H. neanderthalensis" +i.daj_gatunek() # => "H. neanderthalensis" +j.daj_gatunek() # => "H. neanderthalensis" + +# Wywołanie metody statycznej +Czlowiek.grunt() # => "*grunt*" + + +#################################################### +## 6. Moduły +#################################################### + +# Tak importuje się moduły: +import math +print(math.sqrt(16)) # => 4.0 + +# Można podać konkretne funkcje, np. ceil, floor z modułu math +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Można zaimportować wszystkie funkcje z danego modułu. +# Uwaga: nie jest to polecane, bo później w kodzie trudno połapać się, +# która funkcja pochodzi z którego modułu. +from math import * + +# Można skracać nazwy modułów. +import math as m +math.sqrt(16) == m.sqrt(16) # => True +# sprawdźmy czy funkcje są równoważne +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True + +# Moduły Pythona to zwykłe skrypty napisane w tym języku. Możesz +# pisać własne i importować je. Nazwa modułu to nazwa pliku. + +# W ten sposób sprawdzisz jakie funkcje wchodzą w skład modułu. +import math +dir(math) + + +#################################################### +## 7. Zaawansowane +#################################################### + +# Generatory pomagają tworzyć tzw. "leniwy kod" +def podwojne_liczby(iterowalne): + for i in iterowalne: + yield i + i + +# Generatory tworzą wartości w locie. +# Zamiast generować wartości raz i zapisywać je (np. w liście), +# generator tworzy je na bieżąco, w wyniku iteracji. To oznacza, +# że w poniższym przykładzie wartości większe niż 15 nie będą przetworzone +# w funkcji "podwojne_liczby". +# Zauważ, że xrange to generator, który wykonuje tę samą operację co range. +# Stworzenie listy od 1 do 900000000 zajęłoby sporo czasu i pamięci, +# a xrange tworzy obiekt generatora zamiast budować całą listę jak range. + +# Aby odróżnić nazwę zmiennej od nazwy zarezerwowanej w Pythonie, używamy +# zwykle na końcu znaku podkreślenia +xrange_ = xrange(1, 900000000) + +# poniższa pętla będzie podwajać liczby aż do 30 +for i in podwojne_liczby(xrange_): + print(i) + if i >= 30: + break + + +# Dekoratory +# w tym przykładzie "beg" jest nakładką na "say" +# Beg wywołuje say. Jeśli say_please jest prawdziwe, wtedy zwracana wartość +# zostanie zmieniona + +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Proszę! Jestem spłukany :(") + return msg + return wrapper + + +@beg +def say(say_please=False): + msg = "Kupisz mi piwo?" + return msg, say_please + + +print(say()) # Kupisz mi piwo? +print(say(say_please=True)) # Kupisz mi piwo? Proszę! Jestem spłukany :( +``` + +## Gotowy na więcej? +### Polskie + +* [Zanurkuj w Pythonie](http://pl.wikibooks.org/wiki/Zanurkuj_w_Pythonie) +* [LearnPythonPl](http://www.learnpython.org/pl/) + +### Angielskie: +#### Darmowe źródła online + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +#### Inne + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/pt-br/python-pt.html.markdown b/pt-br/python-pt.html.markdown deleted file mode 100644 index 82b70117..00000000 --- a/pt-br/python-pt.html.markdown +++ /dev/null @@ -1,509 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["Vilson Vieira", "http://automata.cc"] -lang: pt-br -filename: learnpython-pt.py ---- - -Python foi criado por Guido Van Rossum no começo dos anos 90. Atualmente é uma -das linguagens de programação mais populares. Eu me apaixonei por Python, por -sua clareza de sintaxe. É basicamente pseudocódigo executável. - -Comentários serão muito apreciados! Você pode me contactar em -[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [arroba] -[serviço de email do google] - -Nota: Este artigo usa Python 2.7 especificamente, mas deveria ser aplicável a -qualquer Python 2.x. Logo haverá uma versão abordando Python 3! - -```python -# Comentários de uma linha começam com cerquilha (ou sustenido) -""" Strings de várias linhas podem ser escritas - usando três ", e são comumente usadas - como comentários -""" - -#################################################### -## 1. Tipos de dados primitivos e operadores -#################################################### - -# Você usa números normalmente -3 #=> 3 - -# Operadores matemáticos são aqueles que você já está acostumado -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 - -# A divisão é um pouco estranha. A divisão de números inteiros arredonda -# para baixo o resultado, automaticamente -5 / 2 #=> 2 - -# Para concertar a divisão, precisamos aprender sobre números de ponto -# flutuante (conhecidos como 'float'). -2.0 # Isso é um 'float' -11.0 / 4.0 #=> 2.75 ahhh... muito melhor - -# Forçamos a precedência de operadores usando parênteses -(1 + 3) * 2 #=> 8 - -# Valores booleanos (ou 'boolean') são também tipos primitivos -True -False - -# Negamos usando 'not' -not True #=> False -not False #=> True - -# Testamos igualdade usando '==' -1 == 1 #=> True -2 == 1 #=> False - -# E desigualdade com '!=' -1 != 1 #=> False -2 != 1 #=> True - -# Mais comparações -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True - -# As comparações podem ser encadeadas! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False - -# Strings são criadas com " ou ' -"Isso é uma string." -'Isso também é uma string.' - -# Strings podem ser somadas (ou melhor, concatenadas)! -"Olá " + "mundo!" #=> "Olá mundo!" - -# Uma string pode ser tratada como uma lista de caracteres -"Esta é uma string"[0] #=> 'E' - -# O caractere % pode ser usado para formatar strings, desta forma: -"%s podem ser %s" % ("strings", "interpoladas") - -# Um jeito novo de formatar strings é usando o método 'format'. -# Esse método é o jeito mais usado -"{0} podem ser {1}".format("strings", "formatadas") -# Você pode usar palavras-chave (ou 'keywords') se você não quiser contar. -"{nome} quer comer {comida}".format(nome="João", comida="lasanha") - -# 'None' é um objeto -None #=> None - -# Não use o operador de igualdade `==` para comparar objetos com 'None' -# Ao invés disso, use `is` -"etc" is None #=> False -None is None #=> True - -# O operador 'is' teste a identidade de um objeto. Isso não é -# muito útil quando estamos lidando com valores primitivos, mas é -# muito útil quando lidamos com objetos. - -# None, 0, e strings/listas vazias são todas interpretadas como 'False'. -# Todos os outros valores são 'True' -0 == False #=> True -"" == False #=> True - - -#################################################### -## 2. Variáveis e Coleções -#################################################### - -# Imprimir na tela é muito fácil -print "Eu sou o Python. Prazer em te conhecer!" - - -# Nós não precisamos declarar variáveis antes de usá-las, basta usar! -alguma_variavel = 5 # A convenção é usar caixa_baixa_com_sobrescritos -alguma_variavel #=> 5 - -# Acessar uma variável que não teve nenhum valor atribuído anteriormente é -# uma exceção. -# Veja a seção 'Controle' para aprender mais sobre tratamento de exceção. -outra_variavel # Gera uma exceção de erro de nome - -# 'if' pode ser usado como uma expressão -"uepa!" if 3 > 2 else 2 #=> "uepa!" - -# Listas armazenam sequências de elementos -lista = [] -# Você pode inicializar uma lista com valores -outra_lista = [4, 5, 6] - -# Adicione elementos no final da lista usando 'append' -lista.append(1) # lista é agora [1] -lista.append(2) # lista é agora [1, 2] -lista.append(4) # lista é agora [1, 2, 4] -lista.append(3) # lista é agora [1, 2, 4, 3] -# Remova elementos do fim da lista usando 'pop' -lista.pop() #=> 3 e lista é agora [1, 2, 4] -# Vamos adicionar o elemento novamente -lista.append(3) # lista agora é [1, 2, 4, 3] novamente. - -# Acesse elementos de uma lista através de seu índices -lista[0] #=> 1 -# Acesse o último elemento com índice negativo! -lista[-1] #=> 3 - -# Tentar acessar um elemento fora dos limites da lista gera uma exceção -# do tipo 'IndexError' -lista[4] # Gera uma exceção 'IndexError' - -# Você pode acessar vários elementos ao mesmo tempo usando a sintaxe de -# limites -# (Para quem gosta de matemática, isso é um limite fechado/aberto) -lista[1:3] #=> [2, 4] -# Você pode omitir o fim se quiser os elementos até o final da lista -lista[2:] #=> [4, 3] -# O mesmo para o início -lista[:3] #=> [1, 2, 4] - -# Remova um elemento qualquer de uma lista usando 'del' -del lista[2] # lista agora é [1, 2, 3] - -# Você pode somar listas (obs: as listas originais não são modificadas) -lista + outra_lista #=> [1, 2, 3, 4, 5, 6] - -# Você também pode concatenar usando o método 'extend' (lista será modificada!) -lista.extend(outra_lista) # Agora lista é [1, 2, 3, 4, 5, 6] - -# Para checar se um elemento pertence a uma lista, use 'in' -1 in lista #=> True - -# Saiba quantos elementos uma lista possui com 'len' -len(lista) #=> 6 - - -# Tuplas são iguais a listas, mas são imutáveis -tup = (1, 2, 3) -tup[0] #=> 1 -tup[0] = 3 # Isso gera uma exceção do tipo TypeError - -# Você pode fazer nas tuplas todas aquelas coisas fez com a lista -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True - -# Você pode 'desempacotar' tuplas (ou listas) em variáveis, associando cada -# elemento da tupla/lista a uma variável correspondente -a, b, c = (1, 2, 3) # a agora é 1, b agora é 2, c agora é 3 -# Tuplas são criadas por padrão, mesmo se você não usar parênteses -d, e, f = 4, 5, 6 -# Sabendo disso, veja só como é fácil trocar os valores de duas variáveis! -e, d = d, e # d agora é 5, e agora é 4 - - -# Dicionários armazenam 'mapeamentos' (do tipo chave-valor) -dicionario_vazio = {} -# Aqui criamos um dicionário já contendo valores -dicionario = {"um": 1, "dois": 2, "três": 3} - -# Acesse valores usando [] -dicionario["um"] #=> 1 - -# Retorna uma lista com todas as chaves do dicionário -dicionario.keys() #=> ["três", "dois", "um"] -# Nota: A ordem das chaves não é garantida. -# O resultado no seu interpretador não necessariamente será igual a esse. - -# Retorna uma lista com todos os valores do dicionário -dicionario.values() #=> [3, 2, 1] -# Nota: A mesma nota acima sobre a ordenação é válida aqui. - -# Veja se uma chave qualquer está em um dicionário usando 'in' -"um" in dicionario #=> True -1 in dicionario #=> False - -# Tentar acessar uma chave que não existe gera uma exceção do tipo 'KeyError' -dicionario["quatro"] # Gera uma exceção KeyError - -# Você pode usar o método 'get' para evitar gerar a exceção 'KeyError'. -# Ao invés de gerar essa exceção, irá retornar 'None' se a chave não existir. -dicionario.get("um") #=> 1 -dicionario.get("quatro") #=> None -# O método 'get' suporta um argumento que diz qual valor deverá ser -# retornado se a chave não existir (ao invés de 'None'). -dicionario.get("um", 4) #=> 1 -dicionario.get("quatro", 4) #=> 4 - -# O método 'setdefault' é um jeito seguro de adicionar um novo par -# chave-valor a um dicionário, associando um valor padrão imutável à uma chave -dicionario.setdefault("cinco", 5) # dicionario["cinco"] é definido como 5 -dicionario.setdefault("cinco", 6) # dicionario["cinco"] ainda é igual a 5 - - -# Conjuntos (ou sets) armazenam ... bem, conjuntos -# Nota: lembre-se que conjuntos não admitem elementos repetidos! -conjunto_vazio = set() -# Podemos inicializar um conjunto com valores -conjunto = set([1, 2, 2, 3, 4]) # conjunto é set([1, 2, 3, 4]), sem repetição! - -# Desde o Python 2.7, {} pode ser usado para declarar um conjunto -conjunto = {1, 2, 2, 3, 4} # => {1 2 3 4} - -# Adicione mais ítens a um conjunto com 'add' -conjunto.add(5) # conjunto agora é {1, 2, 3, 4, 5} - -# Calcule a intersecção de dois conjuntos com & -outro_conj = {3, 4, 5, 6} -conjunto & outro_conj #=> {3, 4, 5} - -# Calcule a união de dois conjuntos com | -conjunto | outro_conj #=> {1, 2, 3, 4, 5, 6} - -# E a diferença entre dois conjuntos com - -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# Veja se um elemento existe em um conjunto usando 'in' -2 in conjunto #=> True -10 in conjunto #=> False - - -#################################################### -## 3. Controle -#################################################### - -# Para começar, vamos apenas criar uma variável -alguma_var = 5 - -# Aqui está uma expressão 'if'. Veja como a identação é importante em Python! -# Esses comandos irão imprimir "alguma_var é menor que 10" -if alguma_var > 10: - print "some_var é maior que 10." -elif some_var < 10: # Esse 'elif' é opcional - print "some_var é menor que 10." -else: # Esse 'else' também é opcional - print "some_var é igual a 10." - - -""" -Laços (ou loops) 'for' iteram em listas. -Irá imprimir: - cachorro é um mamífero - gato é um mamífero - rato é um mamífero -""" -for animal in ["cachorro", "gato", "rato"]: - # Você pode usar % para interpolar strings formatadas - print "%s é um mamífero" % animal - -""" -A função `range(um número)` retorna uma lista de números -do zero até o número dado. -Irá imprimir: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -Laços 'while' executam enquanto uma condição dada for verdadeira. -Irá imprimir: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # Isso é um atalho para a expressão x = x + 1 - -# Tratamos excessões usando o bloco try/except -# Funciona em Python 2.6 e versões superiores: - -try: - # Use 'raise' para gerar um erro - raise IndexError("Isso é um erro de índice") -except IndexError as e: - pass # Pass é um operador que não faz nada, deixa passar. - # Usualmente você iria tratar a exceção aqui... - - -#################################################### -## 4. Funções -#################################################### - -# Use 'def' para definir novas funções -def soma(x, y): - print "x é %s e y é %s" % (x, y) - return x + y # Retorne valores usando 'return' - -# Chamando funções com parâmetros -soma(5, 6) #=> imprime "x é 5 e y é 6" e retorna o valor 11 - -# Um outro jeito de chamar funções é especificando explicitamente os valores -# de cada parâmetro com chaves -soma(y=6, x=5) # Argumentos com chaves podem vir em qualquer ordem. - -# Você pode definir funções que recebem um número qualquer de argumentos -# (respeitando a sua ordem) -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# Você também pode definir funções que recebem um número qualquer de argumentos -# com chaves -def args_com_chaves(**ch_args): - return ch_args - -# Vamos chamar essa função para ver o que acontece -args_com_chaves(pe="grande", lago="Ness") #=> {"pe": "grande", "lago": "Ness"} - -# Você pode fazer as duas coisas ao mesmo tempo, se desejar -def todos_args(*args, **ch_wargs): - print args - print ch_args -""" -todos_args(1, 2, a=3, b=4) imprime: - (1, 2) - {"a": 3, "b": 4} -""" - -# Quando você chamar funções, pode fazer o oposto do que fizemos até agora! -# Podemos usar * para expandir tuplas de argumentos e ** para expandir -# dicionários de argumentos com chave. -args = (1, 2, 3, 4) -ch_args = {"a": 3, "b": 4} -todos_args(*args) # equivalente a todos_args(1, 2, 3, 4) -todos_args(**ch_args) # equivalente a todos_args(a=3, b=4) -todos_args(*args, **ch_args) # equivalente a todos_args(1, 2, 3, 4, a=3, b=4) - -# Em Python, funções são elementos de primeira ordem (são como objetos, -# strings ou números) -def cria_somador(x): - def somador(y): - return x + y - return somador - -soma_10 = cria_somador(10) -soma_10(3) #=> 13 - -# Desta forma, existem também funções anônimas -(lambda x: x > 2)(3) #=> True - -# E existem funções de alta ordem por padrão -map(soma_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] -reduce(lambda x, y: x + y, [3, 4, 5, 6, 7]) #=> 25 - -# Nós podemos usar compreensão de listas para mapear e filtrar também -[soma_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] - -#################################################### -## 5. Classes -#################################################### - -# Para criar uma nova classe, devemos herdar de 'object' -class Humano(object): - - # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa - # classe - especie = "H. sapiens" - - # Definimos um inicializador básico - def __init__(self, nome): - # Atribui o valor de argumento dado a um atributo da instância - self.nome = nome - - # Um método de instância. Todos os métodos levam 'self' como primeiro - # argumento - def diga(self, msg): - return "%s: %s" % (self.nome, msg) - - # Um método de classe é compartilhado por todas as instâncias - # Eles são chamados passando o nome da classe como primeiro argumento - @classmethod - def get_especie(cls): - return cls.especie - - # Um método estático é chamado sem uma referência a classe ou instância - @staticmethod - def ronca(): - return "*arrrrrrr*" - - -# Instancie uma classe -i = Humano(nome="Ivone") -print i.diga("oi") # imprime "Ivone: oi" - -j = Human("Joel") -print j.say("olá") #prints out "Joel: olá" - -# Chame nosso método de classe -i.get_especie() #=> "H. sapiens" - -# Modifique um atributo compartilhado -Humano.especie = "H. neanderthalensis" -i.get_especie() #=> "H. neanderthalensis" -j.get_especie() #=> "H. neanderthalensis" - -# Chame o método estático -Humano.ronca() #=> "*arrrrrrr*" - - -#################################################### -## 6. Módulos -#################################################### - -# Você pode importar módulos -import math -print math.sqrt(16) #=> 4.0 - -# Você pode importar funções específicas de um módulo -from math import ceil, floor -print ceil(3.7) #=> 4.0 -print floor(3.7) #=> 3.0 - -# Você também pode importar todas as funções de um módulo -# Atenção: isso não é recomendado! -from math import * - -# Você pode usar apelidos para os módulos, encurtando seus nomes -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Módulos em Python são apenas arquivos Python. Você -# pode escrever o seu próprio módulo e importá-lo. O nome do -# módulo será o mesmo que o nome do arquivo. - -# Você pode descobrir quais funções e atributos -# estão definidos em um módulo qualquer. -import math -dir(math) - - -``` - -## Pronto para mais? - -### Online e gratuito - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2.6/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) - -### Livros impressos - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/pt-br/pythonlegacy-pt.html.markdown b/pt-br/pythonlegacy-pt.html.markdown new file mode 100644 index 00000000..82b70117 --- /dev/null +++ b/pt-br/pythonlegacy-pt.html.markdown @@ -0,0 +1,509 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Vilson Vieira", "http://automata.cc"] +lang: pt-br +filename: learnpython-pt.py +--- + +Python foi criado por Guido Van Rossum no começo dos anos 90. Atualmente é uma +das linguagens de programação mais populares. Eu me apaixonei por Python, por +sua clareza de sintaxe. É basicamente pseudocódigo executável. + +Comentários serão muito apreciados! Você pode me contactar em +[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [arroba] +[serviço de email do google] + +Nota: Este artigo usa Python 2.7 especificamente, mas deveria ser aplicável a +qualquer Python 2.x. Logo haverá uma versão abordando Python 3! + +```python +# Comentários de uma linha começam com cerquilha (ou sustenido) +""" Strings de várias linhas podem ser escritas + usando três ", e são comumente usadas + como comentários +""" + +#################################################### +## 1. Tipos de dados primitivos e operadores +#################################################### + +# Você usa números normalmente +3 #=> 3 + +# Operadores matemáticos são aqueles que você já está acostumado +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# A divisão é um pouco estranha. A divisão de números inteiros arredonda +# para baixo o resultado, automaticamente +5 / 2 #=> 2 + +# Para concertar a divisão, precisamos aprender sobre números de ponto +# flutuante (conhecidos como 'float'). +2.0 # Isso é um 'float' +11.0 / 4.0 #=> 2.75 ahhh... muito melhor + +# Forçamos a precedência de operadores usando parênteses +(1 + 3) * 2 #=> 8 + +# Valores booleanos (ou 'boolean') são também tipos primitivos +True +False + +# Negamos usando 'not' +not True #=> False +not False #=> True + +# Testamos igualdade usando '==' +1 == 1 #=> True +2 == 1 #=> False + +# E desigualdade com '!=' +1 != 1 #=> False +2 != 1 #=> True + +# Mais comparações +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# As comparações podem ser encadeadas! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Strings são criadas com " ou ' +"Isso é uma string." +'Isso também é uma string.' + +# Strings podem ser somadas (ou melhor, concatenadas)! +"Olá " + "mundo!" #=> "Olá mundo!" + +# Uma string pode ser tratada como uma lista de caracteres +"Esta é uma string"[0] #=> 'E' + +# O caractere % pode ser usado para formatar strings, desta forma: +"%s podem ser %s" % ("strings", "interpoladas") + +# Um jeito novo de formatar strings é usando o método 'format'. +# Esse método é o jeito mais usado +"{0} podem ser {1}".format("strings", "formatadas") +# Você pode usar palavras-chave (ou 'keywords') se você não quiser contar. +"{nome} quer comer {comida}".format(nome="João", comida="lasanha") + +# 'None' é um objeto +None #=> None + +# Não use o operador de igualdade `==` para comparar objetos com 'None' +# Ao invés disso, use `is` +"etc" is None #=> False +None is None #=> True + +# O operador 'is' teste a identidade de um objeto. Isso não é +# muito útil quando estamos lidando com valores primitivos, mas é +# muito útil quando lidamos com objetos. + +# None, 0, e strings/listas vazias são todas interpretadas como 'False'. +# Todos os outros valores são 'True' +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Variáveis e Coleções +#################################################### + +# Imprimir na tela é muito fácil +print "Eu sou o Python. Prazer em te conhecer!" + + +# Nós não precisamos declarar variáveis antes de usá-las, basta usar! +alguma_variavel = 5 # A convenção é usar caixa_baixa_com_sobrescritos +alguma_variavel #=> 5 + +# Acessar uma variável que não teve nenhum valor atribuído anteriormente é +# uma exceção. +# Veja a seção 'Controle' para aprender mais sobre tratamento de exceção. +outra_variavel # Gera uma exceção de erro de nome + +# 'if' pode ser usado como uma expressão +"uepa!" if 3 > 2 else 2 #=> "uepa!" + +# Listas armazenam sequências de elementos +lista = [] +# Você pode inicializar uma lista com valores +outra_lista = [4, 5, 6] + +# Adicione elementos no final da lista usando 'append' +lista.append(1) # lista é agora [1] +lista.append(2) # lista é agora [1, 2] +lista.append(4) # lista é agora [1, 2, 4] +lista.append(3) # lista é agora [1, 2, 4, 3] +# Remova elementos do fim da lista usando 'pop' +lista.pop() #=> 3 e lista é agora [1, 2, 4] +# Vamos adicionar o elemento novamente +lista.append(3) # lista agora é [1, 2, 4, 3] novamente. + +# Acesse elementos de uma lista através de seu índices +lista[0] #=> 1 +# Acesse o último elemento com índice negativo! +lista[-1] #=> 3 + +# Tentar acessar um elemento fora dos limites da lista gera uma exceção +# do tipo 'IndexError' +lista[4] # Gera uma exceção 'IndexError' + +# Você pode acessar vários elementos ao mesmo tempo usando a sintaxe de +# limites +# (Para quem gosta de matemática, isso é um limite fechado/aberto) +lista[1:3] #=> [2, 4] +# Você pode omitir o fim se quiser os elementos até o final da lista +lista[2:] #=> [4, 3] +# O mesmo para o início +lista[:3] #=> [1, 2, 4] + +# Remova um elemento qualquer de uma lista usando 'del' +del lista[2] # lista agora é [1, 2, 3] + +# Você pode somar listas (obs: as listas originais não são modificadas) +lista + outra_lista #=> [1, 2, 3, 4, 5, 6] + +# Você também pode concatenar usando o método 'extend' (lista será modificada!) +lista.extend(outra_lista) # Agora lista é [1, 2, 3, 4, 5, 6] + +# Para checar se um elemento pertence a uma lista, use 'in' +1 in lista #=> True + +# Saiba quantos elementos uma lista possui com 'len' +len(lista) #=> 6 + + +# Tuplas são iguais a listas, mas são imutáveis +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Isso gera uma exceção do tipo TypeError + +# Você pode fazer nas tuplas todas aquelas coisas fez com a lista +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Você pode 'desempacotar' tuplas (ou listas) em variáveis, associando cada +# elemento da tupla/lista a uma variável correspondente +a, b, c = (1, 2, 3) # a agora é 1, b agora é 2, c agora é 3 +# Tuplas são criadas por padrão, mesmo se você não usar parênteses +d, e, f = 4, 5, 6 +# Sabendo disso, veja só como é fácil trocar os valores de duas variáveis! +e, d = d, e # d agora é 5, e agora é 4 + + +# Dicionários armazenam 'mapeamentos' (do tipo chave-valor) +dicionario_vazio = {} +# Aqui criamos um dicionário já contendo valores +dicionario = {"um": 1, "dois": 2, "três": 3} + +# Acesse valores usando [] +dicionario["um"] #=> 1 + +# Retorna uma lista com todas as chaves do dicionário +dicionario.keys() #=> ["três", "dois", "um"] +# Nota: A ordem das chaves não é garantida. +# O resultado no seu interpretador não necessariamente será igual a esse. + +# Retorna uma lista com todos os valores do dicionário +dicionario.values() #=> [3, 2, 1] +# Nota: A mesma nota acima sobre a ordenação é válida aqui. + +# Veja se uma chave qualquer está em um dicionário usando 'in' +"um" in dicionario #=> True +1 in dicionario #=> False + +# Tentar acessar uma chave que não existe gera uma exceção do tipo 'KeyError' +dicionario["quatro"] # Gera uma exceção KeyError + +# Você pode usar o método 'get' para evitar gerar a exceção 'KeyError'. +# Ao invés de gerar essa exceção, irá retornar 'None' se a chave não existir. +dicionario.get("um") #=> 1 +dicionario.get("quatro") #=> None +# O método 'get' suporta um argumento que diz qual valor deverá ser +# retornado se a chave não existir (ao invés de 'None'). +dicionario.get("um", 4) #=> 1 +dicionario.get("quatro", 4) #=> 4 + +# O método 'setdefault' é um jeito seguro de adicionar um novo par +# chave-valor a um dicionário, associando um valor padrão imutável à uma chave +dicionario.setdefault("cinco", 5) # dicionario["cinco"] é definido como 5 +dicionario.setdefault("cinco", 6) # dicionario["cinco"] ainda é igual a 5 + + +# Conjuntos (ou sets) armazenam ... bem, conjuntos +# Nota: lembre-se que conjuntos não admitem elementos repetidos! +conjunto_vazio = set() +# Podemos inicializar um conjunto com valores +conjunto = set([1, 2, 2, 3, 4]) # conjunto é set([1, 2, 3, 4]), sem repetição! + +# Desde o Python 2.7, {} pode ser usado para declarar um conjunto +conjunto = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Adicione mais ítens a um conjunto com 'add' +conjunto.add(5) # conjunto agora é {1, 2, 3, 4, 5} + +# Calcule a intersecção de dois conjuntos com & +outro_conj = {3, 4, 5, 6} +conjunto & outro_conj #=> {3, 4, 5} + +# Calcule a união de dois conjuntos com | +conjunto | outro_conj #=> {1, 2, 3, 4, 5, 6} + +# E a diferença entre dois conjuntos com - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Veja se um elemento existe em um conjunto usando 'in' +2 in conjunto #=> True +10 in conjunto #=> False + + +#################################################### +## 3. Controle +#################################################### + +# Para começar, vamos apenas criar uma variável +alguma_var = 5 + +# Aqui está uma expressão 'if'. Veja como a identação é importante em Python! +# Esses comandos irão imprimir "alguma_var é menor que 10" +if alguma_var > 10: + print "some_var é maior que 10." +elif some_var < 10: # Esse 'elif' é opcional + print "some_var é menor que 10." +else: # Esse 'else' também é opcional + print "some_var é igual a 10." + + +""" +Laços (ou loops) 'for' iteram em listas. +Irá imprimir: + cachorro é um mamífero + gato é um mamífero + rato é um mamífero +""" +for animal in ["cachorro", "gato", "rato"]: + # Você pode usar % para interpolar strings formatadas + print "%s é um mamífero" % animal + +""" +A função `range(um número)` retorna uma lista de números +do zero até o número dado. +Irá imprimir: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +Laços 'while' executam enquanto uma condição dada for verdadeira. +Irá imprimir: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Isso é um atalho para a expressão x = x + 1 + +# Tratamos excessões usando o bloco try/except +# Funciona em Python 2.6 e versões superiores: + +try: + # Use 'raise' para gerar um erro + raise IndexError("Isso é um erro de índice") +except IndexError as e: + pass # Pass é um operador que não faz nada, deixa passar. + # Usualmente você iria tratar a exceção aqui... + + +#################################################### +## 4. Funções +#################################################### + +# Use 'def' para definir novas funções +def soma(x, y): + print "x é %s e y é %s" % (x, y) + return x + y # Retorne valores usando 'return' + +# Chamando funções com parâmetros +soma(5, 6) #=> imprime "x é 5 e y é 6" e retorna o valor 11 + +# Um outro jeito de chamar funções é especificando explicitamente os valores +# de cada parâmetro com chaves +soma(y=6, x=5) # Argumentos com chaves podem vir em qualquer ordem. + +# Você pode definir funções que recebem um número qualquer de argumentos +# (respeitando a sua ordem) +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Você também pode definir funções que recebem um número qualquer de argumentos +# com chaves +def args_com_chaves(**ch_args): + return ch_args + +# Vamos chamar essa função para ver o que acontece +args_com_chaves(pe="grande", lago="Ness") #=> {"pe": "grande", "lago": "Ness"} + +# Você pode fazer as duas coisas ao mesmo tempo, se desejar +def todos_args(*args, **ch_wargs): + print args + print ch_args +""" +todos_args(1, 2, a=3, b=4) imprime: + (1, 2) + {"a": 3, "b": 4} +""" + +# Quando você chamar funções, pode fazer o oposto do que fizemos até agora! +# Podemos usar * para expandir tuplas de argumentos e ** para expandir +# dicionários de argumentos com chave. +args = (1, 2, 3, 4) +ch_args = {"a": 3, "b": 4} +todos_args(*args) # equivalente a todos_args(1, 2, 3, 4) +todos_args(**ch_args) # equivalente a todos_args(a=3, b=4) +todos_args(*args, **ch_args) # equivalente a todos_args(1, 2, 3, 4, a=3, b=4) + +# Em Python, funções são elementos de primeira ordem (são como objetos, +# strings ou números) +def cria_somador(x): + def somador(y): + return x + y + return somador + +soma_10 = cria_somador(10) +soma_10(3) #=> 13 + +# Desta forma, existem também funções anônimas +(lambda x: x > 2)(3) #=> True + +# E existem funções de alta ordem por padrão +map(soma_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] +reduce(lambda x, y: x + y, [3, 4, 5, 6, 7]) #=> 25 + +# Nós podemos usar compreensão de listas para mapear e filtrar também +[soma_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#################################################### +## 5. Classes +#################################################### + +# Para criar uma nova classe, devemos herdar de 'object' +class Humano(object): + + # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa + # classe + especie = "H. sapiens" + + # Definimos um inicializador básico + def __init__(self, nome): + # Atribui o valor de argumento dado a um atributo da instância + self.nome = nome + + # Um método de instância. Todos os métodos levam 'self' como primeiro + # argumento + def diga(self, msg): + return "%s: %s" % (self.nome, msg) + + # Um método de classe é compartilhado por todas as instâncias + # Eles são chamados passando o nome da classe como primeiro argumento + @classmethod + def get_especie(cls): + return cls.especie + + # Um método estático é chamado sem uma referência a classe ou instância + @staticmethod + def ronca(): + return "*arrrrrrr*" + + +# Instancie uma classe +i = Humano(nome="Ivone") +print i.diga("oi") # imprime "Ivone: oi" + +j = Human("Joel") +print j.say("olá") #prints out "Joel: olá" + +# Chame nosso método de classe +i.get_especie() #=> "H. sapiens" + +# Modifique um atributo compartilhado +Humano.especie = "H. neanderthalensis" +i.get_especie() #=> "H. neanderthalensis" +j.get_especie() #=> "H. neanderthalensis" + +# Chame o método estático +Humano.ronca() #=> "*arrrrrrr*" + + +#################################################### +## 6. Módulos +#################################################### + +# Você pode importar módulos +import math +print math.sqrt(16) #=> 4.0 + +# Você pode importar funções específicas de um módulo +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Você também pode importar todas as funções de um módulo +# Atenção: isso não é recomendado! +from math import * + +# Você pode usar apelidos para os módulos, encurtando seus nomes +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Módulos em Python são apenas arquivos Python. Você +# pode escrever o seu próprio módulo e importá-lo. O nome do +# módulo será o mesmo que o nome do arquivo. + +# Você pode descobrir quais funções e atributos +# estão definidos em um módulo qualquer. +import math +dir(math) + + +``` + +## Pronto para mais? + +### Online e gratuito + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### Livros impressos + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/python.html.markdown b/python.html.markdown deleted file mode 100644 index 0cc33a80..00000000 --- a/python.html.markdown +++ /dev/null @@ -1,827 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] - - ["Amin Bandali", "https://aminb.org"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["evuez", "http://github.com/evuez"] - - ["asyne", "https://github.com/justblah"] - - ["habi", "http://github.com/habi"] - - ["Rommel Martinez", "https://ebzzry.io"] -filename: learnpython.py ---- - -Python was created by Guido Van Rossum in the early 90s. It is now one of the -most popular languages in existence. I fell in love with Python for its -syntactic clarity. It's basically executable pseudocode. - -Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) -or louiedinh [at] [google's email service] - -Note: This article applies to Python 2.7 specifically, but should be applicable -to Python 2.x. Python 2.7 is reaching end of life and will stop being -maintained in 2020, it is though recommended to start learning Python with -Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). - -It is also possible to write Python code which is compatible with Python 2.7 -and 3.x at the same time, using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports -allow you to write Python 3 code that will run on Python 2, so check out the -Python 3 tutorial. - -```python - -# Single line comments start with a number symbol. - -""" Multiline strings can be written - using three "s, and are often used - as comments -""" - -#################################################### -# 1. Primitive Datatypes and Operators -#################################################### - -# You have numbers -3 # => 3 - -# Math is what you would expect -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7 - -# Division is a bit tricky. It is integer division and floors the results -# automatically. -5 / 2 # => 2 - -# To fix division we need to learn about floats. -2.0 # This is a float -11.0 / 4.0 # => 2.75 ahhh...much better - -# Result of integer division truncated down both for positive and negative. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # works on floats too --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Note that we can also import division module(Section 6 Modules) -# to carry out normal division with just one '/'. -from __future__ import division - -11 / 4 # => 2.75 ...normal division -11 // 4 # => 2 ...floored division - -# Modulo operation -7 % 3 # => 1 - -# Exponentiation (x to the yth power) -2 ** 4 # => 16 - -# Enforce precedence with parentheses -(1 + 3) * 2 # => 8 - -# Boolean Operators -# Note "and" and "or" are case-sensitive -True and False # => False -False or True # => True - -# Note using Bool operators with ints -0 and 2 # => 0 --5 or 0 # => -5 -0 == False # => True -2 == True # => False -1 == True # => True - -# negate with not -not True # => False -not False # => True - -# Equality is == -1 == 1 # => True -2 == 1 # => False - -# Inequality is != -1 != 1 # => False -2 != 1 # => True - -# More comparisons -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Comparisons can be chained! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# Strings are created with " or ' -"This is a string." -'This is also a string.' - -# Strings can be added too! -"Hello " + "world!" # => "Hello world!" -# Strings can be added without using '+' -"Hello " "world!" # => "Hello world!" - -# ... or multiplied -"Hello" * 3 # => "HelloHelloHello" - -# A string can be treated like a list of characters -"This is a string"[0] # => 'T' - -# You can find the length of a string -len("This is a string") # => 16 - -# String formatting with % -# Even though the % string operator will be deprecated on Python 3.1 and removed -# later at some time, it may still be good to know how it works. -x = 'apple' -y = 'lemon' -z = "The items in the basket are %s and %s" % (x, y) - -# A newer way to format strings is the format method. -# This method is the preferred way -"{} is a {}".format("This", "placeholder") -"{0} can be {1}".format("strings", "formatted") -# You can use keywords if you don't want to count. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") - -# None is an object -None # => None - -# Don't use the equality "==" symbol to compare objects to None -# Use "is" instead -"etc" is None # => False -None is None # => True - -# The 'is' operator tests for object identity. This isn't -# very useful when dealing with primitive values, but is -# very useful when dealing with objects. - -# Any object can be used in a Boolean context. -# The following values are considered falsey: -# - None -# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j) -# - empty sequences (e.g., '', (), []) -# - empty containers (e.g., {}, set()) -# - instances of user-defined classes meeting certain conditions -# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ -# -# All other values are truthy (using the bool() function on them returns True). -bool(0) # => False -bool("") # => False - - -#################################################### -# 2. Variables and Collections -#################################################### - -# Python has a print statement -print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! - -# Simple way to get input data from console -input_string_var = raw_input( - "Enter some data: ") # Returns the data as a string -input_var = input("Enter some data: ") # Evaluates the data as python code -# Warning: Caution is recommended for input() method usage -# Note: In python 3, input() is deprecated and raw_input() is renamed to input() - -# No need to declare variables before assigning to them. -some_var = 5 # Convention is to use lower_case_with_underscores -some_var # => 5 - -# Accessing a previously unassigned variable is an exception. -# See Control Flow to learn more about exception handling. -some_other_var # Raises a name error - -# if can be used as an expression -# Equivalent of C's '?:' ternary operator -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# Lists store sequences -li = [] -# You can start with a prefilled list -other_li = [4, 5, 6] - -# Add stuff to the end of a list with append -li.append(1) # li is now [1] -li.append(2) # li is now [1, 2] -li.append(4) # li is now [1, 2, 4] -li.append(3) # li is now [1, 2, 4, 3] -# Remove from the end with pop -li.pop() # => 3 and li is now [1, 2, 4] -# Let's put it back -li.append(3) # li is now [1, 2, 4, 3] again. - -# Access a list like you would any array -li[0] # => 1 -# Assign new values to indexes that have already been initialized with = -li[0] = 42 -li[0] # => 42 -li[0] = 1 # Note: setting it back to the original value -# Look at the last element -li[-1] # => 3 - -# Looking out of bounds is an IndexError -li[4] # Raises an IndexError - -# You can look at ranges with slice syntax. -# (It's a closed/open range for you mathy types.) -li[1:3] # => [2, 4] -# Omit the beginning -li[2:] # => [4, 3] -# Omit the end -li[:3] # => [1, 2, 4] -# Select every second entry -li[::2] # =>[1, 4] -# Reverse a copy of the list -li[::-1] # => [3, 4, 2, 1] -# Use any combination of these to make advanced slices -# li[start:end:step] - -# Remove arbitrary elements from a list with "del" -del li[2] # li is now [1, 2, 3] - -# You can add lists -li + other_li # => [1, 2, 3, 4, 5, 6] -# Note: values for li and for other_li are not modified. - -# Concatenate lists with "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] - -# Remove first occurrence of a value -li.remove(2) # li is now [1, 3, 4, 5, 6] -li.remove(2) # Raises a ValueError as 2 is not in the list - -# Insert an element at a specific index -li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again - -# Get the index of the first item found -li.index(2) # => 1 -li.index(7) # Raises a ValueError as 7 is not in the list - -# Check for existence in a list with "in" -1 in li # => True - -# Examine the length with "len()" -len(li) # => 6 - -# Tuples are like lists but are immutable. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Raises a TypeError - -# You can do all those list thingies on tuples too -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# You can unpack tuples (or lists) into variables -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 -d, e, f = 4, 5, 6 # you can leave out the parentheses -# Tuples are created by default if you leave out the parentheses -g = 4, 5, 6 # => (4, 5, 6) -# Now look how easy it is to swap two values -e, d = d, e # d is now 5 and e is now 4 - -# Dictionaries store mappings -empty_dict = {} -# Here is a prefilled dictionary -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Look up values with [] -filled_dict["one"] # => 1 - -# Get all keys as a list with "keys()" -filled_dict.keys() # => ["three", "two", "one"] -# Note - Dictionary key ordering is not guaranteed. -# Your results might not match this exactly. - -# Get all values as a list with "values()" -filled_dict.values() # => [3, 2, 1] -# Note - Same as above regarding key ordering. - -# Get all key-value pairs as a list of tuples with "items()" -filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] - -# Check for existence of keys in a dictionary with "in" -"one" in filled_dict # => True -1 in filled_dict # => False - -# Looking up a non-existing key is a KeyError -filled_dict["four"] # KeyError - -# Use "get()" method to avoid the KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# The get method supports a default argument when the value is missing -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 -# note that filled_dict.get("four") is still => None -# (get doesn't set the value in the dictionary) - -# set the value of a key with a syntax similar to lists -filled_dict["four"] = 4 # now, filled_dict["four"] => 4 - -# "setdefault()" inserts into a dictionary only if the given key isn't present -filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 - -# You can declare sets (which are like unordered lists that cannot contain -# duplicate values) using the set object. -empty_set = set() -# Initialize a "set()" with a bunch of values -some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4]) - -# order is not guaranteed, even though it may sometimes look sorted -another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4]) - -# Since Python 2.7, {} can be used to declare a set -filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} - -# Add more items to a set -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} - -# Do set intersection with & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# Do set union with | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Do set difference with - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Do set symmetric difference with ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Check if set on the left is a superset of set on the right -{1, 2} >= {1, 2, 3} # => False - -# Check if set on the left is a subset of set on the right -{1, 2} <= {1, 2, 3} # => True - -# Check for existence in a set with in -2 in filled_set # => True -10 in filled_set # => False -10 not in filled_set # => True - -# Check data type of variable -type(li) # => list -type(filled_dict) # => dict -type(5) # => int - - -#################################################### -# 3. Control Flow -#################################################### - -# Let's just make a variable -some_var = 5 - -# Here is an if statement. Indentation is significant in python! -# prints "some_var is smaller than 10" -if some_var > 10: - print "some_var is totally bigger than 10." -elif some_var < 10: # This elif clause is optional. - print "some_var is smaller than 10." -else: # This is optional too. - print "some_var is indeed 10." - -""" -For loops iterate over lists -prints: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # You can use {0} to interpolate formatted strings. (See above.) - print "{0} is a mammal".format(animal) - -""" -"range(number)" returns a list of numbers -from zero to the given number -prints: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -"range(lower, upper)" returns a list of numbers -from the lower number to the upper number -prints: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print i - -""" -While loops go until a condition is no longer met. -prints: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # Shorthand for x = x + 1 - -# Handle exceptions with a try/except block - -# Works on Python 2.6 and up: -try: - # Use "raise" to raise an error - raise IndexError("This is an index error") -except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. -except (TypeError, NameError): - pass # Multiple exceptions can be handled together, if required. -else: # Optional clause to the try/except block. Must follow all except blocks - print "All good!" # Runs only if the code in try raises no exceptions -finally: # Execute under all circumstances - print "We can clean up resources here" - -# Instead of try/finally to cleanup resources you can use a with statement -with open("myfile.txt") as f: - for line in f: - print line - - -#################################################### -# 4. Functions -#################################################### - -# Use "def" to create new functions -def add(x, y): - print "x is {0} and y is {1}".format(x, y) - return x + y # Return values with a return statement - - -# Calling functions with parameters -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 - -# Another way to call functions is with keyword arguments -add(y=6, x=5) # Keyword arguments can arrive in any order. - - -# You can define functions that take a variable number of -# positional args, which will be interpreted as a tuple by using * -def varargs(*args): - return args - - -varargs(1, 2, 3) # => (1, 2, 3) - - -# You can define functions that take a variable number of -# keyword args, as well, which will be interpreted as a dict by using ** -def keyword_args(**kwargs): - return kwargs - - -# Let's call it to see what happens -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# You can do both at once, if you like -def all_the_args(*args, **kwargs): - print args - print kwargs - - -""" -all_the_args(1, 2, a=3, b=4) prints: - (1, 2) - {"a": 3, "b": 4} -""" - -# When calling functions, you can do the opposite of args/kwargs! -# Use * to expand positional args and use ** to expand keyword args. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4) - - -# you can pass args and kwargs along to other functions that take args/kwargs -# by expanding them with * and ** respectively -def pass_all_the_args(*args, **kwargs): - all_the_args(*args, **kwargs) - print varargs(*args) - print keyword_args(**kwargs) - - -# Function Scope -x = 5 - - -def set_x(num): - # Local var x not the same as global variable x - x = num # => 43 - print x # => 43 - - -def set_global_x(num): - global x - print x # => 5 - x = num # global var x is now set to 6 - print x # => 6 - - -set_x(43) -set_global_x(6) - - -# Python has first class functions -def create_adder(x): - def adder(y): - return x + y - - return adder - - -add_10 = create_adder(10) -add_10(3) # => 13 - -# There are also anonymous functions -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# There are built-in higher order functions -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] - -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# We can use list comprehensions for nice maps and filters -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# You can construct set and dict comprehensions as well. -{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'} -{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -# 5. Classes -#################################################### - -# We subclass from object to get a class. -class Human(object): - # A class attribute. It is shared by all instances of this class - species = "H. sapiens" - - # Basic initializer, this is called when this class is instantiated. - # Note that the double leading and trailing underscores denote objects - # or attributes that are used by python but that live in user-controlled - # namespaces. You should not invent such names on your own. - def __init__(self, name): - # Assign the argument to the instance's name attribute - self.name = name - - # Initialize property - self.age = 0 - - # An instance method. All methods take "self" as the first argument - def say(self, msg): - return "{0}: {1}".format(self.name, msg) - - # A class method is shared among all instances - # They are called with the calling class as the first argument - @classmethod - def get_species(cls): - return cls.species - - # A static method is called without a class or instance reference - @staticmethod - def grunt(): - return "*grunt*" - - # A property is just like a getter. - # It turns the method age() into an read-only attribute - # of the same name. - @property - def age(self): - return self._age - - # This allows the property to be set - @age.setter - def age(self, age): - self._age = age - - # This allows the property to be deleted - @age.deleter - def age(self): - del self._age - - -# Instantiate a class -i = Human(name="Ian") -print i.say("hi") # prints out "Ian: hi" - -j = Human("Joel") -print j.say("hello") # prints out "Joel: hello" - -# Call our class method -i.get_species() # => "H. sapiens" - -# Change the shared attribute -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# Call the static method -Human.grunt() # => "*grunt*" - -# Update the property -i.age = 42 - -# Get the property -i.age # => 42 - -# Delete the property -del i.age -i.age # => raises an AttributeError - -#################################################### -# 6. Modules -#################################################### - -# You can import modules -import math - -print math.sqrt(16) # => 4.0 - -# You can get specific functions from a module -from math import ceil, floor - -print ceil(3.7) # => 4.0 -print floor(3.7) # => 3.0 - -# You can import all functions from a module. -# Warning: this is not recommended -from math import * - -# You can shorten module names -import math as m - -math.sqrt(16) == m.sqrt(16) # => True -# you can also test that the functions are equivalent -from math import sqrt - -math.sqrt == m.sqrt == sqrt # => True - -# Python modules are just ordinary python files. You -# can write your own, and import them. The name of the -# module is the same as the name of the file. - -# You can find out which functions and attributes -# defines a module. -import math - -dir(math) - - -# If you have a Python script named math.py in the same -# folder as your current script, the file math.py will -# be loaded instead of the built-in Python module. -# This happens because the local folder has priority -# over Python's built-in libraries. - - -#################################################### -# 7. Advanced -#################################################### - -# Generators -# A generator "generates" values as they are requested instead of storing -# everything up front - -# The following method (*NOT* a generator) will double all values and store it -# in `double_arr`. For large size of iterables, that might get huge! -def double_numbers(iterable): - double_arr = [] - for i in iterable: - double_arr.append(i + i) - return double_arr - - -# Running the following would mean we'll double all values first and return all -# of them back to be checked by our condition -for value in double_numbers(range(1000000)): # `test_non_generator` - print value - if value > 5: - break - - -# We could instead use a generator to "generate" the doubled value as the item -# is being requested -def double_numbers_generator(iterable): - for i in iterable: - yield i + i - - -# Running the same code as before, but with a generator, now allows us to iterate -# over the values and doubling them one by one as they are being consumed by -# our logic. Hence as soon as we see a value > 5, we break out of the -# loop and don't need to double most of the values sent in (MUCH FASTER!) -for value in double_numbers_generator(xrange(1000000)): # `test_generator` - print value - if value > 5: - break - -# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`? -# Just as `double_numbers_generator` is the generator version of `double_numbers` -# We have `xrange` as the generator version of `range` -# `range` would return back and array with 1000000 values for us to use -# `xrange` would generate 1000000 values for us as we request / iterate over those items - -# Just as you can create a list comprehension, you can create generator -# comprehensions as well. -values = (-x for x in [1, 2, 3, 4, 5]) -for x in values: - print(x) # prints -1 -2 -3 -4 -5 to console/terminal - -# You can also cast a generator comprehension directly to a list. -values = (-x for x in [1, 2, 3, 4, 5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - -# Decorators -# A decorator is a higher order function, which accepts and returns a function. -# Simple usage example – add_apples decorator will add 'Apple' element into -# fruits list returned by get_fruits target function. -def add_apples(func): - def get_fruits(): - fruits = func() - fruits.append('Apple') - return fruits - return get_fruits - -@add_apples -def get_fruits(): - return ['Banana', 'Mango', 'Orange'] - -# Prints out the list of fruits with 'Apple' element in it: -# Banana, Mango, Orange, Apple -print ', '.join(get_fruits()) - -# in this example beg wraps say -# Beg will call say. If say_please is True then it will change the returned -# message -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print say() # Can you buy me a beer? -print say(say_please=True) # Can you buy me a beer? Please! I am poor :( -``` - -## Ready For More? - -### Free Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [LearnPython](http://www.learnpython.org/) -* [Fullstack Python](https://www.fullstackpython.com/) - -### Dead Tree - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/pythonlegacy.html.markdown b/pythonlegacy.html.markdown new file mode 100644 index 00000000..0cc33a80 --- /dev/null +++ b/pythonlegacy.html.markdown @@ -0,0 +1,827 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "https://aminb.org"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] + - ["asyne", "https://github.com/justblah"] + - ["habi", "http://github.com/habi"] + - ["Rommel Martinez", "https://ebzzry.io"] +filename: learnpython.py +--- + +Python was created by Guido Van Rossum in the early 90s. It is now one of the +most popular languages in existence. I fell in love with Python for its +syntactic clarity. It's basically executable pseudocode. + +Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) +or louiedinh [at] [google's email service] + +Note: This article applies to Python 2.7 specifically, but should be applicable +to Python 2.x. Python 2.7 is reaching end of life and will stop being +maintained in 2020, it is though recommended to start learning Python with +Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). + +It is also possible to write Python code which is compatible with Python 2.7 +and 3.x at the same time, using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports +allow you to write Python 3 code that will run on Python 2, so check out the +Python 3 tutorial. + +```python + +# Single line comments start with a number symbol. + +""" Multiline strings can be written + using three "s, and are often used + as comments +""" + +#################################################### +# 1. Primitive Datatypes and Operators +#################################################### + +# You have numbers +3 # => 3 + +# Math is what you would expect +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# Division is a bit tricky. It is integer division and floors the results +# automatically. +5 / 2 # => 2 + +# To fix division we need to learn about floats. +2.0 # This is a float +11.0 / 4.0 # => 2.75 ahhh...much better + +# Result of integer division truncated down both for positive and negative. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Note that we can also import division module(Section 6 Modules) +# to carry out normal division with just one '/'. +from __future__ import division + +11 / 4 # => 2.75 ...normal division +11 // 4 # => 2 ...floored division + +# Modulo operation +7 % 3 # => 1 + +# Exponentiation (x to the yth power) +2 ** 4 # => 16 + +# Enforce precedence with parentheses +(1 + 3) * 2 # => 8 + +# Boolean Operators +# Note "and" and "or" are case-sensitive +True and False # => False +False or True # => True + +# Note using Bool operators with ints +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# negate with not +not True # => False +not False # => True + +# Equality is == +1 == 1 # => True +2 == 1 # => False + +# Inequality is != +1 != 1 # => False +2 != 1 # => True + +# More comparisons +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Comparisons can be chained! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Strings are created with " or ' +"This is a string." +'This is also a string.' + +# Strings can be added too! +"Hello " + "world!" # => "Hello world!" +# Strings can be added without using '+' +"Hello " "world!" # => "Hello world!" + +# ... or multiplied +"Hello" * 3 # => "HelloHelloHello" + +# A string can be treated like a list of characters +"This is a string"[0] # => 'T' + +# You can find the length of a string +len("This is a string") # => 16 + +# String formatting with % +# Even though the % string operator will be deprecated on Python 3.1 and removed +# later at some time, it may still be good to know how it works. +x = 'apple' +y = 'lemon' +z = "The items in the basket are %s and %s" % (x, y) + +# A newer way to format strings is the format method. +# This method is the preferred way +"{} is a {}".format("This", "placeholder") +"{0} can be {1}".format("strings", "formatted") +# You can use keywords if you don't want to count. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") + +# None is an object +None # => None + +# Don't use the equality "==" symbol to compare objects to None +# Use "is" instead +"etc" is None # => False +None is None # => True + +# The 'is' operator tests for object identity. This isn't +# very useful when dealing with primitive values, but is +# very useful when dealing with objects. + +# Any object can be used in a Boolean context. +# The following values are considered falsey: +# - None +# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j) +# - empty sequences (e.g., '', (), []) +# - empty containers (e.g., {}, set()) +# - instances of user-defined classes meeting certain conditions +# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# All other values are truthy (using the bool() function on them returns True). +bool(0) # => False +bool("") # => False + + +#################################################### +# 2. Variables and Collections +#################################################### + +# Python has a print statement +print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! + +# Simple way to get input data from console +input_string_var = raw_input( + "Enter some data: ") # Returns the data as a string +input_var = input("Enter some data: ") # Evaluates the data as python code +# Warning: Caution is recommended for input() method usage +# Note: In python 3, input() is deprecated and raw_input() is renamed to input() + +# No need to declare variables before assigning to them. +some_var = 5 # Convention is to use lower_case_with_underscores +some_var # => 5 + +# Accessing a previously unassigned variable is an exception. +# See Control Flow to learn more about exception handling. +some_other_var # Raises a name error + +# if can be used as an expression +# Equivalent of C's '?:' ternary operator +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Lists store sequences +li = [] +# You can start with a prefilled list +other_li = [4, 5, 6] + +# Add stuff to the end of a list with append +li.append(1) # li is now [1] +li.append(2) # li is now [1, 2] +li.append(4) # li is now [1, 2, 4] +li.append(3) # li is now [1, 2, 4, 3] +# Remove from the end with pop +li.pop() # => 3 and li is now [1, 2, 4] +# Let's put it back +li.append(3) # li is now [1, 2, 4, 3] again. + +# Access a list like you would any array +li[0] # => 1 +# Assign new values to indexes that have already been initialized with = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Note: setting it back to the original value +# Look at the last element +li[-1] # => 3 + +# Looking out of bounds is an IndexError +li[4] # Raises an IndexError + +# You can look at ranges with slice syntax. +# (It's a closed/open range for you mathy types.) +li[1:3] # => [2, 4] +# Omit the beginning +li[2:] # => [4, 3] +# Omit the end +li[:3] # => [1, 2, 4] +# Select every second entry +li[::2] # =>[1, 4] +# Reverse a copy of the list +li[::-1] # => [3, 4, 2, 1] +# Use any combination of these to make advanced slices +# li[start:end:step] + +# Remove arbitrary elements from a list with "del" +del li[2] # li is now [1, 2, 3] + +# You can add lists +li + other_li # => [1, 2, 3, 4, 5, 6] +# Note: values for li and for other_li are not modified. + +# Concatenate lists with "extend()" +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# Remove first occurrence of a value +li.remove(2) # li is now [1, 3, 4, 5, 6] +li.remove(2) # Raises a ValueError as 2 is not in the list + +# Insert an element at a specific index +li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again + +# Get the index of the first item found +li.index(2) # => 1 +li.index(7) # Raises a ValueError as 7 is not in the list + +# Check for existence in a list with "in" +1 in li # => True + +# Examine the length with "len()" +len(li) # => 6 + +# Tuples are like lists but are immutable. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Raises a TypeError + +# You can do all those list thingies on tuples too +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# You can unpack tuples (or lists) into variables +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +d, e, f = 4, 5, 6 # you can leave out the parentheses +# Tuples are created by default if you leave out the parentheses +g = 4, 5, 6 # => (4, 5, 6) +# Now look how easy it is to swap two values +e, d = d, e # d is now 5 and e is now 4 + +# Dictionaries store mappings +empty_dict = {} +# Here is a prefilled dictionary +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Look up values with [] +filled_dict["one"] # => 1 + +# Get all keys as a list with "keys()" +filled_dict.keys() # => ["three", "two", "one"] +# Note - Dictionary key ordering is not guaranteed. +# Your results might not match this exactly. + +# Get all values as a list with "values()" +filled_dict.values() # => [3, 2, 1] +# Note - Same as above regarding key ordering. + +# Get all key-value pairs as a list of tuples with "items()" +filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] + +# Check for existence of keys in a dictionary with "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# Looking up a non-existing key is a KeyError +filled_dict["four"] # KeyError + +# Use "get()" method to avoid the KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# The get method supports a default argument when the value is missing +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 +# note that filled_dict.get("four") is still => None +# (get doesn't set the value in the dictionary) + +# set the value of a key with a syntax similar to lists +filled_dict["four"] = 4 # now, filled_dict["four"] => 4 + +# "setdefault()" inserts into a dictionary only if the given key isn't present +filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 + +# You can declare sets (which are like unordered lists that cannot contain +# duplicate values) using the set object. +empty_set = set() +# Initialize a "set()" with a bunch of values +some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4]) + +# order is not guaranteed, even though it may sometimes look sorted +another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4]) + +# Since Python 2.7, {} can be used to declare a set +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Add more items to a set +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Do set intersection with & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Do set union with | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Do set difference with - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Do set symmetric difference with ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Check if set on the left is a superset of set on the right +{1, 2} >= {1, 2, 3} # => False + +# Check if set on the left is a subset of set on the right +{1, 2} <= {1, 2, 3} # => True + +# Check for existence in a set with in +2 in filled_set # => True +10 in filled_set # => False +10 not in filled_set # => True + +# Check data type of variable +type(li) # => list +type(filled_dict) # => dict +type(5) # => int + + +#################################################### +# 3. Control Flow +#################################################### + +# Let's just make a variable +some_var = 5 + +# Here is an if statement. Indentation is significant in python! +# prints "some_var is smaller than 10" +if some_var > 10: + print "some_var is totally bigger than 10." +elif some_var < 10: # This elif clause is optional. + print "some_var is smaller than 10." +else: # This is optional too. + print "some_var is indeed 10." + +""" +For loops iterate over lists +prints: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # You can use {0} to interpolate formatted strings. (See above.) + print "{0} is a mammal".format(animal) + +""" +"range(number)" returns a list of numbers +from zero to the given number +prints: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(lower, upper)" returns a list of numbers +from the lower number to the upper number +prints: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +While loops go until a condition is no longer met. +prints: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Shorthand for x = x + 1 + +# Handle exceptions with a try/except block + +# Works on Python 2.6 and up: +try: + # Use "raise" to raise an error + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass is just a no-op. Usually you would do recovery here. +except (TypeError, NameError): + pass # Multiple exceptions can be handled together, if required. +else: # Optional clause to the try/except block. Must follow all except blocks + print "All good!" # Runs only if the code in try raises no exceptions +finally: # Execute under all circumstances + print "We can clean up resources here" + +# Instead of try/finally to cleanup resources you can use a with statement +with open("myfile.txt") as f: + for line in f: + print line + + +#################################################### +# 4. Functions +#################################################### + +# Use "def" to create new functions +def add(x, y): + print "x is {0} and y is {1}".format(x, y) + return x + y # Return values with a return statement + + +# Calling functions with parameters +add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 + +# Another way to call functions is with keyword arguments +add(y=6, x=5) # Keyword arguments can arrive in any order. + + +# You can define functions that take a variable number of +# positional args, which will be interpreted as a tuple by using * +def varargs(*args): + return args + + +varargs(1, 2, 3) # => (1, 2, 3) + + +# You can define functions that take a variable number of +# keyword args, as well, which will be interpreted as a dict by using ** +def keyword_args(**kwargs): + return kwargs + + +# Let's call it to see what happens +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# You can do both at once, if you like +def all_the_args(*args, **kwargs): + print args + print kwargs + + +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# When calling functions, you can do the opposite of args/kwargs! +# Use * to expand positional args and use ** to expand keyword args. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4) + + +# you can pass args and kwargs along to other functions that take args/kwargs +# by expanding them with * and ** respectively +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + + +# Function Scope +x = 5 + + +def set_x(num): + # Local var x not the same as global variable x + x = num # => 43 + print x # => 43 + + +def set_global_x(num): + global x + print x # => 5 + x = num # global var x is now set to 6 + print x # => 6 + + +set_x(43) +set_global_x(6) + + +# Python has first class functions +def create_adder(x): + def adder(y): + return x + y + + return adder + + +add_10 = create_adder(10) +add_10(3) # => 13 + +# There are also anonymous functions +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# There are built-in higher order functions +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# We can use list comprehensions for nice maps and filters +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# You can construct set and dict comprehensions as well. +{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'} +{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +# 5. Classes +#################################################### + +# We subclass from object to get a class. +class Human(object): + # A class attribute. It is shared by all instances of this class + species = "H. sapiens" + + # Basic initializer, this is called when this class is instantiated. + # Note that the double leading and trailing underscores denote objects + # or attributes that are used by python but that live in user-controlled + # namespaces. You should not invent such names on your own. + def __init__(self, name): + # Assign the argument to the instance's name attribute + self.name = name + + # Initialize property + self.age = 0 + + # An instance method. All methods take "self" as the first argument + def say(self, msg): + return "{0}: {1}".format(self.name, msg) + + # A class method is shared among all instances + # They are called with the calling class as the first argument + @classmethod + def get_species(cls): + return cls.species + + # A static method is called without a class or instance reference + @staticmethod + def grunt(): + return "*grunt*" + + # A property is just like a getter. + # It turns the method age() into an read-only attribute + # of the same name. + @property + def age(self): + return self._age + + # This allows the property to be set + @age.setter + def age(self, age): + self._age = age + + # This allows the property to be deleted + @age.deleter + def age(self): + del self._age + + +# Instantiate a class +i = Human(name="Ian") +print i.say("hi") # prints out "Ian: hi" + +j = Human("Joel") +print j.say("hello") # prints out "Joel: hello" + +# Call our class method +i.get_species() # => "H. sapiens" + +# Change the shared attribute +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Call the static method +Human.grunt() # => "*grunt*" + +# Update the property +i.age = 42 + +# Get the property +i.age # => 42 + +# Delete the property +del i.age +i.age # => raises an AttributeError + +#################################################### +# 6. Modules +#################################################### + +# You can import modules +import math + +print math.sqrt(16) # => 4.0 + +# You can get specific functions from a module +from math import ceil, floor + +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m + +math.sqrt(16) == m.sqrt(16) # => True +# you can also test that the functions are equivalent +from math import sqrt + +math.sqrt == m.sqrt == sqrt # => True + +# Python modules are just ordinary python files. You +# can write your own, and import them. The name of the +# module is the same as the name of the file. + +# You can find out which functions and attributes +# defines a module. +import math + +dir(math) + + +# If you have a Python script named math.py in the same +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. +# This happens because the local folder has priority +# over Python's built-in libraries. + + +#################################################### +# 7. Advanced +#################################################### + +# Generators +# A generator "generates" values as they are requested instead of storing +# everything up front + +# The following method (*NOT* a generator) will double all values and store it +# in `double_arr`. For large size of iterables, that might get huge! +def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + return double_arr + + +# Running the following would mean we'll double all values first and return all +# of them back to be checked by our condition +for value in double_numbers(range(1000000)): # `test_non_generator` + print value + if value > 5: + break + + +# We could instead use a generator to "generate" the doubled value as the item +# is being requested +def double_numbers_generator(iterable): + for i in iterable: + yield i + i + + +# Running the same code as before, but with a generator, now allows us to iterate +# over the values and doubling them one by one as they are being consumed by +# our logic. Hence as soon as we see a value > 5, we break out of the +# loop and don't need to double most of the values sent in (MUCH FASTER!) +for value in double_numbers_generator(xrange(1000000)): # `test_generator` + print value + if value > 5: + break + +# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`? +# Just as `double_numbers_generator` is the generator version of `double_numbers` +# We have `xrange` as the generator version of `range` +# `range` would return back and array with 1000000 values for us to use +# `xrange` would generate 1000000 values for us as we request / iterate over those items + +# Just as you can create a list comprehension, you can create generator +# comprehensions as well. +values = (-x for x in [1, 2, 3, 4, 5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# You can also cast a generator comprehension directly to a list. +values = (-x for x in [1, 2, 3, 4, 5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + +# Decorators +# A decorator is a higher order function, which accepts and returns a function. +# Simple usage example – add_apples decorator will add 'Apple' element into +# fruits list returned by get_fruits target function. +def add_apples(func): + def get_fruits(): + fruits = func() + fruits.append('Apple') + return fruits + return get_fruits + +@add_apples +def get_fruits(): + return ['Banana', 'Mango', 'Orange'] + +# Prints out the list of fruits with 'Apple' element in it: +# Banana, Mango, Orange, Apple +print ', '.join(get_fruits()) + +# in this example beg wraps say +# Beg will call say. If say_please is True then it will change the returned +# message +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print say() # Can you buy me a beer? +print say(say_please=True) # Can you buy me a beer? Please! I am poor :( +``` + +## Ready For More? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [LearnPython](http://www.learnpython.org/) +* [Fullstack Python](https://www.fullstackpython.com/) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/ro-ro/python-ro.html.markdown b/ro-ro/python-ro.html.markdown deleted file mode 100644 index ada0c034..00000000 --- a/ro-ro/python-ro.html.markdown +++ /dev/null @@ -1,493 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["Ovidiu Ciule", "https://github.com/ociule"] -filename: learnpython-ro.py -lang: ro-ro ---- - -Python a fost creat de Guido Van Rossum la începutul anilor '90. Python a -devenit astăzi unul din cele mai populare limbaje de programare. -M-am indrăgostit de Python pentru claritatea sa sintactică. Python este aproape -pseudocod executabil. - -Opinia dumneavoastră este binevenită! Puteţi sa imi scrieţi la [@ociule](http://twitter.com/ociule) -sau ociule [at] [google's email service] - -Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. -O versiune Python 3 va apărea în curând, în limba engleză mai întâi. - -```python -# Comentariile pe o singură linie încep cu un caracter diez. -""" Şirurile de caractere pe mai multe linii pot fi încadrate folosind trei caractere ", şi sunt des - folosite ca şi comentarii pe mai multe linii. -""" - -#################################################### -## 1. Operatori şi tipuri de date primare -#################################################### - -# Avem numere -3 #=> 3 - -# Matematica se comportă cum ne-am aştepta -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 - -# Împărţirea este un pic surprinzătoare. Este de fapt împărţire pe numere -# întregi şi rotunjeşte -# automat spre valoarea mai mică -5 / 2 #=> 2 - -# Pentru a folosi împărţirea fără rest avem nevoie de numere reale -2.0 # Acesta e un număr real -11.0 / 4.0 #=> 2.75 ahhh ... cum ne aşteptam - -# Ordinea operaţiilor se poate forţa cu paranteze -(1 + 3) * 2 #=> 8 - -# Valoriile boolene sunt şi ele valori primare -True -False - -# Pot fi negate cu operatorul not -not True #=> False -not False #=> True - -# Egalitatea este == -1 == 1 #=> True -2 == 1 #=> False - -# Inegalitate este != -1 != 1 #=> False -2 != 1 #=> True - -# Comparaţii -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True - -# Comparaţiile pot fi inlănţuite! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False - -# Şirurile de caractere pot fi încadrate cu " sau ' -"Acesta e un şir de caractere." -'Şi acesta este un şir de caractere.' - -# Şirurile de caractere pot fi adăugate! -"Hello " + "world!" #=> "Hello world!" - -# Un şir de caractere poate fi folosit ca o listă -"Acesta e un şir de caractere"[0] #=> 'A' - -# Caracterul % (procent) poate fi folosit pentru a formata şiruri de caractere : -"%s pot fi %s" % ("şirurile", "interpolate") - -# O metodă mai nouă de a formata şiruri este metoda "format" -# Este metoda recomandată -"{0} pot fi {1}".format("şirurile", "formatate") -# Puteţi folosi cuvinte cheie dacă nu doriţi sa număraţi -"{nume} vrea să mănânce {fel}".format(nume="Bob", fel="lasagna") - -# "None", care reprezintă valoarea nedefinită, e un obiect -None #=> None - -# Nu folosiţi operatorul == pentru a compara un obiect cu None -# Folosiţi operatorul "is" -"etc" is None #=> False -None is None #=> True - -# Operatorul "is" testeaza dacă obiectele sunt identice. -# Acastă operaţie nu e foarte folositoare cu tipuri primare, -# dar e foarte folositoare cu obiecte. - -# None, 0, şi şiruri de caractere goale sunt evaluate ca si fals, False. -# Toate celelalte valori sunt adevărate, True. -0 == False #=> True -"" == False #=> True - - -#################################################### -## 2. Variabile şi colecţii -#################################################### - -# Printarea este uşoară -print "Eu sunt Python. Încântat de cunoştinţă!" - - -# Nu este nevoie sa declari variabilele înainte de a le folosi -o_variabila = 5 # Convenţia este de a folosi caractere_minuscule_cu_underscore -o_variabila #=> 5 - -# Dacă accesăm o variabilă nefolosită declanşăm o excepţie. -# Vezi secţiunea Control de Execuţie pentru mai multe detalii despre excepţii. -alta_variabila # Declanşează o eroare de nume - -# "If" poate fi folosit într-o expresie. -"yahoo!" if 3 > 2 else 2 #=> "yahoo!" - -# Listele sunt folosite pentru colecţii -li = [] -# O listă poate avea valori de la început -alta_li = [4, 5, 6] - -# Se adaugă valori la sfârşitul lister cu append -li.append(1) #li e acum [1] -li.append(2) #li e acum [1, 2] -li.append(4) #li e acum [1, 2, 4] -li.append(3) #li este acum [1, 2, 4, 3] -# Se şterg de la sfarşit cu pop -li.pop() #=> 3 şi li e acum [1, 2, 4] -# Să o adaugăm înapoi valoarea -li.append(3) # li e din nou [1, 2, 4, 3] - -# Putem accesa valorile individuale dintr-o listă cu operatorul index -li[0] #=> 1 -# Valoarea speciala -1 pentru index accesează ultima valoare -li[-1] #=> 3 - -# Dacă depaşim limitele listei declanşăm o eroare IndexError -li[4] # Declanşează IndexError - -# Putem să ne uităm la intervale folosind sintaxa de "felii" -# În Python, intervalele sunt închise la început si deschise la sfârşit. -li[1:3] #=> [2, 4] -# Fără început -li[2:] #=> [4, 3] -# Fără sfarşit -li[:3] #=> [1, 2, 4] - -# Putem şterge elemente arbitrare din lista cu operatorul "del" care primeşte indexul lor -del li[2] # li e acum [1, 2, 3] - -# Listele pot fi adăugate -li + alta_li #=> [1, 2, 3, 4, 5, 6] - Notă: li si alta_li nu sunt modificate! - -# Concatenăm liste cu "extend()" -li.extend(alta_li) # Acum li este [1, 2, 3, 4, 5, 6] - -# Se verifică existenţa valorilor in lista cu "in" -1 in li #=> True - -# Şi lungimea cu "len()" -len(li) #=> 6 - - -# Tuplele sunt ca şi listele dar imutabile -tup = (1, 2, 3) -tup[0] #=> 1 -tup[0] = 3 # Declanşează TypeError - -# Pot fi folosite ca şi liste -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True - -# Tuplele pot fi despachetate -a, b, c = (1, 2, 3) # a este acum 1, b este acum 2 şi c este acum 3 -# Tuplele pot fi folosite şi fără paranteze -d, e, f = 4, 5, 6 -# Putem inversa valori foarte uşor! -e, d = d, e # d este acum 5 şi e este acum 4 - - -# Dicţionarele stochează chei şi o valoare pentru fiecare cheie -dict_gol = {} -# Şi un dicţionar cu valori -dict_cu_valori = {"unu": 1, "doi": 2, "trei": 3} - -# Căutaţi valori cu [] -dict_cu_valori["unu"] #=> 1 - -# Obţinem lista cheilor cu "keys()" -dict_cu_valori.keys() #=> ["trei", "doi", "unu"] -# Notă - ordinea cheilor obţinute cu keys() nu este garantată. -# Puteţi obţine rezultate diferite de exemplul de aici. - -# Obţinem valorile cu values() -dict_cu_valori.values() #=> [3, 2, 1] -# Notă - aceeaşi ca mai sus, aplicată asupra valorilor. - -# Verificăm existenţa unei valori cu "in" -"unu" in dict_cu_valori #=> True -1 in dict_cu_valori #=> False - -# Accesarea unei chei care nu exista declanşează o KeyError -dict_cu_valori["four"] # KeyError - -# Putem folosi metoda "get()" pentru a evita KeyError -dict_cu_valori.get("one") #=> 1 -dict_cu_valori.get("four") #=> None -# Metoda get poate primi ca al doilea argument o valoare care va fi returnată -# când cheia nu este prezentă. -dict_cu_valori.get("one", 4) #=> 1 -dict_cu_valori.get("four", 4) #=> 4 - -# "setdefault()" este o metodă pentru a adăuga chei-valori fără a le modifica, dacă cheia există deja -dict_cu_valori.setdefault("five", 5) #dict_cu_valori["five"] este acum 5 -dict_cu_valori.setdefault("five", 6) #dict_cu_valori["five"] exista deja, nu este modificată, tot 5 - - -# Set este colecţia mulţime -set_gol = set() -# Putem crea un set cu valori -un_set = set([1,2,2,3,4]) # un_set este acum set([1, 2, 3, 4]), amintiţi-vă ca mulţimile garantează unicatul! - -# În Python 2.7, {} poate fi folosit pentru un set -set_cu_valori = {1, 2, 2, 3, 4} # => {1 2 3 4} - -# Putem adăuga valori cu add -set_cu_valori.add(5) # set_cu_valori este acum {1, 2, 3, 4, 5} - -# Putem intersecta seturi -alt_set = {3, 4, 5, 6} -set_cu_valori & alt_set #=> {3, 4, 5} - -# Putem calcula uniunea cu | -set_cu_valori | alt_set #=> {1, 2, 3, 4, 5, 6} - -# Diferenţa între seturi se face cu - -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# Verificăm existenţa cu "in" -2 in set_cu_valori #=> True -10 in set_cu_valori #=> False - - -#################################################### -## 3. Controlul Execuţiei -#################################################### - -# O variabilă -o_variabila = 5 - -# Acesta este un "if". Indentarea este importanta în python! -# Printează "o_variabila este mai mică ca 10" -if o_variabila > 10: - print "o_variabila e mai mare ca 10." -elif o_variabila < 10: # Clauza elif e opţională. - print "o_variabila este mai mică ca 10." -else: # Şi else e opţional. - print "o_variabila este exact 10." - - -""" -Buclele "for" pot fi folosite pentru a parcurge liste -Vom afişa: - câinele este un mamifer - pisica este un mamifer - şoarecele este un mamifer -""" -for animal in ["câinele", "pisica", "şoarecele"]: - # Folosim % pentru a compune mesajul - print "%s este un mamifer" % animal - -""" -"range(număr)" crează o lista de numere -de la zero la numărul dat -afişează: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -While repetă pana când condiţia dată nu mai este adevărată. -afişează: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # Prescurtare pentru x = x + 1 - -# Recepţionăm excepţii cu blocuri try/except - -# Acest cod e valid in Python > 2.6: -try: - # Folosim "raise" pentru a declanşa o eroare - raise IndexError("Asta este o IndexError") -except IndexError as e: - pass # Pass nu face nimic. În mod normal aici ne-am ocupa de eroare. - - -#################################################### -## 4. Funcţii -#################################################### - -# Folosim "def" pentru a defini funcţii -def add(x, y): - print "x este %s şi y este %s" % (x, y) - return x + y # Funcţia poate returna valori cu "return" - -# Apelăm funcţia "add" cu parametrii -add(5, 6) #=> Va afişa "x este 5 şi y este 6" şi va returna 11 - -# Altă cale de a apela funcţii: cu parametrii numiţi -add(y=6, x=5) # Ordinea parametrilor numiţi nu contează - -# Putem defini funcţii care primesc un număr variabil de parametrii nenumiţi -# Aceşti parametrii nenumiţi se cheamă si poziţinali -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# Şi putem defini funcţii care primesc un număr variabil de parametrii numiţi -def keyword_args(**kwargs): - return kwargs - -# Hai să vedem cum merge -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} - -# Se pot combina -def all_the_args(*args, **kwargs): - print args - print kwargs -""" -all_the_args(1, 2, a=3, b=4) va afişa: - (1, 2) - {"a": 3, "b": 4} -""" - -# Când apelăm funcţii, putem face inversul args/kwargs! -# Folosim * pentru a expanda tuple şi ** pentru a expanda kwargs. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # echivalent cu foo(1, 2, 3, 4) -all_the_args(**kwargs) # echivalent cu foo(a=3, b=4) -all_the_args(*args, **kwargs) # echivalent cu foo(1, 2, 3, 4, a=3, b=4) - -# În Python, funcţiile sunt obiecte primare -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) #=> 13 - -# Funcţiile pot fi anonime -(lambda x: x > 2)(3) #=> True - -# Există funcţii de ordin superior (care operează pe alte funcţii) predefinite -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# Putem folosi scurtături de liste pentru a simplifica munca cu map si filter -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] - -#################################################### -## 5. Clase -#################################################### - -# Moştenim object pentru a crea o nouă clasă -class Om(object): - - # Acesta este un atribut al clasei. Va fi moştenit de toate instanţele. - species = "H. sapiens" - - # Constructor (mai degrabă, configurator de bază) - def __init__(self, nume): - # Valoarea parametrului este stocată in atributul instanţei - self.nume = nume - - # Aceasta este o metoda a instanţei. - # Toate metodele primesc "self" ca si primul argument. - def spune(self, mesaj): - return "%s: %s" % (self.nume, mesaj) - - # O metodă a clasei. Este partajată de toate instanţele. - # Va primi ca si primul argument clasa căreia îi aparţine. - @classmethod - def get_species(cls): - return cls.species - - # O metoda statica nu primeste un argument automat. - @staticmethod - def exclama(): - return "*Aaaaaah*" - - -# Instanţiem o clasă -i = Om(nume="Ion") -print i.spune("salut") # afişează: "Ion: salut" - -j = Om("George") -print j.spune("ciau") # afişează George: ciau" - -# Apelăm metoda clasei -i.get_species() #=> "H. sapiens" - -# Modificăm atributul partajat -Om.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" - -# Apelăm metoda statică -Om.exclama() #=> "*Aaaaaah*" - - -#################################################### -## 6. Module -#################################################### - -# Pentru a folosi un modul, trebuie importat -import math -print math.sqrt(16) #=> 4.0 - -# Putem importa doar anumite funcţii dintr-un modul -from math import ceil, floor -print ceil(3.7) #=> 4.0 -print floor(3.7) #=> 3.0 - -# Putem importa toate funcţiile dintr-un modul, dar nu este o idee bună -# Nu faceţi asta! -from math import * - -# Numele modulelor pot fi modificate la import, de exemplu pentru a le scurta -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Modulele python sunt pur şi simplu fişiere cu cod python. -# Puteţi sa creaţi modulele voastre, şi sa le importaţi. -# Numele modulului este acelasi cu numele fişierului. - -# Cu "dir" inspectăm ce funcţii conţine un modul -import math -dir(math) - - -``` - -## Doriţi mai mult? - -### Gratis online, în limba engleză - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2.6/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) - -### Cărţi, în limba engleză - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/ro-ro/pythonlegacy-ro.html.markdown b/ro-ro/pythonlegacy-ro.html.markdown new file mode 100644 index 00000000..ada0c034 --- /dev/null +++ b/ro-ro/pythonlegacy-ro.html.markdown @@ -0,0 +1,493 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Ovidiu Ciule", "https://github.com/ociule"] +filename: learnpython-ro.py +lang: ro-ro +--- + +Python a fost creat de Guido Van Rossum la începutul anilor '90. Python a +devenit astăzi unul din cele mai populare limbaje de programare. +M-am indrăgostit de Python pentru claritatea sa sintactică. Python este aproape +pseudocod executabil. + +Opinia dumneavoastră este binevenită! Puteţi sa imi scrieţi la [@ociule](http://twitter.com/ociule) +sau ociule [at] [google's email service] + +Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. +O versiune Python 3 va apărea în curând, în limba engleză mai întâi. + +```python +# Comentariile pe o singură linie încep cu un caracter diez. +""" Şirurile de caractere pe mai multe linii pot fi încadrate folosind trei caractere ", şi sunt des + folosite ca şi comentarii pe mai multe linii. +""" + +#################################################### +## 1. Operatori şi tipuri de date primare +#################################################### + +# Avem numere +3 #=> 3 + +# Matematica se comportă cum ne-am aştepta +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Împărţirea este un pic surprinzătoare. Este de fapt împărţire pe numere +# întregi şi rotunjeşte +# automat spre valoarea mai mică +5 / 2 #=> 2 + +# Pentru a folosi împărţirea fără rest avem nevoie de numere reale +2.0 # Acesta e un număr real +11.0 / 4.0 #=> 2.75 ahhh ... cum ne aşteptam + +# Ordinea operaţiilor se poate forţa cu paranteze +(1 + 3) * 2 #=> 8 + +# Valoriile boolene sunt şi ele valori primare +True +False + +# Pot fi negate cu operatorul not +not True #=> False +not False #=> True + +# Egalitatea este == +1 == 1 #=> True +2 == 1 #=> False + +# Inegalitate este != +1 != 1 #=> False +2 != 1 #=> True + +# Comparaţii +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Comparaţiile pot fi inlănţuite! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Şirurile de caractere pot fi încadrate cu " sau ' +"Acesta e un şir de caractere." +'Şi acesta este un şir de caractere.' + +# Şirurile de caractere pot fi adăugate! +"Hello " + "world!" #=> "Hello world!" + +# Un şir de caractere poate fi folosit ca o listă +"Acesta e un şir de caractere"[0] #=> 'A' + +# Caracterul % (procent) poate fi folosit pentru a formata şiruri de caractere : +"%s pot fi %s" % ("şirurile", "interpolate") + +# O metodă mai nouă de a formata şiruri este metoda "format" +# Este metoda recomandată +"{0} pot fi {1}".format("şirurile", "formatate") +# Puteţi folosi cuvinte cheie dacă nu doriţi sa număraţi +"{nume} vrea să mănânce {fel}".format(nume="Bob", fel="lasagna") + +# "None", care reprezintă valoarea nedefinită, e un obiect +None #=> None + +# Nu folosiţi operatorul == pentru a compara un obiect cu None +# Folosiţi operatorul "is" +"etc" is None #=> False +None is None #=> True + +# Operatorul "is" testeaza dacă obiectele sunt identice. +# Acastă operaţie nu e foarte folositoare cu tipuri primare, +# dar e foarte folositoare cu obiecte. + +# None, 0, şi şiruri de caractere goale sunt evaluate ca si fals, False. +# Toate celelalte valori sunt adevărate, True. +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Variabile şi colecţii +#################################################### + +# Printarea este uşoară +print "Eu sunt Python. Încântat de cunoştinţă!" + + +# Nu este nevoie sa declari variabilele înainte de a le folosi +o_variabila = 5 # Convenţia este de a folosi caractere_minuscule_cu_underscore +o_variabila #=> 5 + +# Dacă accesăm o variabilă nefolosită declanşăm o excepţie. +# Vezi secţiunea Control de Execuţie pentru mai multe detalii despre excepţii. +alta_variabila # Declanşează o eroare de nume + +# "If" poate fi folosit într-o expresie. +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Listele sunt folosite pentru colecţii +li = [] +# O listă poate avea valori de la început +alta_li = [4, 5, 6] + +# Se adaugă valori la sfârşitul lister cu append +li.append(1) #li e acum [1] +li.append(2) #li e acum [1, 2] +li.append(4) #li e acum [1, 2, 4] +li.append(3) #li este acum [1, 2, 4, 3] +# Se şterg de la sfarşit cu pop +li.pop() #=> 3 şi li e acum [1, 2, 4] +# Să o adaugăm înapoi valoarea +li.append(3) # li e din nou [1, 2, 4, 3] + +# Putem accesa valorile individuale dintr-o listă cu operatorul index +li[0] #=> 1 +# Valoarea speciala -1 pentru index accesează ultima valoare +li[-1] #=> 3 + +# Dacă depaşim limitele listei declanşăm o eroare IndexError +li[4] # Declanşează IndexError + +# Putem să ne uităm la intervale folosind sintaxa de "felii" +# În Python, intervalele sunt închise la început si deschise la sfârşit. +li[1:3] #=> [2, 4] +# Fără început +li[2:] #=> [4, 3] +# Fără sfarşit +li[:3] #=> [1, 2, 4] + +# Putem şterge elemente arbitrare din lista cu operatorul "del" care primeşte indexul lor +del li[2] # li e acum [1, 2, 3] + +# Listele pot fi adăugate +li + alta_li #=> [1, 2, 3, 4, 5, 6] - Notă: li si alta_li nu sunt modificate! + +# Concatenăm liste cu "extend()" +li.extend(alta_li) # Acum li este [1, 2, 3, 4, 5, 6] + +# Se verifică existenţa valorilor in lista cu "in" +1 in li #=> True + +# Şi lungimea cu "len()" +len(li) #=> 6 + + +# Tuplele sunt ca şi listele dar imutabile +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Declanşează TypeError + +# Pot fi folosite ca şi liste +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Tuplele pot fi despachetate +a, b, c = (1, 2, 3) # a este acum 1, b este acum 2 şi c este acum 3 +# Tuplele pot fi folosite şi fără paranteze +d, e, f = 4, 5, 6 +# Putem inversa valori foarte uşor! +e, d = d, e # d este acum 5 şi e este acum 4 + + +# Dicţionarele stochează chei şi o valoare pentru fiecare cheie +dict_gol = {} +# Şi un dicţionar cu valori +dict_cu_valori = {"unu": 1, "doi": 2, "trei": 3} + +# Căutaţi valori cu [] +dict_cu_valori["unu"] #=> 1 + +# Obţinem lista cheilor cu "keys()" +dict_cu_valori.keys() #=> ["trei", "doi", "unu"] +# Notă - ordinea cheilor obţinute cu keys() nu este garantată. +# Puteţi obţine rezultate diferite de exemplul de aici. + +# Obţinem valorile cu values() +dict_cu_valori.values() #=> [3, 2, 1] +# Notă - aceeaşi ca mai sus, aplicată asupra valorilor. + +# Verificăm existenţa unei valori cu "in" +"unu" in dict_cu_valori #=> True +1 in dict_cu_valori #=> False + +# Accesarea unei chei care nu exista declanşează o KeyError +dict_cu_valori["four"] # KeyError + +# Putem folosi metoda "get()" pentru a evita KeyError +dict_cu_valori.get("one") #=> 1 +dict_cu_valori.get("four") #=> None +# Metoda get poate primi ca al doilea argument o valoare care va fi returnată +# când cheia nu este prezentă. +dict_cu_valori.get("one", 4) #=> 1 +dict_cu_valori.get("four", 4) #=> 4 + +# "setdefault()" este o metodă pentru a adăuga chei-valori fără a le modifica, dacă cheia există deja +dict_cu_valori.setdefault("five", 5) #dict_cu_valori["five"] este acum 5 +dict_cu_valori.setdefault("five", 6) #dict_cu_valori["five"] exista deja, nu este modificată, tot 5 + + +# Set este colecţia mulţime +set_gol = set() +# Putem crea un set cu valori +un_set = set([1,2,2,3,4]) # un_set este acum set([1, 2, 3, 4]), amintiţi-vă ca mulţimile garantează unicatul! + +# În Python 2.7, {} poate fi folosit pentru un set +set_cu_valori = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Putem adăuga valori cu add +set_cu_valori.add(5) # set_cu_valori este acum {1, 2, 3, 4, 5} + +# Putem intersecta seturi +alt_set = {3, 4, 5, 6} +set_cu_valori & alt_set #=> {3, 4, 5} + +# Putem calcula uniunea cu | +set_cu_valori | alt_set #=> {1, 2, 3, 4, 5, 6} + +# Diferenţa între seturi se face cu - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Verificăm existenţa cu "in" +2 in set_cu_valori #=> True +10 in set_cu_valori #=> False + + +#################################################### +## 3. Controlul Execuţiei +#################################################### + +# O variabilă +o_variabila = 5 + +# Acesta este un "if". Indentarea este importanta în python! +# Printează "o_variabila este mai mică ca 10" +if o_variabila > 10: + print "o_variabila e mai mare ca 10." +elif o_variabila < 10: # Clauza elif e opţională. + print "o_variabila este mai mică ca 10." +else: # Şi else e opţional. + print "o_variabila este exact 10." + + +""" +Buclele "for" pot fi folosite pentru a parcurge liste +Vom afişa: + câinele este un mamifer + pisica este un mamifer + şoarecele este un mamifer +""" +for animal in ["câinele", "pisica", "şoarecele"]: + # Folosim % pentru a compune mesajul + print "%s este un mamifer" % animal + +""" +"range(număr)" crează o lista de numere +de la zero la numărul dat +afişează: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +While repetă pana când condiţia dată nu mai este adevărată. +afişează: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Prescurtare pentru x = x + 1 + +# Recepţionăm excepţii cu blocuri try/except + +# Acest cod e valid in Python > 2.6: +try: + # Folosim "raise" pentru a declanşa o eroare + raise IndexError("Asta este o IndexError") +except IndexError as e: + pass # Pass nu face nimic. În mod normal aici ne-am ocupa de eroare. + + +#################################################### +## 4. Funcţii +#################################################### + +# Folosim "def" pentru a defini funcţii +def add(x, y): + print "x este %s şi y este %s" % (x, y) + return x + y # Funcţia poate returna valori cu "return" + +# Apelăm funcţia "add" cu parametrii +add(5, 6) #=> Va afişa "x este 5 şi y este 6" şi va returna 11 + +# Altă cale de a apela funcţii: cu parametrii numiţi +add(y=6, x=5) # Ordinea parametrilor numiţi nu contează + +# Putem defini funcţii care primesc un număr variabil de parametrii nenumiţi +# Aceşti parametrii nenumiţi se cheamă si poziţinali +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Şi putem defini funcţii care primesc un număr variabil de parametrii numiţi +def keyword_args(**kwargs): + return kwargs + +# Hai să vedem cum merge +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Se pot combina +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) va afişa: + (1, 2) + {"a": 3, "b": 4} +""" + +# Când apelăm funcţii, putem face inversul args/kwargs! +# Folosim * pentru a expanda tuple şi ** pentru a expanda kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # echivalent cu foo(1, 2, 3, 4) +all_the_args(**kwargs) # echivalent cu foo(a=3, b=4) +all_the_args(*args, **kwargs) # echivalent cu foo(1, 2, 3, 4, a=3, b=4) + +# În Python, funcţiile sunt obiecte primare +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Funcţiile pot fi anonime +(lambda x: x > 2)(3) #=> True + +# Există funcţii de ordin superior (care operează pe alte funcţii) predefinite +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Putem folosi scurtături de liste pentru a simplifica munca cu map si filter +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#################################################### +## 5. Clase +#################################################### + +# Moştenim object pentru a crea o nouă clasă +class Om(object): + + # Acesta este un atribut al clasei. Va fi moştenit de toate instanţele. + species = "H. sapiens" + + # Constructor (mai degrabă, configurator de bază) + def __init__(self, nume): + # Valoarea parametrului este stocată in atributul instanţei + self.nume = nume + + # Aceasta este o metoda a instanţei. + # Toate metodele primesc "self" ca si primul argument. + def spune(self, mesaj): + return "%s: %s" % (self.nume, mesaj) + + # O metodă a clasei. Este partajată de toate instanţele. + # Va primi ca si primul argument clasa căreia îi aparţine. + @classmethod + def get_species(cls): + return cls.species + + # O metoda statica nu primeste un argument automat. + @staticmethod + def exclama(): + return "*Aaaaaah*" + + +# Instanţiem o clasă +i = Om(nume="Ion") +print i.spune("salut") # afişează: "Ion: salut" + +j = Om("George") +print j.spune("ciau") # afişează George: ciau" + +# Apelăm metoda clasei +i.get_species() #=> "H. sapiens" + +# Modificăm atributul partajat +Om.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Apelăm metoda statică +Om.exclama() #=> "*Aaaaaah*" + + +#################################################### +## 6. Module +#################################################### + +# Pentru a folosi un modul, trebuie importat +import math +print math.sqrt(16) #=> 4.0 + +# Putem importa doar anumite funcţii dintr-un modul +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Putem importa toate funcţiile dintr-un modul, dar nu este o idee bună +# Nu faceţi asta! +from math import * + +# Numele modulelor pot fi modificate la import, de exemplu pentru a le scurta +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Modulele python sunt pur şi simplu fişiere cu cod python. +# Puteţi sa creaţi modulele voastre, şi sa le importaţi. +# Numele modulului este acelasi cu numele fişierului. + +# Cu "dir" inspectăm ce funcţii conţine un modul +import math +dir(math) + + +``` + +## Doriţi mai mult? + +### Gratis online, în limba engleză + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### Cărţi, în limba engleză + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown deleted file mode 100644 index 6087a686..00000000 --- a/ru-ru/python-ru.html.markdown +++ /dev/null @@ -1,643 +0,0 @@ ---- -language: python -lang: ru-ru -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["Yury Timofeev", "http://twitter.com/gagar1n"] - - ["Andre Polykanine", "https://github.com/Oire"] -filename: learnpython-ru.py ---- - -Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из -самых популярных языков. Я влюбился в Python за понятный и доходчивый синтаксис — это -почти исполняемый псевдокод. - -С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh) -или louiedinh [at] [почтовый сервис Google] - -Замечание: Эта статья относится к Python 2.7, но должно работать и в других версиях Python 2.x. -Чтобы изучить Python 3.x, обратитесь к статье по Python 3. - -```python -# Однострочные комментарии начинаются с символа решётки. -""" Многострочный текст может быть - записан, используя 3 знака " и обычно используется - в качестве встроенной документации -""" - -#################################################### -## 1. Примитивные типы данных и операторы -#################################################### - -# У вас есть числа -3 #=> 3 - -# Математика работает вполне ожидаемо -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 - -# А вот деление немного сложнее. В этом случае происходит деление -# целых чисел, и результат автоматически округляется в меньшую сторону. -5 / 2 #=> 2 - -# Чтобы делить правильно, сначала нужно немного узнать о числах -# с плавающей запятой. -2.0 # Это число с плавающей запятой -11.0 / 4.0 #=> 2.75 Вооот... Так гораздо лучше - -# Результат целочисленного деления округляется в меньшую сторону -# как для положительных, так и для отрицательных чисел. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Остаток от деления -7 % 3 # => 1 - -# Возведение в степень -2**4 # => 16 - -# Приоритет операций указывается скобками -(1 + 3) * 2 #=> 8 - -# Логические операторы -# Обратите внимание: ключевые слова «and» и «or» чувствительны к регистру букв -True and False #=> False -False or True #=> True - -# Обратите внимание, что логические операторы используются и с целыми числами -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True - -# Для отрицания используется ключевое слово not -not True #=> False -not False #=> True - -# Равенство — это == -1 == 1 #=> True -2 == 1 #=> False - -# Неравенство — это != -1 != 1 #=> False -2 != 1 #=> True - -# Ещё немного сравнений -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True - -# Сравнения могут быть записаны цепочкой! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False - -# Строки определяются символом " или ' -"Это строка." -'Это тоже строка.' - -# И строки тоже можно складывать! -"Привет " + "мир!" #=> "Привет мир!" - -# ... или умножать -"Привет" * 3 # => "ПриветПриветПривет" - -# Со строкой можно работать, как со списком символов -"Это строка"[0] #=> 'Э' - -# Символ % используется для форматирования строк, например: -"%s могут быть %s" % ("строки", "интерполированы") - -# Новый способ форматирования строк — использование метода format. -# Это предпочитаемый способ. -"{0} могут быть {1}".format("строки", "форматированы") - -# Если вы не хотите считать, можете использовать ключевые слова. -"{name} хочет есть {food}".format(name="Боб", food="лазанью") - -# None является объектом -None #=> None - -# Не используйте оператор равенства '=='' для сравнения -# объектов с None. Используйте для этого «is» -"etc" is None #=> False -None is None #=> True - -# Оператор 'is' проверяет идентичность объектов. Он не -# очень полезен при работе с примитивными типами, но -# зато просто незаменим при работе с объектами. - -# None, 0 и пустые строки/списки равны False. -# Все остальные значения равны True -0 == False #=> True -"" == False #=> True - - -#################################################### -## 2. Переменные и коллекции -#################################################### - -# В Python есть оператор print, доступный в версиях 2.x, но удалённый в версии 3 -print "Я Python. Приятно познакомиться!" -# В Python также есть функция print(), доступная в версиях 2.7 и 3, -# Но для версии 2.7 нужно добавить следующий импорт модуля (раскомментируйте)): -# from __future__ import print_function -print("Я тоже Python! ") - -# Объявлять переменные перед инициализацией не нужно. -some_var = 5 # По соглашению используется нижний_регистр_с_подчёркиваниями -some_var #=> 5 - -# При попытке доступа к неинициализированной переменной -# выбрасывается исключение. -# См. раздел «Поток управления» для информации об исключениях. -some_other_var # Выбрасывает ошибку именования - -# if может быть использован как выражение -"yahoo!" if 3 > 2 else 2 #=> "yahoo!" - -# Списки хранят последовательности -li = [] -# Можно сразу начать с заполненного списка -other_li = [4, 5, 6] - -# строка разделена в список -a="adambard" -list(a) #=> ['a','d','a','m','b','a','r','d'] - -# Объекты добавляются в конец списка методом append -li.append(1) # [1] -li.append(2) # [1, 2] -li.append(4) # [1, 2, 4] -li.append(3) # [1, 2, 4, 3] -# И удаляются с конца методом pop -li.pop() #=> возвращает 3 и li становится равен [1, 2, 4] -# Положим элемент обратно -li.append(3) # [1, 2, 4, 3]. - -# Обращайтесь со списком, как с обычным массивом -li[0] #=> 1 -# Присваивайте новые значения уже инициализированным индексам с помощью = -li[0] = 42 -li[0] # => 42 -li[0] = 1 # Обратите внимание: возвращаемся на исходное значение -# Обратимся к последнему элементу -li[-1] #=> 3 - -# Попытка выйти за границы массива приведёт к ошибке индекса -li[4] # Выдаёт IndexError - -# Можно обращаться к диапазону, используя так называемые срезы -# (Для тех, кто любит математику, это называется замкнуто-открытый интервал). -li[1:3] #=> [2, 4] -# Опускаем начало -li[2:] #=> [4, 3] -# Опускаем конец -li[:3] #=> [1, 2, 4] -# Выбираем каждый второй элемент -li[::2] # =>[1, 4] -# Переворачиваем список -li[::-1] # => [3, 4, 2, 1] -# Используйте сочетания всего вышеназванного для выделения более сложных срезов -# li[начало:конец:шаг] - -# Удаляем произвольные элементы из списка оператором del -del li[2] # li теперь [1, 2, 3] - -# Вы можете складывать, или, как ещё говорят, конкатенировать списки -li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются -# Обратите внимание: значения li и other_li при этом не изменились. - -# Объединять списки можно методом extend -li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6] - -# Проверить элемент на вхождение в список можно оператором in -1 in li #=> True - -# Длина списка вычисляется функцией len -len(li) #=> 6 - - -# Кортежи — это такие списки, только неизменяемые -tup = (1, 2, 3) -tup[0] #=> 1 -tup[0] = 3 # Выдаёт TypeError - -# Всё то же самое можно делать и с кортежами -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True - -# Вы можете распаковывать кортежи (или списки) в переменные -a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3 -# Кортежи создаются по умолчанию, если опущены скобки -d, e, f = 4, 5, 6 -# Обратите внимание, как легко поменять местами значения двух переменных -e, d = d, e # теперь d == 5, а e == 4 - -# Словари содержат ассоциативные массивы -empty_dict = {} -# Вот так описывается предзаполненный словарь -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Значения извлекаются так же, как из списка, с той лишь разницей, -# что индекс — у словарей он называется ключом — не обязан быть числом -filled_dict["one"] #=> 1 - -# Можно получить все ключи в виде списка с помощью метода keys -filled_dict.keys() #=> ["three", "two", "one"] -# Замечание: сохранение порядка ключей в словаре не гарантируется -# Ваши результаты могут не совпадать с этими. - -# Можно получить и все значения в виде списка, используйте метод values -filled_dict.values() #=> [3, 2, 1] -# То же самое замечание насчёт порядка ключей справедливо и здесь - -# При помощи оператора in можно проверять ключи на вхождение в словарь -"one" in filled_dict #=> True -1 in filled_dict #=> False - -# Попытка получить значение по несуществующему ключу выбросит ошибку ключа -filled_dict["four"] # KeyError - -# Чтобы избежать этого, используйте метод get() -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None -# Метод get также принимает аргумент по умолчанию, значение которого будет -# возвращено при отсутствии указанного ключа -filled_dict.get("one", 4) #=> 1 -filled_dict.get("four", 4) #=> 4 -# Обратите внимание, что filled_dict.get("four") всё ещё => None -# (get не устанавливает значение элемента словаря) - -# Присваивайте значение ключам так же, как и в списках -filled_dict["four"] = 4 # теперь filled_dict["four"] => 4 - -# Метод setdefault() вставляет пару ключ-значение, только если такого ключа нет -filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5 -filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5 - - -# Множества содержат... ну, в общем, множества -# (которые похожи на списки, только в них не может быть дублирующихся элементов) -empty_set = set() -# Инициализация множества набором значений -some_set = set([1,2,2,3,4]) # some_set теперь равно set([1, 2, 3, 4]) - -# Порядок сортировки не гарантируется, хотя иногда они выглядят отсортированными -another_set = set([4, 3, 2, 2, 1]) # another_set теперь set([1, 2, 3, 4]) - -# Начиная с Python 2.7, вы можете использовать {}, чтобы объявить множество -filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} - -# Добавление новых элементов в множество -filled_set.add(5) # filled_set равно {1, 2, 3, 4, 5} - -# Пересечение множеств: & -other_set = {3, 4, 5, 6} -filled_set & other_set #=> {3, 4, 5} - -# Объединение множеств: | -filled_set | other_set #=> {1, 2, 3, 4, 5, 6} - -# Разность множеств: - -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# Проверка на вхождение во множество: in -2 in filled_set #=> True -10 in filled_set #=> False - - -#################################################### -## 3. Поток управления -#################################################### - -# Для начала заведём переменную -some_var = 5 - -# Так выглядит выражение if. Отступы в python очень важны! -# результат: «some_var меньше, чем 10» -if some_var > 10: - print("some_var намного больше, чем 10.") -elif some_var < 10: # Выражение elif необязательно. - print("some_var меньше, чем 10.") -else: # Это тоже необязательно. - print("some_var равно 10.") - - -""" -Циклы For проходят по спискам - -Результат: - собака — это млекопитающее - кошка — это млекопитающее - мышь — это млекопитающее -""" -for animal in ["собака", "кошка", "мышь"]: - # Можете использовать оператор % для интерполяции форматированных строк - print("%s — это млекопитающее" % animal) - -""" -«range(число)» возвращает список чисел -от нуля до заданного числа -Результат: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -Циклы while продолжаются до тех пор, пока указанное условие не станет ложным. -Результат: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Краткая запись для x = x + 1 - -# Обрабатывайте исключения блоками try/except - -# Работает в Python 2.6 и выше: -try: - # Чтобы выбросить ошибку, используется raise - raise IndexError("Это ошибка индекса") -except IndexError as e: - # pass — это просто отсутствие оператора. Обычно здесь происходит - # восстановление после ошибки. - pass -except (TypeError, NameError): - pass # Несколько исключений можно обработать вместе, если нужно. -else: # Необязательное выражение. Должно следовать за последним блоком except - print("Всё хорошо!") # Выполнится, только если не было никаких исключений - - - -#################################################### -## 4. Функции -#################################################### - -# Используйте def для создания новых функций -def add(x, y): - print("x равен %s, а y равен %s" % (x, y)) - return x + y # Возвращайте результат с помощью ключевого слова return - -# Вызов функции с аргументами -add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвращает 11 - -# Другой способ вызова функции — вызов с именованными аргументами -add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке. - -# Вы можете определить функцию, принимающую переменное число аргументов, -# которые будут интерпретированы как кортеж, если вы не используете * -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# А также можете определить функцию, принимающую переменное число -# именованных аргументов, которые будут интерпретированы как словарь, -# если вы не используете ** -def keyword_args(**kwargs): - return kwargs - -# Вызовем эту функцию и посмотрим, что из этого получится -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} - -# Если хотите, можете использовать оба способа одновременно -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) выводит: - (1, 2) - {"a": 3, "b": 4} -""" - -# Вызывая функции, можете сделать наоборот! -# Используйте символ * для распаковки кортежей и ** для распаковки словарей -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # эквивалентно foo(1, 2, 3, 4) -all_the_args(**kwargs) # эквивалентно foo(a=3, b=4) -all_the_args(*args, **kwargs) # эквивалентно foo(1, 2, 3, 4, a=3, b=4) - -# вы можете передавать переменное число позиционных или именованных аргументов -# другим функциям, которые их принимают, распаковывая их с помощью -# * или ** соответственно -def pass_all_the_args(*args, **kwargs): - all_the_args(*args, **kwargs) - print varargs(*args) - print keyword_args(**kwargs) - -# Область определения функций -x = 5 - -def setX(num): - # Локальная переменная x — это не то же самое, что глобальная переменная x - x = num # => 43 - print (x) # => 43 - -def setGlobalX(num): - global x - print (x) # => 5 - x = num # Глобальная переменная x теперь равна 6 - print (x) # => 6 - -setX(43) -setGlobalX(6) - -# В Python функции — «объекты первого класса» -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) #=> 13 - -# Также есть и анонимные функции -(lambda x: x > 2)(3) #=> True - -# Есть встроенные функции высшего порядка -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# Для удобного отображения и фильтрации можно использовать списочные включения -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] - -#################################################### -## 5. Классы -#################################################### - -# Чтобы получить класс, мы наследуемся от object. -class Human(object): - - # Атрибут класса. Он разделяется всеми экземплярами этого класса - species = "H. sapiens" - - # Обычный конструктор, вызывается при инициализации экземпляра класса - # Обратите внимание, что двойное подчёркивание в начале и в конце имени - # означает объекты и атрибуты, которые используются Python, но находятся - # в пространствах имён, управляемых пользователем. - # Не придумывайте им имена самостоятельно. - def __init__(self, name): - # Присваивание значения аргумента атрибуту класса name - self.name = name - - # Метод экземпляра. Все методы принимают self в качестве первого аргумента - def say(self, msg): - return "%s: %s" % (self.name, msg) - - # Метод класса разделяется между всеми экземплярами - # Они вызываются с указыванием вызывающего класса в качестве первого аргумента - @classmethod - def get_species(cls): - return cls.species - - # Статический метод вызывается без ссылки на класс или экземпляр - @staticmethod - def grunt(): - return "*grunt*" - - -# Инициализация экземпляра класса -i = Human(name="Иван") -print(i.say("привет")) # Выводит: «Иван: привет» - -j = Human("Пётр") -print(j.say("Привет")) # Выводит: «Пётр: привет» - -# Вызов метода класса -i.get_species() #=> "H. sapiens" - -# Изменение разделяемого атрибута -Human.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" - -# Вызов статического метода -Human.grunt() #=> "*grunt*" - - -#################################################### -## 6. Модули -#################################################### - -# Вы можете импортировать модули -import math -print(math.sqrt(16)) #=> 4.0 - -# Вы можете импортировать отдельные функции модуля -from math import ceil, floor -print(ceil(3.7)) #=> 4.0 -print(floor(3.7)) #=> 3.0 - -# Можете импортировать все функции модуля. -# (Хотя это и не рекомендуется) -from math import * - -# Можете сокращать имена модулей -import math as m -math.sqrt(16) == m.sqrt(16) #=> True -# Вы также можете убедиться, что функции эквивалентны -from math import sqrt -math.sqrt == m.sqrt == sqrt # => True - -# Модули в Python — это обычные Python-файлы. Вы -# можете писать свои модули и импортировать их. Название -# модуля совпадает с названием файла. - -# Вы можете узнать, какие функции и атрибуты определены -# в модуле -import math -dir(math) - -#################################################### -## 7. Дополнительно -#################################################### - -# Генераторы помогут выполнить ленивые вычисления -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Генератор создаёт значения на лету. -# Он не возвращает все значения разом, а создаёт каждое из них при каждой -# итерации. Это значит, что значения больше 15 в double_numbers -# обработаны не будут. -# Обратите внимание: xrange — это генератор, который делает то же, что и range. -# Создание списка чисел от 1 до 900000000 требует много места и времени. -# xrange создаёт объект генератора, а не список сразу, как это делает range. -# Если нам нужно имя переменной, совпадающее с ключевым словом Python, -# мы используем подчёркивание в конце -xrange_ = xrange(1, 900000000) - -# Будет удваивать все числа, пока результат не превысит 30 -for i in double_numbers(xrange_): - print(i) - if i >= 30: - break - - -# Декораторы -# В этом примере beg оборачивает say -# Метод beg вызовет say. Если say_please равно True, -# он изменит возвращаемое сообщение -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, " Пожалуйста! У меня нет денег :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Вы не купите мне пива?" - return msg, say_please - - -print(say()) # Вы не купите мне пива? -print(say(say_please=True)) # Вы не купите мне пива? Пожалуйста! У меня нет денег :( - -``` - -## Хотите ещё? - -### Бесплатные онлайн-материалы - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Официальная документация](http://docs.python.org/2.6/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) - -### Платные - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/ru-ru/pythonlegacy-ru.html.markdown b/ru-ru/pythonlegacy-ru.html.markdown new file mode 100644 index 00000000..6087a686 --- /dev/null +++ b/ru-ru/pythonlegacy-ru.html.markdown @@ -0,0 +1,643 @@ +--- +language: python +lang: ru-ru +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Yury Timofeev", "http://twitter.com/gagar1n"] + - ["Andre Polykanine", "https://github.com/Oire"] +filename: learnpython-ru.py +--- + +Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из +самых популярных языков. Я влюбился в Python за понятный и доходчивый синтаксис — это +почти исполняемый псевдокод. + +С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh) +или louiedinh [at] [почтовый сервис Google] + +Замечание: Эта статья относится к Python 2.7, но должно работать и в других версиях Python 2.x. +Чтобы изучить Python 3.x, обратитесь к статье по Python 3. + +```python +# Однострочные комментарии начинаются с символа решётки. +""" Многострочный текст может быть + записан, используя 3 знака " и обычно используется + в качестве встроенной документации +""" + +#################################################### +## 1. Примитивные типы данных и операторы +#################################################### + +# У вас есть числа +3 #=> 3 + +# Математика работает вполне ожидаемо +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# А вот деление немного сложнее. В этом случае происходит деление +# целых чисел, и результат автоматически округляется в меньшую сторону. +5 / 2 #=> 2 + +# Чтобы делить правильно, сначала нужно немного узнать о числах +# с плавающей запятой. +2.0 # Это число с плавающей запятой +11.0 / 4.0 #=> 2.75 Вооот... Так гораздо лучше + +# Результат целочисленного деления округляется в меньшую сторону +# как для положительных, так и для отрицательных чисел. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Остаток от деления +7 % 3 # => 1 + +# Возведение в степень +2**4 # => 16 + +# Приоритет операций указывается скобками +(1 + 3) * 2 #=> 8 + +# Логические операторы +# Обратите внимание: ключевые слова «and» и «or» чувствительны к регистру букв +True and False #=> False +False or True #=> True + +# Обратите внимание, что логические операторы используются и с целыми числами +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Для отрицания используется ключевое слово not +not True #=> False +not False #=> True + +# Равенство — это == +1 == 1 #=> True +2 == 1 #=> False + +# Неравенство — это != +1 != 1 #=> False +2 != 1 #=> True + +# Ещё немного сравнений +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Сравнения могут быть записаны цепочкой! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Строки определяются символом " или ' +"Это строка." +'Это тоже строка.' + +# И строки тоже можно складывать! +"Привет " + "мир!" #=> "Привет мир!" + +# ... или умножать +"Привет" * 3 # => "ПриветПриветПривет" + +# Со строкой можно работать, как со списком символов +"Это строка"[0] #=> 'Э' + +# Символ % используется для форматирования строк, например: +"%s могут быть %s" % ("строки", "интерполированы") + +# Новый способ форматирования строк — использование метода format. +# Это предпочитаемый способ. +"{0} могут быть {1}".format("строки", "форматированы") + +# Если вы не хотите считать, можете использовать ключевые слова. +"{name} хочет есть {food}".format(name="Боб", food="лазанью") + +# None является объектом +None #=> None + +# Не используйте оператор равенства '=='' для сравнения +# объектов с None. Используйте для этого «is» +"etc" is None #=> False +None is None #=> True + +# Оператор 'is' проверяет идентичность объектов. Он не +# очень полезен при работе с примитивными типами, но +# зато просто незаменим при работе с объектами. + +# None, 0 и пустые строки/списки равны False. +# Все остальные значения равны True +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Переменные и коллекции +#################################################### + +# В Python есть оператор print, доступный в версиях 2.x, но удалённый в версии 3 +print "Я Python. Приятно познакомиться!" +# В Python также есть функция print(), доступная в версиях 2.7 и 3, +# Но для версии 2.7 нужно добавить следующий импорт модуля (раскомментируйте)): +# from __future__ import print_function +print("Я тоже Python! ") + +# Объявлять переменные перед инициализацией не нужно. +some_var = 5 # По соглашению используется нижний_регистр_с_подчёркиваниями +some_var #=> 5 + +# При попытке доступа к неинициализированной переменной +# выбрасывается исключение. +# См. раздел «Поток управления» для информации об исключениях. +some_other_var # Выбрасывает ошибку именования + +# if может быть использован как выражение +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Списки хранят последовательности +li = [] +# Можно сразу начать с заполненного списка +other_li = [4, 5, 6] + +# строка разделена в список +a="adambard" +list(a) #=> ['a','d','a','m','b','a','r','d'] + +# Объекты добавляются в конец списка методом append +li.append(1) # [1] +li.append(2) # [1, 2] +li.append(4) # [1, 2, 4] +li.append(3) # [1, 2, 4, 3] +# И удаляются с конца методом pop +li.pop() #=> возвращает 3 и li становится равен [1, 2, 4] +# Положим элемент обратно +li.append(3) # [1, 2, 4, 3]. + +# Обращайтесь со списком, как с обычным массивом +li[0] #=> 1 +# Присваивайте новые значения уже инициализированным индексам с помощью = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Обратите внимание: возвращаемся на исходное значение +# Обратимся к последнему элементу +li[-1] #=> 3 + +# Попытка выйти за границы массива приведёт к ошибке индекса +li[4] # Выдаёт IndexError + +# Можно обращаться к диапазону, используя так называемые срезы +# (Для тех, кто любит математику, это называется замкнуто-открытый интервал). +li[1:3] #=> [2, 4] +# Опускаем начало +li[2:] #=> [4, 3] +# Опускаем конец +li[:3] #=> [1, 2, 4] +# Выбираем каждый второй элемент +li[::2] # =>[1, 4] +# Переворачиваем список +li[::-1] # => [3, 4, 2, 1] +# Используйте сочетания всего вышеназванного для выделения более сложных срезов +# li[начало:конец:шаг] + +# Удаляем произвольные элементы из списка оператором del +del li[2] # li теперь [1, 2, 3] + +# Вы можете складывать, или, как ещё говорят, конкатенировать списки +li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются +# Обратите внимание: значения li и other_li при этом не изменились. + +# Объединять списки можно методом extend +li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6] + +# Проверить элемент на вхождение в список можно оператором in +1 in li #=> True + +# Длина списка вычисляется функцией len +len(li) #=> 6 + + +# Кортежи — это такие списки, только неизменяемые +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Выдаёт TypeError + +# Всё то же самое можно делать и с кортежами +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Вы можете распаковывать кортежи (или списки) в переменные +a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3 +# Кортежи создаются по умолчанию, если опущены скобки +d, e, f = 4, 5, 6 +# Обратите внимание, как легко поменять местами значения двух переменных +e, d = d, e # теперь d == 5, а e == 4 + +# Словари содержат ассоциативные массивы +empty_dict = {} +# Вот так описывается предзаполненный словарь +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Значения извлекаются так же, как из списка, с той лишь разницей, +# что индекс — у словарей он называется ключом — не обязан быть числом +filled_dict["one"] #=> 1 + +# Можно получить все ключи в виде списка с помощью метода keys +filled_dict.keys() #=> ["three", "two", "one"] +# Замечание: сохранение порядка ключей в словаре не гарантируется +# Ваши результаты могут не совпадать с этими. + +# Можно получить и все значения в виде списка, используйте метод values +filled_dict.values() #=> [3, 2, 1] +# То же самое замечание насчёт порядка ключей справедливо и здесь + +# При помощи оператора in можно проверять ключи на вхождение в словарь +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Попытка получить значение по несуществующему ключу выбросит ошибку ключа +filled_dict["four"] # KeyError + +# Чтобы избежать этого, используйте метод get() +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# Метод get также принимает аргумент по умолчанию, значение которого будет +# возвращено при отсутствии указанного ключа +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 +# Обратите внимание, что filled_dict.get("four") всё ещё => None +# (get не устанавливает значение элемента словаря) + +# Присваивайте значение ключам так же, как и в списках +filled_dict["four"] = 4 # теперь filled_dict["four"] => 4 + +# Метод setdefault() вставляет пару ключ-значение, только если такого ключа нет +filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5 +filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5 + + +# Множества содержат... ну, в общем, множества +# (которые похожи на списки, только в них не может быть дублирующихся элементов) +empty_set = set() +# Инициализация множества набором значений +some_set = set([1,2,2,3,4]) # some_set теперь равно set([1, 2, 3, 4]) + +# Порядок сортировки не гарантируется, хотя иногда они выглядят отсортированными +another_set = set([4, 3, 2, 2, 1]) # another_set теперь set([1, 2, 3, 4]) + +# Начиная с Python 2.7, вы можете использовать {}, чтобы объявить множество +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Добавление новых элементов в множество +filled_set.add(5) # filled_set равно {1, 2, 3, 4, 5} + +# Пересечение множеств: & +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Объединение множеств: | +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Разность множеств: - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Проверка на вхождение во множество: in +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Поток управления +#################################################### + +# Для начала заведём переменную +some_var = 5 + +# Так выглядит выражение if. Отступы в python очень важны! +# результат: «some_var меньше, чем 10» +if some_var > 10: + print("some_var намного больше, чем 10.") +elif some_var < 10: # Выражение elif необязательно. + print("some_var меньше, чем 10.") +else: # Это тоже необязательно. + print("some_var равно 10.") + + +""" +Циклы For проходят по спискам + +Результат: + собака — это млекопитающее + кошка — это млекопитающее + мышь — это млекопитающее +""" +for animal in ["собака", "кошка", "мышь"]: + # Можете использовать оператор % для интерполяции форматированных строк + print("%s — это млекопитающее" % animal) + +""" +«range(число)» возвращает список чисел +от нуля до заданного числа +Результат: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +Циклы while продолжаются до тех пор, пока указанное условие не станет ложным. +Результат: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Краткая запись для x = x + 1 + +# Обрабатывайте исключения блоками try/except + +# Работает в Python 2.6 и выше: +try: + # Чтобы выбросить ошибку, используется raise + raise IndexError("Это ошибка индекса") +except IndexError as e: + # pass — это просто отсутствие оператора. Обычно здесь происходит + # восстановление после ошибки. + pass +except (TypeError, NameError): + pass # Несколько исключений можно обработать вместе, если нужно. +else: # Необязательное выражение. Должно следовать за последним блоком except + print("Всё хорошо!") # Выполнится, только если не было никаких исключений + + + +#################################################### +## 4. Функции +#################################################### + +# Используйте def для создания новых функций +def add(x, y): + print("x равен %s, а y равен %s" % (x, y)) + return x + y # Возвращайте результат с помощью ключевого слова return + +# Вызов функции с аргументами +add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвращает 11 + +# Другой способ вызова функции — вызов с именованными аргументами +add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке. + +# Вы можете определить функцию, принимающую переменное число аргументов, +# которые будут интерпретированы как кортеж, если вы не используете * +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# А также можете определить функцию, принимающую переменное число +# именованных аргументов, которые будут интерпретированы как словарь, +# если вы не используете ** +def keyword_args(**kwargs): + return kwargs + +# Вызовем эту функцию и посмотрим, что из этого получится +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Если хотите, можете использовать оба способа одновременно +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) выводит: + (1, 2) + {"a": 3, "b": 4} +""" + +# Вызывая функции, можете сделать наоборот! +# Используйте символ * для распаковки кортежей и ** для распаковки словарей +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # эквивалентно foo(1, 2, 3, 4) +all_the_args(**kwargs) # эквивалентно foo(a=3, b=4) +all_the_args(*args, **kwargs) # эквивалентно foo(1, 2, 3, 4, a=3, b=4) + +# вы можете передавать переменное число позиционных или именованных аргументов +# другим функциям, которые их принимают, распаковывая их с помощью +# * или ** соответственно +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# Область определения функций +x = 5 + +def setX(num): + # Локальная переменная x — это не то же самое, что глобальная переменная x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # Глобальная переменная x теперь равна 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + +# В Python функции — «объекты первого класса» +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Также есть и анонимные функции +(lambda x: x > 2)(3) #=> True + +# Есть встроенные функции высшего порядка +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Для удобного отображения и фильтрации можно использовать списочные включения +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#################################################### +## 5. Классы +#################################################### + +# Чтобы получить класс, мы наследуемся от object. +class Human(object): + + # Атрибут класса. Он разделяется всеми экземплярами этого класса + species = "H. sapiens" + + # Обычный конструктор, вызывается при инициализации экземпляра класса + # Обратите внимание, что двойное подчёркивание в начале и в конце имени + # означает объекты и атрибуты, которые используются Python, но находятся + # в пространствах имён, управляемых пользователем. + # Не придумывайте им имена самостоятельно. + def __init__(self, name): + # Присваивание значения аргумента атрибуту класса name + self.name = name + + # Метод экземпляра. Все методы принимают self в качестве первого аргумента + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Метод класса разделяется между всеми экземплярами + # Они вызываются с указыванием вызывающего класса в качестве первого аргумента + @classmethod + def get_species(cls): + return cls.species + + # Статический метод вызывается без ссылки на класс или экземпляр + @staticmethod + def grunt(): + return "*grunt*" + + +# Инициализация экземпляра класса +i = Human(name="Иван") +print(i.say("привет")) # Выводит: «Иван: привет» + +j = Human("Пётр") +print(j.say("Привет")) # Выводит: «Пётр: привет» + +# Вызов метода класса +i.get_species() #=> "H. sapiens" + +# Изменение разделяемого атрибута +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Вызов статического метода +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Модули +#################################################### + +# Вы можете импортировать модули +import math +print(math.sqrt(16)) #=> 4.0 + +# Вы можете импортировать отдельные функции модуля +from math import ceil, floor +print(ceil(3.7)) #=> 4.0 +print(floor(3.7)) #=> 3.0 + +# Можете импортировать все функции модуля. +# (Хотя это и не рекомендуется) +from math import * + +# Можете сокращать имена модулей +import math as m +math.sqrt(16) == m.sqrt(16) #=> True +# Вы также можете убедиться, что функции эквивалентны +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True + +# Модули в Python — это обычные Python-файлы. Вы +# можете писать свои модули и импортировать их. Название +# модуля совпадает с названием файла. + +# Вы можете узнать, какие функции и атрибуты определены +# в модуле +import math +dir(math) + +#################################################### +## 7. Дополнительно +#################################################### + +# Генераторы помогут выполнить ленивые вычисления +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Генератор создаёт значения на лету. +# Он не возвращает все значения разом, а создаёт каждое из них при каждой +# итерации. Это значит, что значения больше 15 в double_numbers +# обработаны не будут. +# Обратите внимание: xrange — это генератор, который делает то же, что и range. +# Создание списка чисел от 1 до 900000000 требует много места и времени. +# xrange создаёт объект генератора, а не список сразу, как это делает range. +# Если нам нужно имя переменной, совпадающее с ключевым словом Python, +# мы используем подчёркивание в конце +xrange_ = xrange(1, 900000000) + +# Будет удваивать все числа, пока результат не превысит 30 +for i in double_numbers(xrange_): + print(i) + if i >= 30: + break + + +# Декораторы +# В этом примере beg оборачивает say +# Метод beg вызовет say. Если say_please равно True, +# он изменит возвращаемое сообщение +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, " Пожалуйста! У меня нет денег :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Вы не купите мне пива?" + return msg, say_please + + +print(say()) # Вы не купите мне пива? +print(say(say_please=True)) # Вы не купите мне пива? Пожалуйста! У меня нет денег :( + +``` + +## Хотите ещё? + +### Бесплатные онлайн-материалы + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Официальная документация](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### Платные + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/tr-tr/python-tr.html.markdown b/tr-tr/python-tr.html.markdown deleted file mode 100644 index 99a3eb4e..00000000 --- a/tr-tr/python-tr.html.markdown +++ /dev/null @@ -1,502 +0,0 @@ ---- -language: python -filename: learnpython-tr.py -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["Haydar KULEKCI", "http://scanf.info/"] -lang: tr-tr ---- -Python Guido Van Rossum tarafından 90'ların başında yaratılmıştır. Şu anda -varolanlar arasında en iyi dillerden birisidir. Ben (Louie Dinh) Python -dilinin syntax'ının belirginliğine aşığım. O basit olarak çalıştırılabilir -pseudocode'dur. - -Geri bildirimlerden son derece mutluluk duyarım! Bana [@louiedinh](http://twitter.com/louiedinh) -adresinden ya da louiedinh [at] [google's email service] adresinden ulaşabilirsiniz. - -Çeviri için geri bildirimleri de [@kulekci](http://twitter.com/kulekci) -adresine yapabilirsiniz. - -Not: Bu yazıdaki özellikler Python 2.7 için geçerlidir, ama Python 2.x için de -uygulanabilir. Python 3 için başka bir zaman tekrar bakınız. - - -```python -# Tek satır yorum hash işareti ile başlar. -""" Çoklu satır diziler üç tane çift tırnak - arasında yazılır. Ve yorum olarak da - kullanılabilir -""" - - -#################################################### -## 1. İlkel Veri Tipleri ve Operatörler -#################################################### - -# Sayılar -3 #=> 3 - -# Matematik beklediğiniz gibi -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 - -# Bölünme biraz ilginç. EĞer tam sayılar üzerinde bölünme işlemi yapıyorsanız -# sonuç otomatik olarak kırpılır. -5 / 2 #=> 2 - -# Bölünme işlemini düzenlemek için kayan noktalı sayıları bilmeniz gerekir. -2.0 # Bu bir kayan noktalı sayı -11.0 / 4.0 #=> 2.75 ahhh...daha iyi - -# İşlem önceliğini parantezler ile sağlayabilirsiniz. -(1 + 3) * 2 #=> 8 - -# Boolean değerleri bilindiği gibi -True -False - -# not ile nagatif(mantıksal) değerini alma -not True #=> False -not False #=> True - -# Eşitlik == -1 == 1 #=> True -2 == 1 #=> False - -# Eşitsizlik != -1 != 1 #=> False -2 != 1 #=> True - -# Daha fazla karşılaştırma -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True - -# Karşılaştırma zincirleme yapılabilir! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False - -# Karakter dizisi " veya ' ile oluşturulabilir -"This is a string." -'This is also a string.' - -# Karakter dizileri birbirleri ile eklenebilir -"Hello " + "world!" #=> "Hello world!" - -# A string can be treated like a list of characters -# Bir string'e karakter listesi gibi davranabilirsiniz. -"This is a string"[0] #=> 'T' - -# % karakter dizisini(string) formatlamak için kullanılır, bunun gibi: -"%s can be %s" % ("strings", "interpolated") - -# String'leri formatlamanın yeni bir yöntem ise format metodudur. -# Bu metod tercih edilen yöntemdir. -"{0} can be {1}".format("strings", "formatted") -# Eğer saymak istemiyorsanız anahtar kelime kullanabilirsiniz. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") - -# None bir objedir -None #=> None - -# "==" eşitliğini non objesi ile karşılaştırmak için kullanmayın. -# Onun yerine "is" kullanın. -"etc" is None #=> False -None is None #=> True - -# 'is' operatörü obje kimliği için test etmektedir. Bu ilkel değerler -# için kullanışlı değildir, ama objeleri karşılaştırmak için kullanışlıdır. - -# None, 0 ve boş string/list'ler False olarak değerlendirilir. -# Tüm eşitlikler True döner -0 == False #=> True -"" == False #=> True - - -#################################################### -## 2. Değişkenler ve Kolleksiyonlar -#################################################### - -# Ekrana yazdırma oldukça kolaydır. -print "I'm Python. Nice to meet you!" - - -# Değişkenlere bir değer atamadan önce tanımlamaya gerek yoktur. -some_var = 5 # Değişken isimlerinde gelenek küçük karakter ve alt çizgi - # kullanmaktır. -some_var #=> 5 - -# Daha önceden tanımlanmamış ya da assign edilmemeiş bir değişkene erişmeye -# çalıştığınızda bir hata fırlatılacaktır. Hata ayıklama hakkında daha fazla -# bilgi için kontrol akışı kısmına göz atınız. -some_other_var # isim hatası fırlatılır - -# isterseniz "if"i bir ifade gibi kullanabilirsiniz. -"yahoo!" if 3 > 2 else 2 #=> "yahoo!" - -# Listeler -li = [] -# Önceden değerleri tanımlanmış listeler -other_li = [4, 5, 6] - -# Bir listenin sonuna birşeyler eklemek -li.append(1) #li şu anda [1] -li.append(2) #li şu anda [1, 2] -li.append(4) #li şu anda [1, 2, 4] -li.append(3) #li şu anda [1, 2, 4, 3] -# pop ile sondan birşeyler silmek -li.pop() #=> 3 and li is now [1, 2, 4] -# Tekrar sonuna eklemek -li.append(3) # li is now [1, 2, 4, 3] again. - -# Dizi gibi listenin elemanlarına erişmek -li[0] #=> 1 -# Son elemanın değerine ulaşmak -li[-1] #=> 3 - -# Listede bulunmayan bir index'teki elemana erişirken "IndexError" hatası -# fırlatılır -li[4] # IndexError fırlatılır - -# slice syntax'ı ile belli aralıktakı değerlere bakabilirsiniz. -# (Açık ve kapalı aralıklıdır.) -li[1:3] #=> [2, 4] -# Başlangıcı ihmal etme -li[2:] #=> [4, 3] -# Sonu ihmal etme -li[:3] #=> [1, 2, 4] - -# "del" ile istenilen bir elemanı listeden silmek -del li[2] # li is now [1, 2, 3] - -# Listeleri birbiri ile birleştirebilirsiniz. -li + other_li #=> [1, 2, 3, 4, 5, 6] - Not: li ve other_li yanlız bırakılır - -# extend ile listeleri birleştirmek -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] - -# bir değerin liste içerisinde varlığını "in" ile kontrol etmek -1 in li #=> True - -# "len" ile listenin uzunluğunu bulmak -len(li) #=> 6 - -# Tüpler listeler gibidir sadece değişmezler(immutable) -tup = (1, 2, 3) -tup[0] #=> 1 -tup[0] = 3 # TypeError fırlatılır. - -# Litelerde yapılanların hepsini tüplerde de yapılabilir -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True - -# Tüplerin(veya listelerin) içerisindeki değerleri değişkenelere -# atanabilir -a, b, c = (1, 2, 3) # a şu anda 1, b şu anda 2 ve c şu anda 3 -# Eğer parantez kullanmaz iseniz tüpler varsayılan olarak oluşturulur -d, e, f = 4, 5, 6 -# şimdi iki değeri değiş tokuş etmek çok kolaydır. -e, d = d, e # d şimdi 5 ve e şimdi 4 - - -# Sözlükler (Dictionaries) key-value saklanır. -empty_dict = {} -# Sözlüklere önceden değer atama örneği -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Değere ulaşmak için [] kullanılır -filled_dict["one"] #=> 1 - -# Tüm anahtarlara(key) "keys()" metodu ile ulaşılır -filled_dict.keys() #=> ["three", "two", "one"] -# Not - Sözlüklerin anahtarlarının sıralı geleceği garanti değildir -# Sonuçlarınız değer listesini aldığınızda tamamen eşleşmeyebilir - -# Tüm değerleri almak için "values()" kullanabilirsiniz. -filled_dict.values() #=> [3, 2, 1] -# Not - Sıralama ile ilgili anahtarlar ile aynı durum geçerlidir. - -# Bir anahtarın sözlükte oluş olmadığını "in" ile kontrol edilebilir -"one" in filled_dict #=> True -1 in filled_dict #=> False - -# Olmayan bir anahtar çağrıldığında KeyError fırlatılır. -filled_dict["four"] # KeyError - -# "get()" metodu KeyError fırlatılmasını önler -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None -# get() metodu eğer anahtar mevcut değilse varsayılan bir değer atama -# imknaı sağlar. -filled_dict.get("one", 4) #=> 1 -filled_dict.get("four", 4) #=> 4 - -# "setdefault()" metodu sözlüğe yeni bir key-value eşleşmesi eklemenin -# güvenli bir yoludur. -filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 - - -# Sets store ... well sets -empty_set = set() -# Bir demek değer ile bir "set" oluşturmak -some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4]) - -# Python 2.7'den beri {}'ler bir "set" tanımlaman için kullanılabilir -filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} - -# Bir set'e daha fazla eleman eklemek -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} - -# "&" işareti ile iki set'in kesişimlerini alınabilir -other_set = {3, 4, 5, 6} -filled_set & other_set #=> {3, 4, 5} - -# | işareti ile -filled_set | other_set #=> {1, 2, 3, 4, 5, 6} - -# "-" işareti ile iki set'in farkları alınabilir -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# "in" ile değerin set içerisinde olup olmadığını kontrol edebilirsiniz -2 in filled_set #=> True -10 in filled_set #=> False - - -#################################################### -## 3. Akış Denetimi -#################################################### - -# Bir değişken oluşturmak -some_var = 5 - -# Buradaki bir if ifadesi. Girintiler(Intentation) Python'da önemlidir! -# "some_var is smaller than 10" yazdırılır. -if some_var > 10: - print "some_var is totally bigger than 10." -elif some_var < 10: # elif ifadesi isteğe bağlıdır - print "some_var is smaller than 10." -else: # Bu da isteğe bağlıdır. - print "some_var is indeed 10." - - -""" -For döngüleri listeler üzerinde iterasyon yapar -Ekrana yazdırılan: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # Biçimlendirmeleri string'e katmak için % kullanabilirsiniz - print "%s is a mammal" % animal - -""" -"range(number)" ifadesi sıfırdan verilen sayıya kadar bir sayı listesi döner -Ekrana yazdırılan: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -While döngüsü koşul sağlanmayana kadar devam eder -Ekrana yazdırılan: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # Shorthand for x = x + 1 - -# try/except bloğu ile hatalar ayıklanabilir - -# Python 2.6 ve üstü için çalışacaktır: -try: - # "raise" bir hata fırlatmak için kullanılabilir - raise IndexError("This is an index error") -except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. - - -#################################################### -## 4. Fonksiyonlar -#################################################### - - -# Yeni bir fonksiyon oluşturmak için "def" kullanılır -def add(x, y): - print "x is %s and y is %s" % (x, y) - return x + y # Return values with a return statement - -# Fonksiyonu parametre ile çağırmak -add(5, 6) #=> prints out "x is 5 and y is 6" and returns 11 - -# Diğer bir yol fonksiyonları anahtar argümanları ile çağırmak -add(y=6, x=5) # Anahtar argümanlarının sırası farklı da olabilir - -# Değişken sayıda parametresi olan bir fonksiyon tanımlayabilirsiniz -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - -# Değişken sayıda anahtar argümanlı parametre alan fonksiyonlar da -# tanımlayabilirsiniz. -def keyword_args(**kwargs): - return kwargs - -# Şu şekilde kullanılacaktır -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} - -# Eğer isterseniz ikisini aynı anda da yapabilirsiniz -def all_the_args(*args, **kwargs): - print args - print kwargs -""" -all_the_args(1, 2, a=3, b=4) prints: - (1, 2) - {"a": 3, "b": 4} -""" - -# Fonksiyonu çağırırken, args/kwargs'ın tam tersini de yapabilirsiniz! -# Tüpü yaymak için * ve kwargs'ı yaymak için ** kullanın. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # foo(1, 2, 3, 4) ile eşit -all_the_args(**kwargs) # foo(a=3, b=4) ile eşit -all_the_args(*args, **kwargs) # foo(1, 2, 3, 4, a=3, b=4) ile eşit - -# Python first-class fonksiyonlara sahiptir -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) #=> 13 - -# Anonymous fonksiyonlar da vardır -(lambda x: x > 2)(3) #=> True - -# Dahili yüksek seviye fonksiyonlar vardır -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# Map etme(maps) ve filtreleme(filtres) için liste kullanabiliriz. -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] - - -#################################################### -## 5. Sınıflar -#################################################### - -# We subclass from object to get a class. -class Human(object): - - # Bir sınıf özelliği. Bu sınıfın tüm "instance"larına paylaşılmıştır. - species = "H. sapiens" - - # Basic initializer - def __init__(self, name): - # Metoda gelen argümanın değerini sınıfın elemanı olan "name" - # değişkenine atama - self.name = name - - # Bir instance metodu. Tüm metodlar ilk argüman olarak "self" - # parametresini alır - def say(self, msg): - return "%s: %s" % (self.name, msg) - - # Bir sınıf metodu tüm "instance"lar arasında paylaşılır - # İlk argüman olarak sınıfı çağırarak çağrılırlar - @classmethod - def get_species(cls): - return cls.species - - # Bir statik metod bir sınıf ya da instance referansı olmadan çağrılır - @staticmethod - def grunt(): - return "*grunt*" - - -# Bir sınıf örneği oluşturmak -i = Human(name="Ian") -print i.say("hi") # "Ian: hi" çıktısı verir - -j = Human("Joel") -print j.say("hello") # "Joel: hello" çıktısı verir - -# Sınıf metodunu çağıralım -i.get_species() #=> "H. sapiens" - -# Paylaşılan sınıf özellik değiştirelim. -Human.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" - -# Statik metodu çağırma -Human.grunt() #=> "*grunt*" - - -#################################################### -## 6. Modüller -#################################################### - -# Modülleri sayfaya dahil edebilirsiniz -import math -print math.sqrt(16) #=> 4.0 - -# Modül içerisinden spesifik bir fonksiyonu getirebilirsiniz -from math import ceil, floor -print ceil(3.7) #=> 4.0 -print floor(3.7) #=> 3.0 - -# Modüldeki tüm fonksiyonları dahil edebilirsiniz -# Uyarı: bu önerilmez -from math import * - -# Modülün adını kısaltabilirsiniz -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Python modülleri sıradan python dosyalarıdır. Kendinize bir modül -# yazabilirsiniz, ve dahil edebilirsiniz. Modülün adı ile dosya adı -# aynı olmalıdır. - -# Modüllerde tanımlanmış fonksiyon ve metodları öğrenebilirsiniz. -import math -dir(math) - - - -``` - -## Daha fazlası için hazır mısınız? - -### Ücretsiz Dökümanlar - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2.6/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) - -### Dead Tree - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/tr-tr/pythonlegacy-tr.html.markdown b/tr-tr/pythonlegacy-tr.html.markdown new file mode 100644 index 00000000..99a3eb4e --- /dev/null +++ b/tr-tr/pythonlegacy-tr.html.markdown @@ -0,0 +1,502 @@ +--- +language: python +filename: learnpython-tr.py +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Haydar KULEKCI", "http://scanf.info/"] +lang: tr-tr +--- +Python Guido Van Rossum tarafından 90'ların başında yaratılmıştır. Şu anda +varolanlar arasında en iyi dillerden birisidir. Ben (Louie Dinh) Python +dilinin syntax'ının belirginliğine aşığım. O basit olarak çalıştırılabilir +pseudocode'dur. + +Geri bildirimlerden son derece mutluluk duyarım! Bana [@louiedinh](http://twitter.com/louiedinh) +adresinden ya da louiedinh [at] [google's email service] adresinden ulaşabilirsiniz. + +Çeviri için geri bildirimleri de [@kulekci](http://twitter.com/kulekci) +adresine yapabilirsiniz. + +Not: Bu yazıdaki özellikler Python 2.7 için geçerlidir, ama Python 2.x için de +uygulanabilir. Python 3 için başka bir zaman tekrar bakınız. + + +```python +# Tek satır yorum hash işareti ile başlar. +""" Çoklu satır diziler üç tane çift tırnak + arasında yazılır. Ve yorum olarak da + kullanılabilir +""" + + +#################################################### +## 1. İlkel Veri Tipleri ve Operatörler +#################################################### + +# Sayılar +3 #=> 3 + +# Matematik beklediğiniz gibi +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Bölünme biraz ilginç. EĞer tam sayılar üzerinde bölünme işlemi yapıyorsanız +# sonuç otomatik olarak kırpılır. +5 / 2 #=> 2 + +# Bölünme işlemini düzenlemek için kayan noktalı sayıları bilmeniz gerekir. +2.0 # Bu bir kayan noktalı sayı +11.0 / 4.0 #=> 2.75 ahhh...daha iyi + +# İşlem önceliğini parantezler ile sağlayabilirsiniz. +(1 + 3) * 2 #=> 8 + +# Boolean değerleri bilindiği gibi +True +False + +# not ile nagatif(mantıksal) değerini alma +not True #=> False +not False #=> True + +# Eşitlik == +1 == 1 #=> True +2 == 1 #=> False + +# Eşitsizlik != +1 != 1 #=> False +2 != 1 #=> True + +# Daha fazla karşılaştırma +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Karşılaştırma zincirleme yapılabilir! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Karakter dizisi " veya ' ile oluşturulabilir +"This is a string." +'This is also a string.' + +# Karakter dizileri birbirleri ile eklenebilir +"Hello " + "world!" #=> "Hello world!" + +# A string can be treated like a list of characters +# Bir string'e karakter listesi gibi davranabilirsiniz. +"This is a string"[0] #=> 'T' + +# % karakter dizisini(string) formatlamak için kullanılır, bunun gibi: +"%s can be %s" % ("strings", "interpolated") + +# String'leri formatlamanın yeni bir yöntem ise format metodudur. +# Bu metod tercih edilen yöntemdir. +"{0} can be {1}".format("strings", "formatted") +# Eğer saymak istemiyorsanız anahtar kelime kullanabilirsiniz. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") + +# None bir objedir +None #=> None + +# "==" eşitliğini non objesi ile karşılaştırmak için kullanmayın. +# Onun yerine "is" kullanın. +"etc" is None #=> False +None is None #=> True + +# 'is' operatörü obje kimliği için test etmektedir. Bu ilkel değerler +# için kullanışlı değildir, ama objeleri karşılaştırmak için kullanışlıdır. + +# None, 0 ve boş string/list'ler False olarak değerlendirilir. +# Tüm eşitlikler True döner +0 == False #=> True +"" == False #=> True + + +#################################################### +## 2. Değişkenler ve Kolleksiyonlar +#################################################### + +# Ekrana yazdırma oldukça kolaydır. +print "I'm Python. Nice to meet you!" + + +# Değişkenlere bir değer atamadan önce tanımlamaya gerek yoktur. +some_var = 5 # Değişken isimlerinde gelenek küçük karakter ve alt çizgi + # kullanmaktır. +some_var #=> 5 + +# Daha önceden tanımlanmamış ya da assign edilmemeiş bir değişkene erişmeye +# çalıştığınızda bir hata fırlatılacaktır. Hata ayıklama hakkında daha fazla +# bilgi için kontrol akışı kısmına göz atınız. +some_other_var # isim hatası fırlatılır + +# isterseniz "if"i bir ifade gibi kullanabilirsiniz. +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" + +# Listeler +li = [] +# Önceden değerleri tanımlanmış listeler +other_li = [4, 5, 6] + +# Bir listenin sonuna birşeyler eklemek +li.append(1) #li şu anda [1] +li.append(2) #li şu anda [1, 2] +li.append(4) #li şu anda [1, 2, 4] +li.append(3) #li şu anda [1, 2, 4, 3] +# pop ile sondan birşeyler silmek +li.pop() #=> 3 and li is now [1, 2, 4] +# Tekrar sonuna eklemek +li.append(3) # li is now [1, 2, 4, 3] again. + +# Dizi gibi listenin elemanlarına erişmek +li[0] #=> 1 +# Son elemanın değerine ulaşmak +li[-1] #=> 3 + +# Listede bulunmayan bir index'teki elemana erişirken "IndexError" hatası +# fırlatılır +li[4] # IndexError fırlatılır + +# slice syntax'ı ile belli aralıktakı değerlere bakabilirsiniz. +# (Açık ve kapalı aralıklıdır.) +li[1:3] #=> [2, 4] +# Başlangıcı ihmal etme +li[2:] #=> [4, 3] +# Sonu ihmal etme +li[:3] #=> [1, 2, 4] + +# "del" ile istenilen bir elemanı listeden silmek +del li[2] # li is now [1, 2, 3] + +# Listeleri birbiri ile birleştirebilirsiniz. +li + other_li #=> [1, 2, 3, 4, 5, 6] - Not: li ve other_li yanlız bırakılır + +# extend ile listeleri birleştirmek +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# bir değerin liste içerisinde varlığını "in" ile kontrol etmek +1 in li #=> True + +# "len" ile listenin uzunluğunu bulmak +len(li) #=> 6 + +# Tüpler listeler gibidir sadece değişmezler(immutable) +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # TypeError fırlatılır. + +# Litelerde yapılanların hepsini tüplerde de yapılabilir +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Tüplerin(veya listelerin) içerisindeki değerleri değişkenelere +# atanabilir +a, b, c = (1, 2, 3) # a şu anda 1, b şu anda 2 ve c şu anda 3 +# Eğer parantez kullanmaz iseniz tüpler varsayılan olarak oluşturulur +d, e, f = 4, 5, 6 +# şimdi iki değeri değiş tokuş etmek çok kolaydır. +e, d = d, e # d şimdi 5 ve e şimdi 4 + + +# Sözlükler (Dictionaries) key-value saklanır. +empty_dict = {} +# Sözlüklere önceden değer atama örneği +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Değere ulaşmak için [] kullanılır +filled_dict["one"] #=> 1 + +# Tüm anahtarlara(key) "keys()" metodu ile ulaşılır +filled_dict.keys() #=> ["three", "two", "one"] +# Not - Sözlüklerin anahtarlarının sıralı geleceği garanti değildir +# Sonuçlarınız değer listesini aldığınızda tamamen eşleşmeyebilir + +# Tüm değerleri almak için "values()" kullanabilirsiniz. +filled_dict.values() #=> [3, 2, 1] +# Not - Sıralama ile ilgili anahtarlar ile aynı durum geçerlidir. + +# Bir anahtarın sözlükte oluş olmadığını "in" ile kontrol edilebilir +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Olmayan bir anahtar çağrıldığında KeyError fırlatılır. +filled_dict["four"] # KeyError + +# "get()" metodu KeyError fırlatılmasını önler +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# get() metodu eğer anahtar mevcut değilse varsayılan bir değer atama +# imknaı sağlar. +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# "setdefault()" metodu sözlüğe yeni bir key-value eşleşmesi eklemenin +# güvenli bir yoludur. +filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 + + +# Sets store ... well sets +empty_set = set() +# Bir demek değer ile bir "set" oluşturmak +some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4]) + +# Python 2.7'den beri {}'ler bir "set" tanımlaman için kullanılabilir +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Bir set'e daha fazla eleman eklemek +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# "&" işareti ile iki set'in kesişimlerini alınabilir +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# | işareti ile +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# "-" işareti ile iki set'in farkları alınabilir +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# "in" ile değerin set içerisinde olup olmadığını kontrol edebilirsiniz +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Akış Denetimi +#################################################### + +# Bir değişken oluşturmak +some_var = 5 + +# Buradaki bir if ifadesi. Girintiler(Intentation) Python'da önemlidir! +# "some_var is smaller than 10" yazdırılır. +if some_var > 10: + print "some_var is totally bigger than 10." +elif some_var < 10: # elif ifadesi isteğe bağlıdır + print "some_var is smaller than 10." +else: # Bu da isteğe bağlıdır. + print "some_var is indeed 10." + + +""" +For döngüleri listeler üzerinde iterasyon yapar +Ekrana yazdırılan: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # Biçimlendirmeleri string'e katmak için % kullanabilirsiniz + print "%s is a mammal" % animal + +""" +"range(number)" ifadesi sıfırdan verilen sayıya kadar bir sayı listesi döner +Ekrana yazdırılan: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +While döngüsü koşul sağlanmayana kadar devam eder +Ekrana yazdırılan: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Shorthand for x = x + 1 + +# try/except bloğu ile hatalar ayıklanabilir + +# Python 2.6 ve üstü için çalışacaktır: +try: + # "raise" bir hata fırlatmak için kullanılabilir + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass is just a no-op. Usually you would do recovery here. + + +#################################################### +## 4. Fonksiyonlar +#################################################### + + +# Yeni bir fonksiyon oluşturmak için "def" kullanılır +def add(x, y): + print "x is %s and y is %s" % (x, y) + return x + y # Return values with a return statement + +# Fonksiyonu parametre ile çağırmak +add(5, 6) #=> prints out "x is 5 and y is 6" and returns 11 + +# Diğer bir yol fonksiyonları anahtar argümanları ile çağırmak +add(y=6, x=5) # Anahtar argümanlarının sırası farklı da olabilir + +# Değişken sayıda parametresi olan bir fonksiyon tanımlayabilirsiniz +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + +# Değişken sayıda anahtar argümanlı parametre alan fonksiyonlar da +# tanımlayabilirsiniz. +def keyword_args(**kwargs): + return kwargs + +# Şu şekilde kullanılacaktır +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Eğer isterseniz ikisini aynı anda da yapabilirsiniz +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# Fonksiyonu çağırırken, args/kwargs'ın tam tersini de yapabilirsiniz! +# Tüpü yaymak için * ve kwargs'ı yaymak için ** kullanın. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # foo(1, 2, 3, 4) ile eşit +all_the_args(**kwargs) # foo(a=3, b=4) ile eşit +all_the_args(*args, **kwargs) # foo(1, 2, 3, 4, a=3, b=4) ile eşit + +# Python first-class fonksiyonlara sahiptir +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Anonymous fonksiyonlar da vardır +(lambda x: x > 2)(3) #=> True + +# Dahili yüksek seviye fonksiyonlar vardır +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Map etme(maps) ve filtreleme(filtres) için liste kullanabiliriz. +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + + +#################################################### +## 5. Sınıflar +#################################################### + +# We subclass from object to get a class. +class Human(object): + + # Bir sınıf özelliği. Bu sınıfın tüm "instance"larına paylaşılmıştır. + species = "H. sapiens" + + # Basic initializer + def __init__(self, name): + # Metoda gelen argümanın değerini sınıfın elemanı olan "name" + # değişkenine atama + self.name = name + + # Bir instance metodu. Tüm metodlar ilk argüman olarak "self" + # parametresini alır + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Bir sınıf metodu tüm "instance"lar arasında paylaşılır + # İlk argüman olarak sınıfı çağırarak çağrılırlar + @classmethod + def get_species(cls): + return cls.species + + # Bir statik metod bir sınıf ya da instance referansı olmadan çağrılır + @staticmethod + def grunt(): + return "*grunt*" + + +# Bir sınıf örneği oluşturmak +i = Human(name="Ian") +print i.say("hi") # "Ian: hi" çıktısı verir + +j = Human("Joel") +print j.say("hello") # "Joel: hello" çıktısı verir + +# Sınıf metodunu çağıralım +i.get_species() #=> "H. sapiens" + +# Paylaşılan sınıf özellik değiştirelim. +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Statik metodu çağırma +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Modüller +#################################################### + +# Modülleri sayfaya dahil edebilirsiniz +import math +print math.sqrt(16) #=> 4.0 + +# Modül içerisinden spesifik bir fonksiyonu getirebilirsiniz +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Modüldeki tüm fonksiyonları dahil edebilirsiniz +# Uyarı: bu önerilmez +from math import * + +# Modülün adını kısaltabilirsiniz +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Python modülleri sıradan python dosyalarıdır. Kendinize bir modül +# yazabilirsiniz, ve dahil edebilirsiniz. Modülün adı ile dosya adı +# aynı olmalıdır. + +# Modüllerde tanımlanmış fonksiyon ve metodları öğrenebilirsiniz. +import math +dir(math) + + + +``` + +## Daha fazlası için hazır mısınız? + +### Ücretsiz Dökümanlar + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/uk-ua/python-ua.html.markdown b/uk-ua/python-ua.html.markdown deleted file mode 100644 index 4091e433..00000000 --- a/uk-ua/python-ua.html.markdown +++ /dev/null @@ -1,818 +0,0 @@ ---- -language: python -lang: uk-ua -contributors: - - ["Louie Dinh", "http://ldinh.ca"] - - ["Amin Bandali", "https://aminb.org"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["evuez", "http://github.com/evuez"] - - ["asyne", "https://github.com/justblah"] - - ["habi", "http://github.com/habi"] -translators: - - ["Oleh Hromiak", "https://github.com/ogroleg"] -filename: learnpython-ua.py ---- - -Мову Python створив Гвідо ван Россум на початку 90-х. Наразі це одна з -найбільш популярних мов. Я закохався у Python завдяки простому і зрозумілому -синтаксису. Це майже як виконуваний псевдокод. - -З вдячністю чекаю ваших відгуків: [@louiedinh](http://twitter.com/louiedinh) -або louiedinh [at] [поштовий сервіс від Google] - -Примітка: Ця стаття стосується Python 2.7, проте має працювати і -у інших версіях Python 2.x. Python 2.7 підходить до кінця свого терміну, -його підтримку припинять у 2020, тож наразі краще починати вивчення Python -з версії 3.x. -Аби вивчити Python 3.x, звертайтесь до статті по Python 3. - -```python -# Однорядкові коментарі починаються з символу решітки. - -""" Текст, що займає декілька рядків, - може бути записаний з використанням 3 знаків " і - зазвичай використовується у якості - вбудованої документації -""" - -#################################################### -## 1. Примітивні типи даних та оператори -#################################################### - -# У вас є числа -3 # => 3 - -# Математика працює досить передбачувано -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7 - -# А ось з діленням все трохи складніше. Воно цілочисельне і результат -# автоматично округлюється у меншу сторону. -5 / 2 # => 2 - -# Аби правильно ділити, спершу варто дізнатися про числа -# з плаваючою комою. -2.0 # Це число з плаваючою комою -11.0 / 4.0 # => 2.75 ох... Так набагато краще - -# Результат цілочисельного ділення округлюється у меншу сторону -# як для додатніх, так і для від'ємних чисел. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # Працює і для чисел з плаваючою комою --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Зверніть увагу, що ми також можемо імпортувати модуль для ділення, -# див. розділ Модулі -# аби звичне ділення працювало при використанні лише '/'. -from __future__ import division - -11 / 4 # => 2.75 ...звичне ділення -11 // 4 # => 2 ...цілочисельне ділення - -# Залишок від ділення -7 % 3 # => 1 - -# Піднесення до степеня -2 ** 4 # => 16 - -# Приорітет операцій вказується дужками -(1 + 3) * 2 # => 8 - -# Логічні оператори -# Зверніть увагу: ключові слова «and» і «or» чутливі до регістру букв -True and False # => False -False or True # => True - -# Завважте, що логічні оператори також використовуються і з цілими числами -0 and 2 # => 0 --5 or 0 # => -5 -0 == False # => True -2 == True # => False -1 == True # => True - -# Для заперечення використовується not -not True # => False -not False # => True - -# Рівність — це == -1 == 1 # => True -2 == 1 # => False - -# Нерівність — це != -1 != 1 # => False -2 != 1 # => True - -# Ще трохи порівнянь -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Порівняння можуть бути записані ланцюжком! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# Рядки позначаються символом " або ' -"Це рядок." -'Це теж рядок.' - -# І рядки також можна додавати! -"Привіт " + "світ!" # => "Привіт світ!" -# Рядки можна додавати і без '+' -"Привіт " "світ!" # => "Привіт світ!" - -# ... або множити -"Привіт" * 3 # => "ПривітПривітПривіт" - -# З рядком можна працювати як зі списком символів -"Це рядок"[0] # => 'Ц' - -# Ви можете дізнатися довжину рядка -len("Це рядок") # => 8 - -# Символ % використовується для форматування рядків, наприклад: -"%s можуть бути %s" % ("рядки", "інтерпольовані") - -# Новий спосіб форматування рядків — використання методу format. -# Це бажаний спосіб. -"{} є {}".format("Це", "заповнювач") -"{0} можуть бути {1}".format("рядки", "форматовані") -# Якщо ви не хочете рахувати, то можете скористатися ключовими словами. -"{name} хоче з'істи {food}".format(name="Боб", food="лазанью") - -# None - це об'єкт -None # => None - -# Не використовуйте оператор рівності '=='' для порівняння -# об'єктів з None. Використовуйте для цього «is» -"etc" is None # => False -None is None # => True - -# Оператор 'is' перевіряє ідентичність об'єктів. Він не -# дуже корисний при роботі з примітивними типами, проте -# незамінний при роботі з об'єктами. - -# None, 0 і порожні рядки/списки рівні False. -# Всі інші значення рівні True -bool(0) # => False -bool("") # => False - - -#################################################### -## 2. Змінні та колекції -#################################################### - -# В Python є оператор print -print "Я Python. Приємно познайомитись!" # => Я Python. Приємно познайомитись! - -# Отримати дані з консолі просто -input_string_var = raw_input( - "Введіть щось: ") # Повертає дані у вигляді рядка -input_var = input("Введіть щось: ") # Працює з даними як з кодом на python -# Застереження: будьте обережні при використанні методу input() - -# Оголошувати змінні перед ініціалізацією не потрібно. -some_var = 5 # За угодою використовується нижній_регістр_з_підкресленнями -some_var # => 5 - -# При спробі доступу до неініціалізованої змінної -# виникне виняткова ситуація. -# Див. розділ Потік управління, аби дізнатись про винятки більше. -some_other_var # Помилка в імені - -# if може використовуватися як вираз -# Такий запис еквівалентний тернарному оператору '?:' у мові С -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# Списки зберігають послідовності -li = [] -# Можна одразу створити заповнений список -other_li = [4, 5, 6] - -# Об'єкти додаються у кінець списку за допомогою методу append -li.append(1) # li тепер дорівнює [1] -li.append(2) # li тепер дорівнює [1, 2] -li.append(4) # li тепер дорівнює [1, 2, 4] -li.append(3) # li тепер дорівнює [1, 2, 4, 3] -# І видаляються з кінця методом pop -li.pop() # => повертає 3 і li стає рівним [1, 2, 4] -# Повернемо елемент назад -li.append(3) # li тепер знову дорівнює [1, 2, 4, 3] - -# Поводьтесь зі списком як зі звичайним масивом -li[0] # => 1 -# Присвоюйте нові значення вже ініціалізованим індексам за допомогою = -li[0] = 42 -li[0] # => 42 -li[0] = 1 # Зверніть увагу: повертаємось до попереднього значення -# Звертаємось до останнього елементу -li[-1] # => 3 - -# Спроба вийти за границі масиву призводить до помилки в індексі -li[4] # помилка в індексі - -# Можна звертатися до діапазону, використовуючи так звані зрізи -# (Для тих, хто любить математику: це називається замкнуто-відкритий інтервал). -li[1:3] # => [2, 4] -# Опускаємо початок -li[2:] # => [4, 3] -# Опускаємо кінець -li[:3] # => [1, 2, 4] -# Вибираємо кожен другий елемент -li[::2] # => [1, 4] -# Перевертаємо список -li[::-1] # => [3, 4, 2, 1] -# Використовуйте суміш вищеназваного для більш складних зрізів -# li[початок:кінець:крок] - -# Видаляємо довільні елементи зі списку оператором del -del li[2] # li тепер [1, 2, 3] - -# Ви можете додавати списки -li + other_li # => [1, 2, 3, 4, 5, 6] -# Зверніть увагу: значення li та other_li при цьому не змінились. - -# Поєднувати списки можна за допомогою методу extend -li.extend(other_li) # Тепер li дорівнює [1, 2, 3, 4, 5, 6] - -# Видалити перше входження значення -li.remove(2) # Тепер li дорівнює [1, 3, 4, 5, 6] -li.remove(2) # Помилка значення, оскільки у списку li немає 2 - -# Вставити елемент за вказаним індексом -li.insert(1, 2) # li знову дорівнює [1, 2, 3, 4, 5, 6] - -# Отримати індекс першого знайденого елементу -li.index(2) # => 1 -li.index(7) # Помилка значення, оскільки у списку li немає 7 - -# Перевірити елемент на входження у список можна оператором in -1 in li # => True - -# Довжина списку обчислюється за допомогою функції len -len(li) # => 6 - -# Кортежі схожі на списки, лише незмінні -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Виникає помилка типу - -# Все те ж саме можна робити і з кортежами -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Ви можете розпаковувати кортежі (або списки) у змінні -a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3 -d, e, f = 4, 5, 6 # дужки можна опустити -# Кортежі створюються за замовчуванням, якщо дужки опущено -g = 4, 5, 6 # => (4, 5, 6) -# Дивіться, як легко обміняти значення двох змінних -e, d = d, e # тепер d дорівнює 5, а e дорівнює 4 - -# Словники містять асоціативні масиви -empty_dict = {} -# Ось так описується попередньо заповнений словник -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Значення можна отримати так само, як і зі списку -filled_dict["one"] # => 1 - -# Можна отримати всі ключі у виді списку за допомогою методу keys -filled_dict.keys() # => ["three", "two", "one"] -# Примітка: збереження порядку ключів у словників не гарантується -# Ваші результати можуть не співпадати з цими. - -# Можна отримати і всі значення у вигляді списку, використовуйте метод values -filled_dict.values() # => [3, 2, 1] -# Те ж зауваження щодо порядку ключів діє і тут - -# Отримуйте всі пари ключ-значення у вигляді списку кортежів -# за допомогою "items()" -filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] - -# За допомогою оператору in можна перевіряти ключі на входження у словник -"one" in filled_dict # => True -1 in filled_dict # => False - -# Спроба отримати значення за неіснуючим ключем викине помилку ключа -filled_dict["four"] # помилка ключа - -# Аби уникнути цього, використовуйте метод get() -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# Метод get також приймає аргумент за замовчуванням, значення якого буде -# повернуто при відсутності вказаного ключа -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 -# Зверніть увагу, що filled_dict.get("four") все ще => None -# (get не встановлює значення елементу словника) - -# Присвоюйте значення ключам так само, як і в списках -filled_dict["four"] = 4 # тепер filled_dict["four"] => 4 - -# Метод setdefault() вставляє пару ключ-значення лише -# за відсутності такого ключа -filled_dict.setdefault("five", 5) # filled_dict["five"] повертає 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] все ще повертає 5 - - -# Множини містять... ну, загалом, множини -# (які схожі на списки, проте в них не може бути елементів, які повторюються) -empty_set = set() -# Ініціалізація множини набором значень -some_set = set([1,2,2,3,4]) # some_set тепер дорівнює set([1, 2, 3, 4]) - -# Порядок не гарантовано, хоча інколи множини виглядають відсортованими -another_set = set([4, 3, 2, 2, 1]) # another_set тепер set([1, 2, 3, 4]) - -# Починаючи з Python 2.7, ви можете використовувати {}, аби створити множину -filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} - -# Додавання нових елементів у множину -filled_set.add(5) # filled_set тепер дорівнює {1, 2, 3, 4, 5} - -# Перетин множин: & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# Об'єднання множин: | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Різниця множин: - -{1,2,3,4} - {2,3,5} # => {1, 4} - -# Симетрична різниця множин: ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Перевіряємо чи множина зліва є надмножиною множини справа -{1, 2} >= {1, 2, 3} # => False - -# Перевіряємо чи множина зліва є підмножиною множини справа -{1, 2} <= {1, 2, 3} # => True - -# Перевірка на входження у множину: in -2 in filled_set # => True -10 in filled_set # => False - - -#################################################### -## 3. Потік управління -#################################################### - -# Для початку створимо змінну -some_var = 5 - -# Так виглядає вираз if. Відступи у python дуже важливі! -# результат: «some_var менше, ніж 10» -if some_var > 10: - print("some_var набагато більше, ніж 10.") -elif some_var < 10: # Вираз elif є необов'язковим. - print("some_var менше, ніж 10.") -else: # Це теж необов'язково. - print("some_var дорівнює 10.") - - -""" -Цикли For проходять по спискам - -Результат: - собака — це ссавець - кішка — це ссавець - миша — це ссавець -""" -for animal in ["собака", "кішка", "миша"]: - # Можете використовувати оператор {0} для інтерполяції форматованих рядків - print "{0} — це ссавець".format(animal) - -""" -"range(число)" повертає список чисел -від нуля до заданого числа -Друкує: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) -""" -"range(нижня_границя, верхня_границя)" повертає список чисел -від нижньої границі до верхньої -Друкує: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print i - -""" -Цикли while продовжуються до тих пір, поки вказана умова не стане хибною. -Друкує: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Короткий запис для x = x + 1 - -# Обробляйте винятки блоками try/except - -# Працює у Python 2.6 і вище: -try: - # Аби створити виняток, використовується raise - raise IndexError("Помилка у індексі!") -except IndexError as e: - pass # pass — оператор, який нічого не робить. Зазвичай тут відбувається - # відновлення після помилки. -except (TypeError, NameError): - pass # Винятки можна обробляти групами, якщо потрібно. -else: # Необов'язковий вираз. Має слідувати за останнім блоком except - print("Все добре!") # Виконається лише якщо не було ніяких винятків -finally: # Виконується у будь-якому випадку - print "Тут ми можемо звільнити ресурси" - -# Замість try/finally для звільнення ресурсів -# ви можете використовувати вираз with -with open("myfile.txt") as f: - for line in f: - print line - - -#################################################### -## 4. Функції -#################################################### - -# Використовуйте def для створення нових функцій -def add(x, y): - print "x дорівнює {0}, а y дорівнює {1}".format(x, y) - return x + y # Повертайте результат за допомогою ключового слова return - - -# Виклик функції з аргументами -add(5, 6) # => друкує «x дорівнює 5, а y дорівнює 6» і повертає 11 - -# Інший спосіб виклику функції — виклик з іменованими аргументами -add(y=6, x=5) # Іменовані аргументи можна вказувати у будь-якому порядку - - -# Ви можете визначити функцію, яка приймає змінну кількість аргументів, -# які будуть інтерпретовані як кортеж, за допомогою * -def varargs(*args): - return args - - -varargs(1, 2, 3) # => (1,2,3) - - -# А також можете визначити функцію, яка приймає змінне число -# іменованих аргументів, котрі будуть інтерпретовані як словник, за допомогою ** -def keyword_args(**kwargs): - return kwargs - - -# Давайте подивимось що з цього вийде -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - -# Якщо хочете, можете використовувати обидва способи одночасно -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) - - -""" -all_the_args(1, 2, a=3, b=4) друкує: - (1, 2) - {"a": 3, "b": 4} -""" - -# Коли викликаєте функції, то можете зробити навпаки! -# Використовуйте символ * аби розпакувати позиційні аргументи і -# ** для іменованих аргументів -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # еквівалентно foo(1, 2, 3, 4) -all_the_args(**kwargs) # еквівалентно foo(a=3, b=4) -all_the_args(*args, **kwargs) # еквівалентно foo(1, 2, 3, 4, a=3, b=4) - -# ви можете передавати довільне число позиційних або іменованих аргументів -# іншим функціям, які їх приймають, розпаковуючи за допомогою -# * або ** відповідно -def pass_all_the_args(*args, **kwargs): - all_the_args(*args, **kwargs) - print varargs(*args) - print keyword_args(**kwargs) - - -# Область визначення функцій -x = 5 - - -def set_x(num): - # Локальна змінна x - не те ж саме, що глобальна змінна x - x = num # => 43 - print x # => 43 - - -def set_global_x(num): - global x - print x # => 5 - x = num # глобальна змінна x тепер дорівнює 6 - print x # => 6 - - -set_x(43) -set_global_x(6) - -# В Python функції є об'єктами першого класу -def create_adder(x): - def adder(y): - return x + y - - return adder - - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Також є і анонімні функції -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# Присутні вбудовані функції вищого порядку -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] - -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# Для зручного відображення і фільтрації можна використовувати -# включення у вигляді списків -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# Ви також можете скористатися включеннями множин та словників -{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'} -{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -## 5. Класи -#################################################### - -# Аби отримати клас, ми наслідуємо object. -class Human(object): - # Атрибут класу. Він розділяється всіма екземплярами цього класу. - species = "H. sapiens" - - # Звичайний конструктор, буде викликаний при ініціалізації екземпляру класу - # Зверніть увагу, що подвійне підкреслення на початку та наприкінці імені - # використовується для позначення об'єктів та атрибутів, - # які використовуються Python, але знаходяться у просторах імен, - # якими керує користувач. Не варто вигадувати для них імена самостійно. - def __init__(self, name): - # Присвоєння значення аргумента атрибуту класу name - self.name = name - - # Ініціалізуємо властивість - self.age = 0 - - # Метод екземпляру. Всі методи приймають self у якості першого аргументу - def say(self, msg): - return "%s: %s" % (self.name, msg) - - # Методи класу розділяються між усіма екземплярами - # Вони викликаються з вказанням викликаючого класу - # у якості першого аргументу - @classmethod - def get_species(cls): - return cls.species - - # Статичний метод викликається без посилання на клас або екземпляр - @staticmethod - def grunt(): - return "*grunt*" - - # Властивість. - # Перетворює метод age() в атрибут тільки для читання - # з таким же ім'ям. - @property - def age(self): - return self._age - - # Це дозволяє змінювати значення властивості - @age.setter - def age(self, age): - self._age = age - - # Це дозволяє видаляти властивість - @age.deleter - def age(self): - del self._age - - -# Створюємо екземпляр класу -i = Human(name="Данило") -print(i.say("привіт")) # Друкує: «Данило: привіт» - -j = Human("Меланка") -print(j.say("Привіт")) # Друкує: «Меланка: привіт» - -# Виклик методу класу -i.get_species() # => "H. sapiens" - -# Зміна розділюваного атрибуту -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# Виклик статичного методу -Human.grunt() # => "*grunt*" - -# Оновлюємо властивість -i.age = 42 - -# Отримуємо значення -i.age # => 42 - -# Видаляємо властивість -del i.age -i.age # => виникає помилка атрибуту - -#################################################### -## 6. Модулі -#################################################### - -# Ви можете імпортувати модулі -import math - -print(math.sqrt(16)) # => 4.0 - -# Ви можете імпортувати окремі функції з модуля -from math import ceil, floor - -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Можете імпортувати всі функції модуля. -# Попередження: краще так не робіть -from math import * - -# Можете скорочувати імена модулів -import math as m - -math.sqrt(16) == m.sqrt(16) # => True -# Ви також можете переконатися, що функції еквівалентні -from math import sqrt - -math.sqrt == m.sqrt == sqrt # => True - -# Модулі в Python — це звичайні Python-файли. Ви -# можете писати свої модулі та імпортувати їх. Назва -# модуля співпадає з назвою файлу. - -# Ви можете дізнатися, які функції та атрибути визначені -# в модулі -import math - -dir(math) - - -# Якщо у вас є Python скрипт з назвою math.py у тій же папці, що -# і ваш поточний скрипт, то файл math.py -# може бути завантажено замість вбудованого у Python модуля. -# Так трапляється, оскільки локальна папка має перевагу -# над вбудованими у Python бібліотеками. - -#################################################### -## 7. Додатково -#################################################### - -# Генератори -# Генератор "генерує" значення тоді, коли вони запитуються, замість того, -# щоб зберігати все одразу - -# Метод нижче (*НЕ* генератор) подвоює всі значення і зберігає їх -# в `double_arr`. При великих розмірах може знадобитися багато ресурсів! -def double_numbers(iterable): - double_arr = [] - for i in iterable: - double_arr.append(i + i) - return double_arr - - -# Тут ми спочатку подвоюємо всі значення, потім повертаємо їх, -# аби перевірити умову -for value in double_numbers(range(1000000)): # `test_non_generator` - print value - if value > 5: - break - - -# Натомість ми можемо скористатися генератором, аби "згенерувати" -# подвійне значення, як тільки воно буде запитане -def double_numbers_generator(iterable): - for i in iterable: - yield i + i - - -# Той самий код, але вже з генератором, тепер дозволяє нам пройтися по -# значенням і подвоювати їх одне за одним якраз тоді, коли вони обробляються -# за нашою логікою, одне за одним. А як тільки ми бачимо, що value > 5, ми -# виходимо з циклу і більше не подвоюємо більшість значень, -# які отримали на вхід (НАБАГАТО ШВИДШЕ!) -for value in double_numbers_generator(xrange(1000000)): # `test_generator` - print value - if value > 5: - break - -# Між іншим: ви помітили використання `range` у `test_non_generator` і -# `xrange` у `test_generator`? -# Як `double_numbers_generator` є версією-генератором `double_numbers`, так -# і `xrange` є аналогом `range`, але у вигляді генератора. -# `range` поверне нам масив з 1000000 значень -# `xrange`, у свою чергу, згенерує 1000000 значень для нас тоді, -# коли ми їх запитуємо / будемо проходитись по ним. - -# Аналогічно включенням у вигляді списків, ви можете створювати включення -# у вигляді генераторів. -values = (-x for x in [1, 2, 3, 4, 5]) -for x in values: - print(x) # друкує -1 -2 -3 -4 -5 - -# Включення у вигляді генератора можна явно перетворити у список -values = (-x for x in [1, 2, 3, 4, 5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - -# Декоратори -# Декоратор – це функція вищого порядку, яка приймає та повертає функцію. -# Простий приклад використання – декоратор add_apples додає елемент 'Apple' в -# список fruits, який повертає цільова функція get_fruits. -def add_apples(func): - def get_fruits(): - fruits = func() - fruits.append('Apple') - return fruits - return get_fruits - -@add_apples -def get_fruits(): - return ['Banana', 'Mango', 'Orange'] - -# Друкуємо список разом з елементом 'Apple', який знаходиться в ньому: -# Banana, Mango, Orange, Apple -print ', '.join(get_fruits()) - -# У цьому прикладі beg обертає say -# Beg викличе say. Якщо say_please дорівнюватиме True, то повідомлення, -# що повертається, буде змінено. -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Будь ласка! Я бідний :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Ви можете купити мені пива?" - return msg, say_please - - -print say() # Ви можете купити мені пива? -print say(say_please=True) # Ви можете купити мені пива? Будь ласка! Я бідний :( -``` - -## Готові до більшого? - -### Безкоштовні онлайн-матеріали - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Официальная документация](http://docs.python.org/2.6/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) - -### Платні - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/uk-ua/pythonlegacy-ua.html.markdown b/uk-ua/pythonlegacy-ua.html.markdown new file mode 100644 index 00000000..4091e433 --- /dev/null +++ b/uk-ua/pythonlegacy-ua.html.markdown @@ -0,0 +1,818 @@ +--- +language: python +lang: uk-ua +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "https://aminb.org"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] + - ["asyne", "https://github.com/justblah"] + - ["habi", "http://github.com/habi"] +translators: + - ["Oleh Hromiak", "https://github.com/ogroleg"] +filename: learnpython-ua.py +--- + +Мову Python створив Гвідо ван Россум на початку 90-х. Наразі це одна з +найбільш популярних мов. Я закохався у Python завдяки простому і зрозумілому +синтаксису. Це майже як виконуваний псевдокод. + +З вдячністю чекаю ваших відгуків: [@louiedinh](http://twitter.com/louiedinh) +або louiedinh [at] [поштовий сервіс від Google] + +Примітка: Ця стаття стосується Python 2.7, проте має працювати і +у інших версіях Python 2.x. Python 2.7 підходить до кінця свого терміну, +його підтримку припинять у 2020, тож наразі краще починати вивчення Python +з версії 3.x. +Аби вивчити Python 3.x, звертайтесь до статті по Python 3. + +```python +# Однорядкові коментарі починаються з символу решітки. + +""" Текст, що займає декілька рядків, + може бути записаний з використанням 3 знаків " і + зазвичай використовується у якості + вбудованої документації +""" + +#################################################### +## 1. Примітивні типи даних та оператори +#################################################### + +# У вас є числа +3 # => 3 + +# Математика працює досить передбачувано +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# А ось з діленням все трохи складніше. Воно цілочисельне і результат +# автоматично округлюється у меншу сторону. +5 / 2 # => 2 + +# Аби правильно ділити, спершу варто дізнатися про числа +# з плаваючою комою. +2.0 # Це число з плаваючою комою +11.0 / 4.0 # => 2.75 ох... Так набагато краще + +# Результат цілочисельного ділення округлюється у меншу сторону +# як для додатніх, так і для від'ємних чисел. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # Працює і для чисел з плаваючою комою +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Зверніть увагу, що ми також можемо імпортувати модуль для ділення, +# див. розділ Модулі +# аби звичне ділення працювало при використанні лише '/'. +from __future__ import division + +11 / 4 # => 2.75 ...звичне ділення +11 // 4 # => 2 ...цілочисельне ділення + +# Залишок від ділення +7 % 3 # => 1 + +# Піднесення до степеня +2 ** 4 # => 16 + +# Приорітет операцій вказується дужками +(1 + 3) * 2 # => 8 + +# Логічні оператори +# Зверніть увагу: ключові слова «and» і «or» чутливі до регістру букв +True and False # => False +False or True # => True + +# Завважте, що логічні оператори також використовуються і з цілими числами +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Для заперечення використовується not +not True # => False +not False # => True + +# Рівність — це == +1 == 1 # => True +2 == 1 # => False + +# Нерівність — це != +1 != 1 # => False +2 != 1 # => True + +# Ще трохи порівнянь +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Порівняння можуть бути записані ланцюжком! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Рядки позначаються символом " або ' +"Це рядок." +'Це теж рядок.' + +# І рядки також можна додавати! +"Привіт " + "світ!" # => "Привіт світ!" +# Рядки можна додавати і без '+' +"Привіт " "світ!" # => "Привіт світ!" + +# ... або множити +"Привіт" * 3 # => "ПривітПривітПривіт" + +# З рядком можна працювати як зі списком символів +"Це рядок"[0] # => 'Ц' + +# Ви можете дізнатися довжину рядка +len("Це рядок") # => 8 + +# Символ % використовується для форматування рядків, наприклад: +"%s можуть бути %s" % ("рядки", "інтерпольовані") + +# Новий спосіб форматування рядків — використання методу format. +# Це бажаний спосіб. +"{} є {}".format("Це", "заповнювач") +"{0} можуть бути {1}".format("рядки", "форматовані") +# Якщо ви не хочете рахувати, то можете скористатися ключовими словами. +"{name} хоче з'істи {food}".format(name="Боб", food="лазанью") + +# None - це об'єкт +None # => None + +# Не використовуйте оператор рівності '=='' для порівняння +# об'єктів з None. Використовуйте для цього «is» +"etc" is None # => False +None is None # => True + +# Оператор 'is' перевіряє ідентичність об'єктів. Він не +# дуже корисний при роботі з примітивними типами, проте +# незамінний при роботі з об'єктами. + +# None, 0 і порожні рядки/списки рівні False. +# Всі інші значення рівні True +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Змінні та колекції +#################################################### + +# В Python є оператор print +print "Я Python. Приємно познайомитись!" # => Я Python. Приємно познайомитись! + +# Отримати дані з консолі просто +input_string_var = raw_input( + "Введіть щось: ") # Повертає дані у вигляді рядка +input_var = input("Введіть щось: ") # Працює з даними як з кодом на python +# Застереження: будьте обережні при використанні методу input() + +# Оголошувати змінні перед ініціалізацією не потрібно. +some_var = 5 # За угодою використовується нижній_регістр_з_підкресленнями +some_var # => 5 + +# При спробі доступу до неініціалізованої змінної +# виникне виняткова ситуація. +# Див. розділ Потік управління, аби дізнатись про винятки більше. +some_other_var # Помилка в імені + +# if може використовуватися як вираз +# Такий запис еквівалентний тернарному оператору '?:' у мові С +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Списки зберігають послідовності +li = [] +# Можна одразу створити заповнений список +other_li = [4, 5, 6] + +# Об'єкти додаються у кінець списку за допомогою методу append +li.append(1) # li тепер дорівнює [1] +li.append(2) # li тепер дорівнює [1, 2] +li.append(4) # li тепер дорівнює [1, 2, 4] +li.append(3) # li тепер дорівнює [1, 2, 4, 3] +# І видаляються з кінця методом pop +li.pop() # => повертає 3 і li стає рівним [1, 2, 4] +# Повернемо елемент назад +li.append(3) # li тепер знову дорівнює [1, 2, 4, 3] + +# Поводьтесь зі списком як зі звичайним масивом +li[0] # => 1 +# Присвоюйте нові значення вже ініціалізованим індексам за допомогою = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Зверніть увагу: повертаємось до попереднього значення +# Звертаємось до останнього елементу +li[-1] # => 3 + +# Спроба вийти за границі масиву призводить до помилки в індексі +li[4] # помилка в індексі + +# Можна звертатися до діапазону, використовуючи так звані зрізи +# (Для тих, хто любить математику: це називається замкнуто-відкритий інтервал). +li[1:3] # => [2, 4] +# Опускаємо початок +li[2:] # => [4, 3] +# Опускаємо кінець +li[:3] # => [1, 2, 4] +# Вибираємо кожен другий елемент +li[::2] # => [1, 4] +# Перевертаємо список +li[::-1] # => [3, 4, 2, 1] +# Використовуйте суміш вищеназваного для більш складних зрізів +# li[початок:кінець:крок] + +# Видаляємо довільні елементи зі списку оператором del +del li[2] # li тепер [1, 2, 3] + +# Ви можете додавати списки +li + other_li # => [1, 2, 3, 4, 5, 6] +# Зверніть увагу: значення li та other_li при цьому не змінились. + +# Поєднувати списки можна за допомогою методу extend +li.extend(other_li) # Тепер li дорівнює [1, 2, 3, 4, 5, 6] + +# Видалити перше входження значення +li.remove(2) # Тепер li дорівнює [1, 3, 4, 5, 6] +li.remove(2) # Помилка значення, оскільки у списку li немає 2 + +# Вставити елемент за вказаним індексом +li.insert(1, 2) # li знову дорівнює [1, 2, 3, 4, 5, 6] + +# Отримати індекс першого знайденого елементу +li.index(2) # => 1 +li.index(7) # Помилка значення, оскільки у списку li немає 7 + +# Перевірити елемент на входження у список можна оператором in +1 in li # => True + +# Довжина списку обчислюється за допомогою функції len +len(li) # => 6 + +# Кортежі схожі на списки, лише незмінні +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Виникає помилка типу + +# Все те ж саме можна робити і з кортежами +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Ви можете розпаковувати кортежі (або списки) у змінні +a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3 +d, e, f = 4, 5, 6 # дужки можна опустити +# Кортежі створюються за замовчуванням, якщо дужки опущено +g = 4, 5, 6 # => (4, 5, 6) +# Дивіться, як легко обміняти значення двох змінних +e, d = d, e # тепер d дорівнює 5, а e дорівнює 4 + +# Словники містять асоціативні масиви +empty_dict = {} +# Ось так описується попередньо заповнений словник +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Значення можна отримати так само, як і зі списку +filled_dict["one"] # => 1 + +# Можна отримати всі ключі у виді списку за допомогою методу keys +filled_dict.keys() # => ["three", "two", "one"] +# Примітка: збереження порядку ключів у словників не гарантується +# Ваші результати можуть не співпадати з цими. + +# Можна отримати і всі значення у вигляді списку, використовуйте метод values +filled_dict.values() # => [3, 2, 1] +# Те ж зауваження щодо порядку ключів діє і тут + +# Отримуйте всі пари ключ-значення у вигляді списку кортежів +# за допомогою "items()" +filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] + +# За допомогою оператору in можна перевіряти ключі на входження у словник +"one" in filled_dict # => True +1 in filled_dict # => False + +# Спроба отримати значення за неіснуючим ключем викине помилку ключа +filled_dict["four"] # помилка ключа + +# Аби уникнути цього, використовуйте метод get() +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# Метод get також приймає аргумент за замовчуванням, значення якого буде +# повернуто при відсутності вказаного ключа +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 +# Зверніть увагу, що filled_dict.get("four") все ще => None +# (get не встановлює значення елементу словника) + +# Присвоюйте значення ключам так само, як і в списках +filled_dict["four"] = 4 # тепер filled_dict["four"] => 4 + +# Метод setdefault() вставляє пару ключ-значення лише +# за відсутності такого ключа +filled_dict.setdefault("five", 5) # filled_dict["five"] повертає 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] все ще повертає 5 + + +# Множини містять... ну, загалом, множини +# (які схожі на списки, проте в них не може бути елементів, які повторюються) +empty_set = set() +# Ініціалізація множини набором значень +some_set = set([1,2,2,3,4]) # some_set тепер дорівнює set([1, 2, 3, 4]) + +# Порядок не гарантовано, хоча інколи множини виглядають відсортованими +another_set = set([4, 3, 2, 2, 1]) # another_set тепер set([1, 2, 3, 4]) + +# Починаючи з Python 2.7, ви можете використовувати {}, аби створити множину +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Додавання нових елементів у множину +filled_set.add(5) # filled_set тепер дорівнює {1, 2, 3, 4, 5} + +# Перетин множин: & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Об'єднання множин: | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Різниця множин: - +{1,2,3,4} - {2,3,5} # => {1, 4} + +# Симетрична різниця множин: ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Перевіряємо чи множина зліва є надмножиною множини справа +{1, 2} >= {1, 2, 3} # => False + +# Перевіряємо чи множина зліва є підмножиною множини справа +{1, 2} <= {1, 2, 3} # => True + +# Перевірка на входження у множину: in +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. Потік управління +#################################################### + +# Для початку створимо змінну +some_var = 5 + +# Так виглядає вираз if. Відступи у python дуже важливі! +# результат: «some_var менше, ніж 10» +if some_var > 10: + print("some_var набагато більше, ніж 10.") +elif some_var < 10: # Вираз elif є необов'язковим. + print("some_var менше, ніж 10.") +else: # Це теж необов'язково. + print("some_var дорівнює 10.") + + +""" +Цикли For проходять по спискам + +Результат: + собака — це ссавець + кішка — це ссавець + миша — це ссавець +""" +for animal in ["собака", "кішка", "миша"]: + # Можете використовувати оператор {0} для інтерполяції форматованих рядків + print "{0} — це ссавець".format(animal) + +""" +"range(число)" повертає список чисел +від нуля до заданого числа +Друкує: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) +""" +"range(нижня_границя, верхня_границя)" повертає список чисел +від нижньої границі до верхньої +Друкує: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +Цикли while продовжуються до тих пір, поки вказана умова не стане хибною. +Друкує: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Короткий запис для x = x + 1 + +# Обробляйте винятки блоками try/except + +# Працює у Python 2.6 і вище: +try: + # Аби створити виняток, використовується raise + raise IndexError("Помилка у індексі!") +except IndexError as e: + pass # pass — оператор, який нічого не робить. Зазвичай тут відбувається + # відновлення після помилки. +except (TypeError, NameError): + pass # Винятки можна обробляти групами, якщо потрібно. +else: # Необов'язковий вираз. Має слідувати за останнім блоком except + print("Все добре!") # Виконається лише якщо не було ніяких винятків +finally: # Виконується у будь-якому випадку + print "Тут ми можемо звільнити ресурси" + +# Замість try/finally для звільнення ресурсів +# ви можете використовувати вираз with +with open("myfile.txt") as f: + for line in f: + print line + + +#################################################### +## 4. Функції +#################################################### + +# Використовуйте def для створення нових функцій +def add(x, y): + print "x дорівнює {0}, а y дорівнює {1}".format(x, y) + return x + y # Повертайте результат за допомогою ключового слова return + + +# Виклик функції з аргументами +add(5, 6) # => друкує «x дорівнює 5, а y дорівнює 6» і повертає 11 + +# Інший спосіб виклику функції — виклик з іменованими аргументами +add(y=6, x=5) # Іменовані аргументи можна вказувати у будь-якому порядку + + +# Ви можете визначити функцію, яка приймає змінну кількість аргументів, +# які будуть інтерпретовані як кортеж, за допомогою * +def varargs(*args): + return args + + +varargs(1, 2, 3) # => (1,2,3) + + +# А також можете визначити функцію, яка приймає змінне число +# іменованих аргументів, котрі будуть інтерпретовані як словник, за допомогою ** +def keyword_args(**kwargs): + return kwargs + + +# Давайте подивимось що з цього вийде +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + +# Якщо хочете, можете використовувати обидва способи одночасно +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) + + +""" +all_the_args(1, 2, a=3, b=4) друкує: + (1, 2) + {"a": 3, "b": 4} +""" + +# Коли викликаєте функції, то можете зробити навпаки! +# Використовуйте символ * аби розпакувати позиційні аргументи і +# ** для іменованих аргументів +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # еквівалентно foo(1, 2, 3, 4) +all_the_args(**kwargs) # еквівалентно foo(a=3, b=4) +all_the_args(*args, **kwargs) # еквівалентно foo(1, 2, 3, 4, a=3, b=4) + +# ви можете передавати довільне число позиційних або іменованих аргументів +# іншим функціям, які їх приймають, розпаковуючи за допомогою +# * або ** відповідно +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + + +# Область визначення функцій +x = 5 + + +def set_x(num): + # Локальна змінна x - не те ж саме, що глобальна змінна x + x = num # => 43 + print x # => 43 + + +def set_global_x(num): + global x + print x # => 5 + x = num # глобальна змінна x тепер дорівнює 6 + print x # => 6 + + +set_x(43) +set_global_x(6) + +# В Python функції є об'єктами першого класу +def create_adder(x): + def adder(y): + return x + y + + return adder + + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Також є і анонімні функції +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Присутні вбудовані функції вищого порядку +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Для зручного відображення і фільтрації можна використовувати +# включення у вигляді списків +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# Ви також можете скористатися включеннями множин та словників +{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'} +{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Класи +#################################################### + +# Аби отримати клас, ми наслідуємо object. +class Human(object): + # Атрибут класу. Він розділяється всіма екземплярами цього класу. + species = "H. sapiens" + + # Звичайний конструктор, буде викликаний при ініціалізації екземпляру класу + # Зверніть увагу, що подвійне підкреслення на початку та наприкінці імені + # використовується для позначення об'єктів та атрибутів, + # які використовуються Python, але знаходяться у просторах імен, + # якими керує користувач. Не варто вигадувати для них імена самостійно. + def __init__(self, name): + # Присвоєння значення аргумента атрибуту класу name + self.name = name + + # Ініціалізуємо властивість + self.age = 0 + + # Метод екземпляру. Всі методи приймають self у якості першого аргументу + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Методи класу розділяються між усіма екземплярами + # Вони викликаються з вказанням викликаючого класу + # у якості першого аргументу + @classmethod + def get_species(cls): + return cls.species + + # Статичний метод викликається без посилання на клас або екземпляр + @staticmethod + def grunt(): + return "*grunt*" + + # Властивість. + # Перетворює метод age() в атрибут тільки для читання + # з таким же ім'ям. + @property + def age(self): + return self._age + + # Це дозволяє змінювати значення властивості + @age.setter + def age(self, age): + self._age = age + + # Це дозволяє видаляти властивість + @age.deleter + def age(self): + del self._age + + +# Створюємо екземпляр класу +i = Human(name="Данило") +print(i.say("привіт")) # Друкує: «Данило: привіт» + +j = Human("Меланка") +print(j.say("Привіт")) # Друкує: «Меланка: привіт» + +# Виклик методу класу +i.get_species() # => "H. sapiens" + +# Зміна розділюваного атрибуту +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Виклик статичного методу +Human.grunt() # => "*grunt*" + +# Оновлюємо властивість +i.age = 42 + +# Отримуємо значення +i.age # => 42 + +# Видаляємо властивість +del i.age +i.age # => виникає помилка атрибуту + +#################################################### +## 6. Модулі +#################################################### + +# Ви можете імпортувати модулі +import math + +print(math.sqrt(16)) # => 4.0 + +# Ви можете імпортувати окремі функції з модуля +from math import ceil, floor + +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Можете імпортувати всі функції модуля. +# Попередження: краще так не робіть +from math import * + +# Можете скорочувати імена модулів +import math as m + +math.sqrt(16) == m.sqrt(16) # => True +# Ви також можете переконатися, що функції еквівалентні +from math import sqrt + +math.sqrt == m.sqrt == sqrt # => True + +# Модулі в Python — це звичайні Python-файли. Ви +# можете писати свої модулі та імпортувати їх. Назва +# модуля співпадає з назвою файлу. + +# Ви можете дізнатися, які функції та атрибути визначені +# в модулі +import math + +dir(math) + + +# Якщо у вас є Python скрипт з назвою math.py у тій же папці, що +# і ваш поточний скрипт, то файл math.py +# може бути завантажено замість вбудованого у Python модуля. +# Так трапляється, оскільки локальна папка має перевагу +# над вбудованими у Python бібліотеками. + +#################################################### +## 7. Додатково +#################################################### + +# Генератори +# Генератор "генерує" значення тоді, коли вони запитуються, замість того, +# щоб зберігати все одразу + +# Метод нижче (*НЕ* генератор) подвоює всі значення і зберігає їх +# в `double_arr`. При великих розмірах може знадобитися багато ресурсів! +def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + return double_arr + + +# Тут ми спочатку подвоюємо всі значення, потім повертаємо їх, +# аби перевірити умову +for value in double_numbers(range(1000000)): # `test_non_generator` + print value + if value > 5: + break + + +# Натомість ми можемо скористатися генератором, аби "згенерувати" +# подвійне значення, як тільки воно буде запитане +def double_numbers_generator(iterable): + for i in iterable: + yield i + i + + +# Той самий код, але вже з генератором, тепер дозволяє нам пройтися по +# значенням і подвоювати їх одне за одним якраз тоді, коли вони обробляються +# за нашою логікою, одне за одним. А як тільки ми бачимо, що value > 5, ми +# виходимо з циклу і більше не подвоюємо більшість значень, +# які отримали на вхід (НАБАГАТО ШВИДШЕ!) +for value in double_numbers_generator(xrange(1000000)): # `test_generator` + print value + if value > 5: + break + +# Між іншим: ви помітили використання `range` у `test_non_generator` і +# `xrange` у `test_generator`? +# Як `double_numbers_generator` є версією-генератором `double_numbers`, так +# і `xrange` є аналогом `range`, але у вигляді генератора. +# `range` поверне нам масив з 1000000 значень +# `xrange`, у свою чергу, згенерує 1000000 значень для нас тоді, +# коли ми їх запитуємо / будемо проходитись по ним. + +# Аналогічно включенням у вигляді списків, ви можете створювати включення +# у вигляді генераторів. +values = (-x for x in [1, 2, 3, 4, 5]) +for x in values: + print(x) # друкує -1 -2 -3 -4 -5 + +# Включення у вигляді генератора можна явно перетворити у список +values = (-x for x in [1, 2, 3, 4, 5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + +# Декоратори +# Декоратор – це функція вищого порядку, яка приймає та повертає функцію. +# Простий приклад використання – декоратор add_apples додає елемент 'Apple' в +# список fruits, який повертає цільова функція get_fruits. +def add_apples(func): + def get_fruits(): + fruits = func() + fruits.append('Apple') + return fruits + return get_fruits + +@add_apples +def get_fruits(): + return ['Banana', 'Mango', 'Orange'] + +# Друкуємо список разом з елементом 'Apple', який знаходиться в ньому: +# Banana, Mango, Orange, Apple +print ', '.join(get_fruits()) + +# У цьому прикладі beg обертає say +# Beg викличе say. Якщо say_please дорівнюватиме True, то повідомлення, +# що повертається, буде змінено. +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Будь ласка! Я бідний :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Ви можете купити мені пива?" + return msg, say_please + + +print say() # Ви можете купити мені пива? +print say(say_please=True) # Ви можете купити мені пива? Будь ласка! Я бідний :( +``` + +## Готові до більшого? + +### Безкоштовні онлайн-матеріали + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Официальная документация](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### Платні + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown deleted file mode 100644 index 65f125d1..00000000 --- a/zh-cn/python-cn.html.markdown +++ /dev/null @@ -1,476 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["Chenbo Li", "http://binarythink.net"] -filename: learnpython-zh.py -lang: zh-cn ---- - -Python 由 Guido Van Rossum 在90年代初创建。 它现在是最流行的语言之一 -我喜爱python是因为它有极为清晰的语法,甚至可以说,它就是可以执行的伪代码 - -很欢迎来自您的反馈,你可以在[@louiedinh](http://twitter.com/louiedinh) 和 louiedinh [at] [google's email service] 这里找到我 - -注意: 这篇文章针对的版本是Python 2.7,但大多也可使用于其他Python 2的版本 -如果是Python 3,请在网络上寻找其他教程 - -```python - -# 单行注释 -""" 多行字符串可以用 - 三个引号包裹,不过这也可以被当做 - 多行注释 -""" - -#################################################### -## 1. 原始数据类型和操作符 -#################################################### - -# 数字类型 -3 # => 3 - -# 简单的算数 -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7 - -# 整数的除法会自动取整 -5 / 2 # => 2 - -# 要做精确的除法,我们需要引入浮点数 -2.0 # 浮点数 -11.0 / 4.0 # => 2.75 精确多了 - -# 括号具有最高优先级 -(1 + 3) * 2 # => 8 - -# 布尔值也是基本的数据类型 -True -False - -# 用 not 来取非 -not True # => False -not False # => True - -# 相等 -1 == 1 # => True -2 == 1 # => False - -# 不等 -1 != 1 # => False -2 != 1 # => True - -# 更多的比较操作符 -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# 比较运算可以连起来写! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# 字符串通过 " 或 ' 括起来 -"This is a string." -'This is also a string.' - -# 字符串通过加号拼接 -"Hello " + "world!" # => "Hello world!" - -# 字符串可以被视为字符的列表 -"This is a string"[0] # => 'T' - -# % 可以用来格式化字符串 -"%s can be %s" % ("strings", "interpolated") - -# 也可以用 format 方法来格式化字符串 -# 推荐使用这个方法 -"{0} can be {1}".format("strings", "formatted") -# 也可以用变量名代替数字 -"{name} wants to eat {food}".format(name="Bob", food="lasagna") - -# None 是对象 -None # => None - -# 不要用相等 `==` 符号来和None进行比较 -# 要用 `is` -"etc" is None # => False -None is None # => True - -# 'is' 可以用来比较对象的相等性 -# 这个操作符在比较原始数据时没多少用,但是比较对象时必不可少 - -# None, 0, 和空字符串都被算作 False -# 其他的均为 True -0 == False # => True -"" == False # => True - - -#################################################### -## 2. 变量和集合 -#################################################### - -# 很方便的输出 -print "I'm Python. Nice to meet you!" - - -# 给变量赋值前不需要事先声明 -some_var = 5 # 一般建议使用小写字母和下划线组合来做为变量名 -some_var # => 5 - -# 访问未赋值的变量会抛出异常 -# 可以查看控制流程一节来了解如何异常处理 -some_other_var # 抛出 NameError - -# if 语句可以作为表达式来使用 -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# 列表用来保存序列 -li = [] -# 可以直接初始化列表 -other_li = [4, 5, 6] - -# 在列表末尾添加元素 -li.append(1) # li 现在是 [1] -li.append(2) # li 现在是 [1, 2] -li.append(4) # li 现在是 [1, 2, 4] -li.append(3) # li 现在是 [1, 2, 4, 3] -# 移除列表末尾元素 -li.pop() # => 3 li 现在是 [1, 2, 4] -# 重新加进去 -li.append(3) # li is now [1, 2, 4, 3] again. - -# 像其他语言访问数组一样访问列表 -li[0] # => 1 -# 访问最后一个元素 -li[-1] # => 3 - -# 越界会抛出异常 -li[4] # 抛出越界异常 - -# 切片语法需要用到列表的索引访问 -# 可以看做数学之中左闭右开区间 -li[1:3] # => [2, 4] -# 省略开头的元素 -li[2:] # => [4, 3] -# 省略末尾的元素 -li[:3] # => [1, 2, 4] - -# 删除特定元素 -del li[2] # li 现在是 [1, 2, 3] - -# 合并列表 -li + other_li # => [1, 2, 3, 4, 5, 6] - 并不会不改变这两个列表 - -# 通过拼接来合并列表 -li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6] - -# 用 in 来返回元素是否在列表中 -1 in li # => True - -# 返回列表长度 -len(li) # => 6 - - -# 元组类似于列表,但它是不可改变的 -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # 类型错误 - -# 对于大多数的列表操作,也适用于元组 -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# 你可以将元组解包赋给多个变量 -a, b, c = (1, 2, 3) # a 是 1,b 是 2,c 是 3 -# 如果不加括号,将会被自动视为元组 -d, e, f = 4, 5, 6 -# 现在我们可以看看交换两个数字是多么容易的事 -e, d = d, e # d 是 5,e 是 4 - - -# 字典用来储存映射关系 -empty_dict = {} -# 字典初始化 -filled_dict = {"one": 1, "two": 2, "three": 3} - -# 字典也用中括号访问元素 -filled_dict["one"] # => 1 - -# 把所有的键保存在列表中 -filled_dict.keys() # => ["three", "two", "one"] -# 键的顺序并不是唯一的,得到的不一定是这个顺序 - -# 把所有的值保存在列表中 -filled_dict.values() # => [3, 2, 1] -# 和键的顺序相同 - -# 判断一个键是否存在 -"one" in filled_dict # => True -1 in filled_dict # => False - -# 查询一个不存在的键会抛出 KeyError -filled_dict["four"] # KeyError - -# 用 get 方法来避免 KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# get 方法支持在不存在的时候返回一个默认值 -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# setdefault 是一个更安全的添加字典元素的方法 -filled_dict.setdefault("five", 5) # filled_dict["five"] 的值为 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] 的值仍然是 5 - - -# 集合储存无顺序的元素 -empty_set = set() -# 初始化一个集合 -some_set = set([1, 2, 2, 3, 4]) # some_set 现在是 set([1, 2, 3, 4]) - -# Python 2.7 之后,大括号可以用来表示集合 -filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} - -# 向集合添加元素 -filled_set.add(5) # filled_set 现在是 {1, 2, 3, 4, 5} - -# 用 & 来计算集合的交 -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# 用 | 来计算集合的并 -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# 用 - 来计算集合的差 -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# 用 in 来判断元素是否存在于集合中 -2 in filled_set # => True -10 in filled_set # => False - - -#################################################### -## 3. 控制流程 -#################################################### - -# 新建一个变量 -some_var = 5 - -# 这是个 if 语句,在 python 中缩进是很重要的。 -# 下面的代码片段将会输出 "some var is smaller than 10" -if some_var > 10: - print "some_var is totally bigger than 10." -elif some_var < 10: # 这个 elif 语句是不必须的 - print "some_var is smaller than 10." -else: # 这个 else 也不是必须的 - print "some_var is indeed 10." - - -""" -用for循环遍历列表 -输出: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # 你可以用 % 来格式化字符串 - print "%s is a mammal" % animal - -""" -`range(number)` 返回从0到给定数字的列表 -输出: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -while 循环 -输出: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # x = x + 1 的简写 - -# 用 try/except 块来处理异常 - -# Python 2.6 及以上适用: -try: - # 用 raise 来抛出异常 - raise IndexError("This is an index error") -except IndexError as e: - pass # pass 就是什么都不做,不过通常这里会做一些恢复工作 - - -#################################################### -## 4. 函数 -#################################################### - -# 用 def 来新建函数 -def add(x, y): - print "x is %s and y is %s" % (x, y) - return x + y # 通过 return 来返回值 - -# 调用带参数的函数 -add(5, 6) # => 输出 "x is 5 and y is 6" 返回 11 - -# 通过关键字赋值来调用函数 -add(y=6, x=5) # 顺序是无所谓的 - -# 我们也可以定义接受多个变量的函数,这些变量是按照顺序排列的 -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1,2,3) - - -# 我们也可以定义接受多个变量的函数,这些变量是按照关键字排列的 -def keyword_args(**kwargs): - return kwargs - -# 实际效果: -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - -# 你也可以同时将一个函数定义成两种形式 -def all_the_args(*args, **kwargs): - print args - print kwargs -""" -all_the_args(1, 2, a=3, b=4) prints: - (1, 2) - {"a": 3, "b": 4} -""" - -# 当调用函数的时候,我们也可以进行相反的操作,把元组和字典展开为参数 -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # 等价于 foo(1, 2, 3, 4) -all_the_args(**kwargs) # 等价于 foo(a=3, b=4) -all_the_args(*args, **kwargs) # 等价于 foo(1, 2, 3, 4, a=3, b=4) - -# 函数在 python 中是一等公民 -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# 匿名函数 -(lambda x: x > 2)(3) # => True - -# 内置高阶函数 -map(add_10, [1, 2, 3]) # => [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# 可以用列表方法来对高阶函数进行更巧妙的引用 -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -#################################################### -## 5. 类 -#################################################### - -# 我们新建的类是从 object 类中继承的 -class Human(object): - - # 类属性,由所有类的对象共享 - species = "H. sapiens" - - # 基本构造函数 - def __init__(self, name): - # 将参数赋给对象成员属性 - self.name = name - - # 成员方法,参数要有 self - def say(self, msg): - return "%s: %s" % (self.name, msg) - - # 类方法由所有类的对象共享 - # 这类方法在调用时,会把类本身传给第一个参数 - @classmethod - def get_species(cls): - return cls.species - - # 静态方法是不需要类和对象的引用就可以调用的方法 - @staticmethod - def grunt(): - return "*grunt*" - - -# 实例化一个类 -i = Human(name="Ian") -print i.say("hi") # 输出 "Ian: hi" - -j = Human("Joel") -print j.say("hello") # 输出 "Joel: hello" - -# 访问类的方法 -i.get_species() # => "H. sapiens" - -# 改变共享属性 -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# 访问静态变量 -Human.grunt() # => "*grunt*" - - -#################################################### -## 6. 模块 -#################################################### - -# 我们可以导入其他模块 -import math -print math.sqrt(16) # => 4.0 - -# 我们也可以从一个模块中导入特定的函数 -from math import ceil, floor -print ceil(3.7) # => 4.0 -print floor(3.7) # => 3.0 - -# 从模块中导入所有的函数 -# 警告:不推荐使用 -from math import * - -# 简写模块名 -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Python的模块其实只是普通的python文件 -# 你也可以创建自己的模块,并且导入它们 -# 模块的名字就和文件的名字相同 - -# 也可以通过下面的方法查看模块中有什么属性和方法 -import math -dir(math) - - -``` - -## 更多阅读 - -希望学到更多?试试下面的链接: - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2.6/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) diff --git a/zh-cn/pythonlegacy-cn.html.markdown b/zh-cn/pythonlegacy-cn.html.markdown new file mode 100644 index 00000000..65f125d1 --- /dev/null +++ b/zh-cn/pythonlegacy-cn.html.markdown @@ -0,0 +1,476 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["Chenbo Li", "http://binarythink.net"] +filename: learnpython-zh.py +lang: zh-cn +--- + +Python 由 Guido Van Rossum 在90年代初创建。 它现在是最流行的语言之一 +我喜爱python是因为它有极为清晰的语法,甚至可以说,它就是可以执行的伪代码 + +很欢迎来自您的反馈,你可以在[@louiedinh](http://twitter.com/louiedinh) 和 louiedinh [at] [google's email service] 这里找到我 + +注意: 这篇文章针对的版本是Python 2.7,但大多也可使用于其他Python 2的版本 +如果是Python 3,请在网络上寻找其他教程 + +```python + +# 单行注释 +""" 多行字符串可以用 + 三个引号包裹,不过这也可以被当做 + 多行注释 +""" + +#################################################### +## 1. 原始数据类型和操作符 +#################################################### + +# 数字类型 +3 # => 3 + +# 简单的算数 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# 整数的除法会自动取整 +5 / 2 # => 2 + +# 要做精确的除法,我们需要引入浮点数 +2.0 # 浮点数 +11.0 / 4.0 # => 2.75 精确多了 + +# 括号具有最高优先级 +(1 + 3) * 2 # => 8 + +# 布尔值也是基本的数据类型 +True +False + +# 用 not 来取非 +not True # => False +not False # => True + +# 相等 +1 == 1 # => True +2 == 1 # => False + +# 不等 +1 != 1 # => False +2 != 1 # => True + +# 更多的比较操作符 +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# 比较运算可以连起来写! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# 字符串通过 " 或 ' 括起来 +"This is a string." +'This is also a string.' + +# 字符串通过加号拼接 +"Hello " + "world!" # => "Hello world!" + +# 字符串可以被视为字符的列表 +"This is a string"[0] # => 'T' + +# % 可以用来格式化字符串 +"%s can be %s" % ("strings", "interpolated") + +# 也可以用 format 方法来格式化字符串 +# 推荐使用这个方法 +"{0} can be {1}".format("strings", "formatted") +# 也可以用变量名代替数字 +"{name} wants to eat {food}".format(name="Bob", food="lasagna") + +# None 是对象 +None # => None + +# 不要用相等 `==` 符号来和None进行比较 +# 要用 `is` +"etc" is None # => False +None is None # => True + +# 'is' 可以用来比较对象的相等性 +# 这个操作符在比较原始数据时没多少用,但是比较对象时必不可少 + +# None, 0, 和空字符串都被算作 False +# 其他的均为 True +0 == False # => True +"" == False # => True + + +#################################################### +## 2. 变量和集合 +#################################################### + +# 很方便的输出 +print "I'm Python. Nice to meet you!" + + +# 给变量赋值前不需要事先声明 +some_var = 5 # 一般建议使用小写字母和下划线组合来做为变量名 +some_var # => 5 + +# 访问未赋值的变量会抛出异常 +# 可以查看控制流程一节来了解如何异常处理 +some_other_var # 抛出 NameError + +# if 语句可以作为表达式来使用 +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# 列表用来保存序列 +li = [] +# 可以直接初始化列表 +other_li = [4, 5, 6] + +# 在列表末尾添加元素 +li.append(1) # li 现在是 [1] +li.append(2) # li 现在是 [1, 2] +li.append(4) # li 现在是 [1, 2, 4] +li.append(3) # li 现在是 [1, 2, 4, 3] +# 移除列表末尾元素 +li.pop() # => 3 li 现在是 [1, 2, 4] +# 重新加进去 +li.append(3) # li is now [1, 2, 4, 3] again. + +# 像其他语言访问数组一样访问列表 +li[0] # => 1 +# 访问最后一个元素 +li[-1] # => 3 + +# 越界会抛出异常 +li[4] # 抛出越界异常 + +# 切片语法需要用到列表的索引访问 +# 可以看做数学之中左闭右开区间 +li[1:3] # => [2, 4] +# 省略开头的元素 +li[2:] # => [4, 3] +# 省略末尾的元素 +li[:3] # => [1, 2, 4] + +# 删除特定元素 +del li[2] # li 现在是 [1, 2, 3] + +# 合并列表 +li + other_li # => [1, 2, 3, 4, 5, 6] - 并不会不改变这两个列表 + +# 通过拼接来合并列表 +li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6] + +# 用 in 来返回元素是否在列表中 +1 in li # => True + +# 返回列表长度 +len(li) # => 6 + + +# 元组类似于列表,但它是不可改变的 +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # 类型错误 + +# 对于大多数的列表操作,也适用于元组 +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# 你可以将元组解包赋给多个变量 +a, b, c = (1, 2, 3) # a 是 1,b 是 2,c 是 3 +# 如果不加括号,将会被自动视为元组 +d, e, f = 4, 5, 6 +# 现在我们可以看看交换两个数字是多么容易的事 +e, d = d, e # d 是 5,e 是 4 + + +# 字典用来储存映射关系 +empty_dict = {} +# 字典初始化 +filled_dict = {"one": 1, "two": 2, "three": 3} + +# 字典也用中括号访问元素 +filled_dict["one"] # => 1 + +# 把所有的键保存在列表中 +filled_dict.keys() # => ["three", "two", "one"] +# 键的顺序并不是唯一的,得到的不一定是这个顺序 + +# 把所有的值保存在列表中 +filled_dict.values() # => [3, 2, 1] +# 和键的顺序相同 + +# 判断一个键是否存在 +"one" in filled_dict # => True +1 in filled_dict # => False + +# 查询一个不存在的键会抛出 KeyError +filled_dict["four"] # KeyError + +# 用 get 方法来避免 KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# get 方法支持在不存在的时候返回一个默认值 +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# setdefault 是一个更安全的添加字典元素的方法 +filled_dict.setdefault("five", 5) # filled_dict["five"] 的值为 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] 的值仍然是 5 + + +# 集合储存无顺序的元素 +empty_set = set() +# 初始化一个集合 +some_set = set([1, 2, 2, 3, 4]) # some_set 现在是 set([1, 2, 3, 4]) + +# Python 2.7 之后,大括号可以用来表示集合 +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# 向集合添加元素 +filled_set.add(5) # filled_set 现在是 {1, 2, 3, 4, 5} + +# 用 & 来计算集合的交 +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# 用 | 来计算集合的并 +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# 用 - 来计算集合的差 +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# 用 in 来判断元素是否存在于集合中 +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. 控制流程 +#################################################### + +# 新建一个变量 +some_var = 5 + +# 这是个 if 语句,在 python 中缩进是很重要的。 +# 下面的代码片段将会输出 "some var is smaller than 10" +if some_var > 10: + print "some_var is totally bigger than 10." +elif some_var < 10: # 这个 elif 语句是不必须的 + print "some_var is smaller than 10." +else: # 这个 else 也不是必须的 + print "some_var is indeed 10." + + +""" +用for循环遍历列表 +输出: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # 你可以用 % 来格式化字符串 + print "%s is a mammal" % animal + +""" +`range(number)` 返回从0到给定数字的列表 +输出: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +while 循环 +输出: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # x = x + 1 的简写 + +# 用 try/except 块来处理异常 + +# Python 2.6 及以上适用: +try: + # 用 raise 来抛出异常 + raise IndexError("This is an index error") +except IndexError as e: + pass # pass 就是什么都不做,不过通常这里会做一些恢复工作 + + +#################################################### +## 4. 函数 +#################################################### + +# 用 def 来新建函数 +def add(x, y): + print "x is %s and y is %s" % (x, y) + return x + y # 通过 return 来返回值 + +# 调用带参数的函数 +add(5, 6) # => 输出 "x is 5 and y is 6" 返回 11 + +# 通过关键字赋值来调用函数 +add(y=6, x=5) # 顺序是无所谓的 + +# 我们也可以定义接受多个变量的函数,这些变量是按照顺序排列的 +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1,2,3) + + +# 我们也可以定义接受多个变量的函数,这些变量是按照关键字排列的 +def keyword_args(**kwargs): + return kwargs + +# 实际效果: +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + +# 你也可以同时将一个函数定义成两种形式 +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# 当调用函数的时候,我们也可以进行相反的操作,把元组和字典展开为参数 +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # 等价于 foo(1, 2, 3, 4) +all_the_args(**kwargs) # 等价于 foo(a=3, b=4) +all_the_args(*args, **kwargs) # 等价于 foo(1, 2, 3, 4, a=3, b=4) + +# 函数在 python 中是一等公民 +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# 匿名函数 +(lambda x: x > 2)(3) # => True + +# 内置高阶函数 +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# 可以用列表方法来对高阶函数进行更巧妙的引用 +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. 类 +#################################################### + +# 我们新建的类是从 object 类中继承的 +class Human(object): + + # 类属性,由所有类的对象共享 + species = "H. sapiens" + + # 基本构造函数 + def __init__(self, name): + # 将参数赋给对象成员属性 + self.name = name + + # 成员方法,参数要有 self + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # 类方法由所有类的对象共享 + # 这类方法在调用时,会把类本身传给第一个参数 + @classmethod + def get_species(cls): + return cls.species + + # 静态方法是不需要类和对象的引用就可以调用的方法 + @staticmethod + def grunt(): + return "*grunt*" + + +# 实例化一个类 +i = Human(name="Ian") +print i.say("hi") # 输出 "Ian: hi" + +j = Human("Joel") +print j.say("hello") # 输出 "Joel: hello" + +# 访问类的方法 +i.get_species() # => "H. sapiens" + +# 改变共享属性 +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# 访问静态变量 +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. 模块 +#################################################### + +# 我们可以导入其他模块 +import math +print math.sqrt(16) # => 4.0 + +# 我们也可以从一个模块中导入特定的函数 +from math import ceil, floor +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 + +# 从模块中导入所有的函数 +# 警告:不推荐使用 +from math import * + +# 简写模块名 +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python的模块其实只是普通的python文件 +# 你也可以创建自己的模块,并且导入它们 +# 模块的名字就和文件的名字相同 + +# 也可以通过下面的方法查看模块中有什么属性和方法 +import math +dir(math) + + +``` + +## 更多阅读 + +希望学到更多?试试下面的链接: + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown deleted file mode 100644 index cd7481d7..00000000 --- a/zh-tw/python-tw.html.markdown +++ /dev/null @@ -1,727 +0,0 @@ ---- -language: python -contributors: - - ["Louie Dinh", "http://ldinh.ca"] - - ["Amin Bandali", "http://aminbandali.com"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["evuez", "http://github.com/evuez"] -translators: - - ["Michael Yeh", "https://hinet60613.github.io/"] -filename: learnpython-tw.py -lang: zh-tw ---- - -Python是在1990年代早期由Guido Van Rossum創建的。它是現在最流行的程式語言之一。我愛上Python是因為他極為清晰的語法,甚至可以說它就是可執行的虛擬碼。 - -非常歡迎各位給我們任何回饋! 你可以在[@louiedinh](http://twitter.com/louiedinh) 或 louiedinh [at] [google's email service]聯絡到我。 - -註: 本篇文章適用的版本為Python 2.7,但大部分的Python 2.X版本應該都適用。 Python 2.7將會在2020年停止維護,因此建議您可以從Python 3開始學Python。 -Python 3.X可以看這篇[Python 3 教學 (英文)](http://learnxinyminutes.com/docs/python3/). - -讓程式碼同時支援Python 2.7和3.X是可以做到的,只要引入 - [`__future__` imports](https://docs.python.org/2/library/__future__.html) 模組. - `__future__` 模組允許你撰寫可以在Python 2上執行的Python 3程式碼,詳細訊息請參考Python 3 教學。 - -```python - -# 單行註解從井字號開始 - -""" 多行字串可以用三個雙引號 - 包住,不過通常這種寫法會 - 被拿來當作多行註解 -""" - -#################################################### -## 1. 原始型別與運算元 -#################################################### - -# 你可以使用數字 -3 # => 3 - -# 還有四則運算 -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7 - -# 除法比較麻煩,除以整數時會自動捨去小數位。 -5 / 2 # => 2 - -# 要做精確的除法,我們需要浮點數 -2.0 # 浮點數 -11.0 / 4.0 # => 2.75 精確多了! - -# 整數除法的無條件捨去對正數或負數都適用 -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # 浮點數的整數也適用 --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# 我們可以用除法模組(參考第六節:模組),讓 -# 單一斜線代表普通除法,而非無條件捨去 -from __future__ import division -11/4 # => 2.75 ...普通除法 -11//4 # => 2 ...無條件捨去 - -# 取餘數 -7 % 3 # => 1 - -# 指數 (x的y次方) -2**4 # => 16 - -# 用括號改變運算順序 -(1 + 3) * 2 # => 8 - -# 布林運算 -# 注意 "and" 和 "or" 要用小寫 -True and False #=> False -False or True #=> True - -# 用整數與布林值做運算 -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True - -# 用not取反向 -not True # => False -not False # => True - -# 等於判斷是用 == -1 == 1 # => True -2 == 1 # => False - -# 不等於判斷是用 != -1 != 1 # => False -2 != 1 # => True - -# 更多比較 -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# 比較是可以串接的 -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# 字串用單引號 ' 或雙引號 " 建立 -"This is a string." -'This is also a string.' - -# 字串相加會被串接再一起 -"Hello " + "world!" # => "Hello world!" -# 不用加號也可以做字串相加 -"Hello " "world!" # => "Hello world!" - -# ... 也可以做相乘 -"Hello" * 3 # => "HelloHelloHello" - -# 字串可以被視為字元的陣列 -"This is a string"[0] # => 'T' - -# 字串的格式化可以用百分之符號 % -# 儘管在Python 3.1後這個功能被廢棄了,並且在 -# 之後的版本會被移除,但還是可以了解一下 -x = 'apple' -y = 'lemon' -z = "The items in the basket are %s and %s" % (x,y) - -# 新的格式化方式是使用format函式 -# 這個方式也是較為推薦的 -"{} is a {}".format("This", "placeholder") -"{0} can be {1}".format("strings", "formatted") -# 你也可以用關鍵字,如果你不想數你是要用第幾個變數的話 -"{name} wants to eat {food}".format(name="Bob", food="lasagna") - -# 無(None) 是一個物件 -None # => None - -# 不要用等於符號 "==" 對 無(None)做比較 -# 用 "is" -"etc" is None # => False -None is None # => True - -# 'is' 運算元是用來識別物件的。對原始型別來說或許沒什麼用, -# 但對物件來說是很有用的。 - -# 任何物件都可以被當作布林值使用 -# 以下的值會被視為是False : -# - 無(None) -# - 任何型別的零 (例如: 0, 0L, 0.0, 0j) -# - 空序列 (例如: '', (), []) -# - 空容器 (例如: {}, set()) -# - 自定義型別的實體,且滿足某些條件 -# 請參考文件: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ -# -# 其餘的值都會被視為True (用bool()函式讓他們回傳布林值). -bool(0) # => False -bool("") # => False - - -#################################################### -## 2. 變數與集合 -#################################################### - -# Python的輸出很方便 -print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! - -# 從命令列獲得值也很方便 -input_string_var = raw_input("Enter some data: ") # 資料會被視為字串存進變數 -input_var = input("Enter some data: ") # 輸入的資料會被當作Python程式碼執行 -# 注意: 請謹慎使用input()函式 -# 註: 在Python 3中,input()已被棄用,raw_input()已被更名為input() - -# 使用變數前不需要先宣告 -some_var = 5 # 方便好用 -lower_case_with_underscores -some_var # => 5 - -# 對沒有被賦值的變數取值會造成例外 -# 請參考錯誤流程部分做例外處理 -some_other_var # 造成 NameError - -# if可以當判斷式使用 -# 相當於C語言中的二元判斷式 -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# 串列型態可以儲存集合 -li = [] -# 你可以預先填好串列內容 -other_li = [4, 5, 6] - -# 用append()在串列後新增東西 -li.append(1) # 此時 li 內容為 [1] -li.append(2) # 此時 li 內容為 [1, 2] -li.append(4) # 此時 li 內容為 [1, 2, 4] -li.append(3) # 此時 li 內容為 [1, 2, 4, 3] -# 用pop()移除串列尾端的元素 -li.pop() # => 3 ,此時 li 內容為 [1, 2, 4] -# 然後再塞回去 -li.append(3) # 此時 li 內容再次為 [1, 2, 4, 3] - -# 你可以像存取陣列一樣的存取串列 -li[0] # => 1 -# 用等號 = 給串列中特定索引的元素賦值 -li[0] = 42 -li[0] # => 42 -li[0] = 1 # 註: 將其設定回原本的值 -# 用 -1 索引值查看串列最後一個元素 -li[-1] # => 3 - -# 存取超過範圍會產生IndexError -li[4] # Raises an IndexError - -# 你可以用切片語法來存取特定範圍的值 -# (相當於數學中的左閉右開區間,即包含最左邊界,但不包含右邊界) -li[1:3] # => [2, 4] -# 略過開頭元素 -li[2:] # => [4, 3] -# 略過結尾元素 -li[:3] # => [1, 2, 4] -# 每隔兩個元素取值 -li[::2] # =>[1, 4] -# 串列反轉 -li[::-1] # => [3, 4, 2, 1] -# 你可以任意組合來達到你想要的效果 -# li[開始索引:結束索引:間隔] - -# 用 "del" 從串列中移除任意元素 -del li[2] # 現在 li 內容為 [1, 2, 3] - -# 你可以做串列相加 -li + other_li # => [1, 2, 3, 4, 5, 6] -# 註: li 及 other_li 沒有被更動 - -# 用 "extend()" 做串列串接 -li.extend(other_li) # 現在 li 內容為 [1, 2, 3, 4, 5, 6] - -# 移除特定值的第一次出現 -li.remove(2) # 現在 li 內容為 [1, 3, 4, 5, 6] -li.remove(2) # 2 不在串列中,造成 ValueError - -# 在特定位置插入值 -li.insert(1, 2) # 現在 li 內容再次回復為 [1, 2, 3, 4, 5, 6] - -# 取得特定值在串列中第一次出現的位置 -li.index(2) # => 1 -li.index(7) # 7 不在串列中,造成 ValueError - -# 用 "in" 檢查特定值是否出現在串列中 -1 in li # => True - -# 用 "len()" 取得串列長度 -len(li) # => 6 - - -# 元組(Tuple,以下仍用原文)類似於串列,但是它是不可改變的 -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # 產生TypeError - -# 能對串列做的東西都可以對tuple做 -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# 你可以把tuple拆開並分別將值存入不同變數 -a, b, c = (1, 2, 3) # a 現在是 1, b 現在是 2, c 現在是 3 -d, e, f = 4, 5, 6 # 也可以不寫括號 -# 如果不加括號,預設會產生tuple -g = 4, 5, 6 # => (4, 5, 6) -# 你看,交換兩個值很簡單吧 -e, d = d, e # 此時 d 的值為 5 且 e 的值為 4 - - -# 字典(Dictionary)用來儲存映射關係 -empty_dict = {} -# 你可以對字典做初始化 -filled_dict = {"one": 1, "two": 2, "three": 3} - -# 用 [] 取值 -filled_dict["one"] # => 1 - -# 用 "keys()" 將所有的Key輸出到一個List中 -filled_dict.keys() # => ["three", "two", "one"] -# 註: 字典裡key的排序是不固定的 -# 你的執行結果可能與上面不同 -# 譯註: 只能保證所有的key都有出現,但不保證順序 - -# 用 "values()" 將所有的Value輸出到一個List中 -filled_dict.values() # => [3, 2, 1] -# 註: 同上,不保證順序 - -# 用 "in" 來檢查指定的Key是否在字典中 -"one" in filled_dict # => True -1 in filled_dict # => False - -# 查詢不存在的Key會造成KeyError -filled_dict["four"] # KeyError - -# 用 "get()" 來避免KeyError -# 若指定的Key不存在的話會得到None -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# "get()" 函式支援預設值,當找不到指定的值時,會回傳指定的預設值 -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 -# 注意此時 filled_dict.get("four") 仍然為 None -# (get()此時並沒有產生出任何的值) - -# 像操作list一樣,對指定的Key賦值 -filled_dict["four"] = 4 # 此時 filled_dict["four"] => 4 - -# "setdefault()" 只在指定的Key不存在時才會將值插入dictionary -filled_dict.setdefault("five", 5) # filled_dict["five"] 被指定為 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] 仍保持 5 - - -# 集合(Set)被用來儲存...集合。 -# 跟串列(List)有點像,但集合內不會有重複的元素 -empty_set = set() -# 初始化 "set()" 並給定一些值 -some_set = set([1, 2, 2, 3, 4]) # 現在 some_set 為 set([1, 2, 3, 4]),注意重複的元素只有一個會被存入 - -# 一樣,不保證順序,就算真的有照順序排也只是你運氣好 -another_set = set([4, 3, 2, 2, 1]) # another_set 現在為 set([1, 2, 3, 4]) - -# 從 Python 2.7 開始,可以使用大括號 {} 來宣告Set -filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} - -# 加入更多元素進入Set -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} - -# 用 & 來對兩個集合取交集 -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# 用 | 來對兩個集合取聯集 -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# 用 - 來將第二個集合內有的元素移出第一個集合 -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# 用 ^ 來對兩個集合取差集 -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# 檢查左邊是否為右邊的母集 -{1, 2} >= {1, 2, 3} # => False - -# 檢查左邊是否為右邊的子集 -{1, 2} <= {1, 2, 3} # => True - -# 用 in 來檢查某元素是否存在於集合內 -2 in filled_set # => True -10 in filled_set # => False - - -#################################################### -## 3. 控制流程 -#################################################### - -# 首先,先宣告一個變數 -some_var = 5 - -# 這邊是 if 判斷式。注意,縮排對Python是很重要的。 -# 下面應該會印出 "some_var is smaller than 10" -if some_var > 10: - print "some_var is totally bigger than 10." -elif some_var < 10: # elif 可有可無 - print "some_var is smaller than 10." -else: # else 也可有可無 - print "some_var is indeed 10." - - -""" -For 迴圈會遞迴整的List -下面的程式碼會輸出: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # 你可以用{0}來組合0出格式化字串 (見上面.) - print "{0} is a mammal".format(animal) - -""" -"range(number)" 回傳一個包含從0到給定值的數字List, -下面的程式碼會輸出: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print i - -""" -"range(lower, upper)" 回傳一個包含從給定的下限 -到給定的上限的數字List -下面的程式碼會輸出: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print i - -""" -While迴圈會執行到條件不成立為止 -下面的程式碼會輸出: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print x - x += 1 # x = x + 1 的簡寫 - -# 用try/except處理例外 - -# 適用Python 2.6及以上版本 -try: - # 用 "raise" 來發起例外 - raise IndexError("This is an index error") -except IndexError as e: - pass # 毫無反應,就只是個什麼都沒做的pass。通常這邊會讓你做對例外的處理 -except (TypeError, NameError): - pass # 有需要的話,多種例外可以一起處理 -else: # else 可有可無,但必須寫在所有的except後 - print "All good!" # 只有在try的時候沒有產生任何except才會被執行 -finally: # 不管什麼情況下一定會被執行 - print "We can clean up resources here" - -# 除了try/finally以外,你可以用 with 來簡單的處理清理動作 -with open("myfile.txt") as f: - for line in f: - print line - -#################################################### -## 4. 函式 -#################################################### - -# 用 "def" 來建立新函式 -def add(x, y): - print "x is {0} and y is {1}".format(x, y) - return x + y # 用 "return" 來回傳值 - -# 用參數來呼叫函式 -add(5, 6) # => 輸出 "x is 5 and y is 6" 並回傳 11 - -# 你也可以寫上參數名稱來呼叫函式 -add(y=6, x=5) # 這種狀況下,兩個參數的順序並不影響執行 - - -# 你可以定義接受多個變數的函式,用*來表示參數tuple -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - - -# 你可以定義接受多個變數的函式,用**來表示參數dictionary -def keyword_args(**kwargs): - return kwargs - -# 呼叫看看會發生什麼事吧 -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# 如果你想要,你也可以兩個同時用 -def all_the_args(*args, **kwargs): - print args - print kwargs -""" -all_the_args(1, 2, a=3, b=4) prints: - (1, 2) - {"a": 3, "b": 4} -""" - -# 呼叫函式時,你可以做反向的操作 -# 用 * 將變數展開為順序排序的變數 -# 用 ** 將變數展開為Keyword排序的變數 -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # 等同於 foo(1, 2, 3, 4) -all_the_args(**kwargs) # 等同於 foo(a=3, b=4) -all_the_args(*args, **kwargs) # 等同於 foo(1, 2, 3, 4, a=3, b=4) - -# 你可以把args跟kwargs傳到下一個函式內 -# 分別用 * 跟 ** 將它展開就可以了 -def pass_all_the_args(*args, **kwargs): - all_the_args(*args, **kwargs) - print varargs(*args) - print keyword_args(**kwargs) - -# 函式範圍 -x = 5 - -def set_x(num): - # 區域變數 x 和全域變數 x 不是同一個東西 - x = num # => 43 - print x # => 43 - -def set_global_x(num): - global x - print x # => 5 - x = num # 全域變數 x 在set_global_x(6)被設定為 6 - print x # => 6 - -set_x(43) -set_global_x(6) - -# Python有一級函式 -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# 也有匿名函式 -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# 還有內建的高階函式 -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] - -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# 我們可以用List列表的方式對map和filter等高階函式做更有趣的應用 -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - - -#################################################### -## 5. 類別 -#################################################### - -# 我們可以由object繼承出一個新的類別 -class Human(object): - - # 類別的參數,被所有這個類別的實體所共用 - species = "H. sapiens" - - # 基礎建構函式,當class被實體化的時候會被呼叫 - # 注意前後的雙底線 - # 代表此物件或屬性雖然在使用者控制的命名空間內,但是被python使用 - def __init__(self, name): - # 將函式引入的參數 name 指定給實體的 name 參數 - self.name = name - - # 初始化屬性 - self.age = 0 - - - # 一個實體的方法(method)。 所有的method都以self為第一個參數 - def say(self, msg): - return "{0}: {1}".format(self.name, msg) - - # 一個類別方法會被所有的實體所共用 - # 他們會以類別為第一參數的方式被呼叫 - @classmethod - def get_species(cls): - return cls.species - - # 靜態方法 - @staticmethod - def grunt(): - return "*grunt*" - - # 屬性就像是用getter取值一樣 - # 它將方法 age() 轉為同名的、只能讀取的屬性 - @property - def age(self): - return self._age - - # 這樣寫的話可以讓屬性被寫入新的值 - @age.setter - def age(self, age): - self._age = age - - # 這樣寫的話允許屬性被刪除 - @age.deleter - def age(self): - del self._age - - -# 將類別實體化 -i = Human(name="Ian") -print i.say("hi") # prints out "Ian: hi" - -j = Human("Joel") -print j.say("hello") # prints out "Joel: hello" - -# 呼叫類別方法 -i.get_species() # => "H. sapiens" - -# 更改共用的屬性 -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# 呼叫靜態方法 -Human.grunt() # => "*grunt*" - -# 更新屬性 -i.age = 42 - -# 取得屬性 -i.age # => 42 - -# 移除屬性 -del i.age -i.age # => raises an AttributeError - - -#################################################### -## 6. 模組 -#################################################### - -# 你可以引入模組來做使用 -import math -print math.sqrt(16) # => 4.0 - # math.sqrt()為取根號 - -# 你可以只從模組取出特定幾個函式 -from math import ceil, floor -print ceil(3.7) # => 4.0 -print floor(3.7) # => 3.0 - -# 你可以將所有的函式從模組中引入 -# 注意:不建議這麼做 -from math import * - -# 你可以用 as 簡寫模組名稱 -import math as m -math.sqrt(16) == m.sqrt(16) # => True -# 你也可以測試函示是否相等 -from math import sqrt -math.sqrt == m.sqrt == sqrt # => True - -# Python的模組就只是一般的Python檔。 -# 你可以自己的模組自己寫、自己的模組自己引入 -# 模組的名稱和檔案名稱一樣 - -# 你可以用dir()來查看有哪些可用函式和屬性 -import math -dir(math) - - -#################################################### -## 7. 進階 -#################################################### - -# 產生器(Generator)可以讓你寫更懶惰的程式碼 -def double_numbers(iterable): - for i in iterable: - yield i + i - -# 產生器可以讓你即時的產生值 -# 不是全部產生完之後再一次回傳,產生器會在每一個遞迴時 -# 產生值。 這也意味著大於15的值不會在double_numbers中產生。 -# 這邊,xrange()做的事情和range()一樣 -# 建立一個 1-900000000 的List會消耗很多時間和記憶體空間 -# xrange() 建立一個產生器物件,而不是如range()建立整個List -# 我們用底線來避免可能和python的關鍵字重複的名稱 -xrange_ = xrange(1, 900000000) - -# 下面的程式碼會把所有的值乘以兩倍,直到出現大於30的值 -for i in double_numbers(xrange_): - print i - if i >= 30: - break - - -# 裝飾子 -# 在這個範例中,beg會綁在say上 -# Beg會呼叫say。 如果say_please為True的話,它會更改回傳的訊息 -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print say() # Can you buy me a beer? -print say(say_please=True) # Can you buy me a beer? Please! I am poor :( -``` - -## 準備好學更多了嗎? - -### 線上免費資源 - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/2/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) - -### 或買本書? - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/zh-tw/pythonlegacy-tw.html.markdown b/zh-tw/pythonlegacy-tw.html.markdown new file mode 100644 index 00000000..cd7481d7 --- /dev/null +++ b/zh-tw/pythonlegacy-tw.html.markdown @@ -0,0 +1,727 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "http://aminbandali.com"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] +translators: + - ["Michael Yeh", "https://hinet60613.github.io/"] +filename: learnpython-tw.py +lang: zh-tw +--- + +Python是在1990年代早期由Guido Van Rossum創建的。它是現在最流行的程式語言之一。我愛上Python是因為他極為清晰的語法,甚至可以說它就是可執行的虛擬碼。 + +非常歡迎各位給我們任何回饋! 你可以在[@louiedinh](http://twitter.com/louiedinh) 或 louiedinh [at] [google's email service]聯絡到我。 + +註: 本篇文章適用的版本為Python 2.7,但大部分的Python 2.X版本應該都適用。 Python 2.7將會在2020年停止維護,因此建議您可以從Python 3開始學Python。 +Python 3.X可以看這篇[Python 3 教學 (英文)](http://learnxinyminutes.com/docs/python3/). + +讓程式碼同時支援Python 2.7和3.X是可以做到的,只要引入 + [`__future__` imports](https://docs.python.org/2/library/__future__.html) 模組. + `__future__` 模組允許你撰寫可以在Python 2上執行的Python 3程式碼,詳細訊息請參考Python 3 教學。 + +```python + +# 單行註解從井字號開始 + +""" 多行字串可以用三個雙引號 + 包住,不過通常這種寫法會 + 被拿來當作多行註解 +""" + +#################################################### +## 1. 原始型別與運算元 +#################################################### + +# 你可以使用數字 +3 # => 3 + +# 還有四則運算 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# 除法比較麻煩,除以整數時會自動捨去小數位。 +5 / 2 # => 2 + +# 要做精確的除法,我們需要浮點數 +2.0 # 浮點數 +11.0 / 4.0 # => 2.75 精確多了! + +# 整數除法的無條件捨去對正數或負數都適用 +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # 浮點數的整數也適用 +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# 我們可以用除法模組(參考第六節:模組),讓 +# 單一斜線代表普通除法,而非無條件捨去 +from __future__ import division +11/4 # => 2.75 ...普通除法 +11//4 # => 2 ...無條件捨去 + +# 取餘數 +7 % 3 # => 1 + +# 指數 (x的y次方) +2**4 # => 16 + +# 用括號改變運算順序 +(1 + 3) * 2 # => 8 + +# 布林運算 +# 注意 "and" 和 "or" 要用小寫 +True and False #=> False +False or True #=> True + +# 用整數與布林值做運算 +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# 用not取反向 +not True # => False +not False # => True + +# 等於判斷是用 == +1 == 1 # => True +2 == 1 # => False + +# 不等於判斷是用 != +1 != 1 # => False +2 != 1 # => True + +# 更多比較 +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# 比較是可以串接的 +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# 字串用單引號 ' 或雙引號 " 建立 +"This is a string." +'This is also a string.' + +# 字串相加會被串接再一起 +"Hello " + "world!" # => "Hello world!" +# 不用加號也可以做字串相加 +"Hello " "world!" # => "Hello world!" + +# ... 也可以做相乘 +"Hello" * 3 # => "HelloHelloHello" + +# 字串可以被視為字元的陣列 +"This is a string"[0] # => 'T' + +# 字串的格式化可以用百分之符號 % +# 儘管在Python 3.1後這個功能被廢棄了,並且在 +# 之後的版本會被移除,但還是可以了解一下 +x = 'apple' +y = 'lemon' +z = "The items in the basket are %s and %s" % (x,y) + +# 新的格式化方式是使用format函式 +# 這個方式也是較為推薦的 +"{} is a {}".format("This", "placeholder") +"{0} can be {1}".format("strings", "formatted") +# 你也可以用關鍵字,如果你不想數你是要用第幾個變數的話 +"{name} wants to eat {food}".format(name="Bob", food="lasagna") + +# 無(None) 是一個物件 +None # => None + +# 不要用等於符號 "==" 對 無(None)做比較 +# 用 "is" +"etc" is None # => False +None is None # => True + +# 'is' 運算元是用來識別物件的。對原始型別來說或許沒什麼用, +# 但對物件來說是很有用的。 + +# 任何物件都可以被當作布林值使用 +# 以下的值會被視為是False : +# - 無(None) +# - 任何型別的零 (例如: 0, 0L, 0.0, 0j) +# - 空序列 (例如: '', (), []) +# - 空容器 (例如: {}, set()) +# - 自定義型別的實體,且滿足某些條件 +# 請參考文件: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# 其餘的值都會被視為True (用bool()函式讓他們回傳布林值). +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. 變數與集合 +#################################################### + +# Python的輸出很方便 +print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! + +# 從命令列獲得值也很方便 +input_string_var = raw_input("Enter some data: ") # 資料會被視為字串存進變數 +input_var = input("Enter some data: ") # 輸入的資料會被當作Python程式碼執行 +# 注意: 請謹慎使用input()函式 +# 註: 在Python 3中,input()已被棄用,raw_input()已被更名為input() + +# 使用變數前不需要先宣告 +some_var = 5 # 方便好用 +lower_case_with_underscores +some_var # => 5 + +# 對沒有被賦值的變數取值會造成例外 +# 請參考錯誤流程部分做例外處理 +some_other_var # 造成 NameError + +# if可以當判斷式使用 +# 相當於C語言中的二元判斷式 +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# 串列型態可以儲存集合 +li = [] +# 你可以預先填好串列內容 +other_li = [4, 5, 6] + +# 用append()在串列後新增東西 +li.append(1) # 此時 li 內容為 [1] +li.append(2) # 此時 li 內容為 [1, 2] +li.append(4) # 此時 li 內容為 [1, 2, 4] +li.append(3) # 此時 li 內容為 [1, 2, 4, 3] +# 用pop()移除串列尾端的元素 +li.pop() # => 3 ,此時 li 內容為 [1, 2, 4] +# 然後再塞回去 +li.append(3) # 此時 li 內容再次為 [1, 2, 4, 3] + +# 你可以像存取陣列一樣的存取串列 +li[0] # => 1 +# 用等號 = 給串列中特定索引的元素賦值 +li[0] = 42 +li[0] # => 42 +li[0] = 1 # 註: 將其設定回原本的值 +# 用 -1 索引值查看串列最後一個元素 +li[-1] # => 3 + +# 存取超過範圍會產生IndexError +li[4] # Raises an IndexError + +# 你可以用切片語法來存取特定範圍的值 +# (相當於數學中的左閉右開區間,即包含最左邊界,但不包含右邊界) +li[1:3] # => [2, 4] +# 略過開頭元素 +li[2:] # => [4, 3] +# 略過結尾元素 +li[:3] # => [1, 2, 4] +# 每隔兩個元素取值 +li[::2] # =>[1, 4] +# 串列反轉 +li[::-1] # => [3, 4, 2, 1] +# 你可以任意組合來達到你想要的效果 +# li[開始索引:結束索引:間隔] + +# 用 "del" 從串列中移除任意元素 +del li[2] # 現在 li 內容為 [1, 2, 3] + +# 你可以做串列相加 +li + other_li # => [1, 2, 3, 4, 5, 6] +# 註: li 及 other_li 沒有被更動 + +# 用 "extend()" 做串列串接 +li.extend(other_li) # 現在 li 內容為 [1, 2, 3, 4, 5, 6] + +# 移除特定值的第一次出現 +li.remove(2) # 現在 li 內容為 [1, 3, 4, 5, 6] +li.remove(2) # 2 不在串列中,造成 ValueError + +# 在特定位置插入值 +li.insert(1, 2) # 現在 li 內容再次回復為 [1, 2, 3, 4, 5, 6] + +# 取得特定值在串列中第一次出現的位置 +li.index(2) # => 1 +li.index(7) # 7 不在串列中,造成 ValueError + +# 用 "in" 檢查特定值是否出現在串列中 +1 in li # => True + +# 用 "len()" 取得串列長度 +len(li) # => 6 + + +# 元組(Tuple,以下仍用原文)類似於串列,但是它是不可改變的 +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # 產生TypeError + +# 能對串列做的東西都可以對tuple做 +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# 你可以把tuple拆開並分別將值存入不同變數 +a, b, c = (1, 2, 3) # a 現在是 1, b 現在是 2, c 現在是 3 +d, e, f = 4, 5, 6 # 也可以不寫括號 +# 如果不加括號,預設會產生tuple +g = 4, 5, 6 # => (4, 5, 6) +# 你看,交換兩個值很簡單吧 +e, d = d, e # 此時 d 的值為 5 且 e 的值為 4 + + +# 字典(Dictionary)用來儲存映射關係 +empty_dict = {} +# 你可以對字典做初始化 +filled_dict = {"one": 1, "two": 2, "three": 3} + +# 用 [] 取值 +filled_dict["one"] # => 1 + +# 用 "keys()" 將所有的Key輸出到一個List中 +filled_dict.keys() # => ["three", "two", "one"] +# 註: 字典裡key的排序是不固定的 +# 你的執行結果可能與上面不同 +# 譯註: 只能保證所有的key都有出現,但不保證順序 + +# 用 "values()" 將所有的Value輸出到一個List中 +filled_dict.values() # => [3, 2, 1] +# 註: 同上,不保證順序 + +# 用 "in" 來檢查指定的Key是否在字典中 +"one" in filled_dict # => True +1 in filled_dict # => False + +# 查詢不存在的Key會造成KeyError +filled_dict["four"] # KeyError + +# 用 "get()" 來避免KeyError +# 若指定的Key不存在的話會得到None +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# "get()" 函式支援預設值,當找不到指定的值時,會回傳指定的預設值 +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 +# 注意此時 filled_dict.get("four") 仍然為 None +# (get()此時並沒有產生出任何的值) + +# 像操作list一樣,對指定的Key賦值 +filled_dict["four"] = 4 # 此時 filled_dict["four"] => 4 + +# "setdefault()" 只在指定的Key不存在時才會將值插入dictionary +filled_dict.setdefault("five", 5) # filled_dict["five"] 被指定為 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] 仍保持 5 + + +# 集合(Set)被用來儲存...集合。 +# 跟串列(List)有點像,但集合內不會有重複的元素 +empty_set = set() +# 初始化 "set()" 並給定一些值 +some_set = set([1, 2, 2, 3, 4]) # 現在 some_set 為 set([1, 2, 3, 4]),注意重複的元素只有一個會被存入 + +# 一樣,不保證順序,就算真的有照順序排也只是你運氣好 +another_set = set([4, 3, 2, 2, 1]) # another_set 現在為 set([1, 2, 3, 4]) + +# 從 Python 2.7 開始,可以使用大括號 {} 來宣告Set +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# 加入更多元素進入Set +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# 用 & 來對兩個集合取交集 +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# 用 | 來對兩個集合取聯集 +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# 用 - 來將第二個集合內有的元素移出第一個集合 +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# 用 ^ 來對兩個集合取差集 +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# 檢查左邊是否為右邊的母集 +{1, 2} >= {1, 2, 3} # => False + +# 檢查左邊是否為右邊的子集 +{1, 2} <= {1, 2, 3} # => True + +# 用 in 來檢查某元素是否存在於集合內 +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. 控制流程 +#################################################### + +# 首先,先宣告一個變數 +some_var = 5 + +# 這邊是 if 判斷式。注意,縮排對Python是很重要的。 +# 下面應該會印出 "some_var is smaller than 10" +if some_var > 10: + print "some_var is totally bigger than 10." +elif some_var < 10: # elif 可有可無 + print "some_var is smaller than 10." +else: # else 也可有可無 + print "some_var is indeed 10." + + +""" +For 迴圈會遞迴整的List +下面的程式碼會輸出: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # 你可以用{0}來組合0出格式化字串 (見上面.) + print "{0} is a mammal".format(animal) + +""" +"range(number)" 回傳一個包含從0到給定值的數字List, +下面的程式碼會輸出: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(lower, upper)" 回傳一個包含從給定的下限 +到給定的上限的數字List +下面的程式碼會輸出: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +While迴圈會執行到條件不成立為止 +下面的程式碼會輸出: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # x = x + 1 的簡寫 + +# 用try/except處理例外 + +# 適用Python 2.6及以上版本 +try: + # 用 "raise" 來發起例外 + raise IndexError("This is an index error") +except IndexError as e: + pass # 毫無反應,就只是個什麼都沒做的pass。通常這邊會讓你做對例外的處理 +except (TypeError, NameError): + pass # 有需要的話,多種例外可以一起處理 +else: # else 可有可無,但必須寫在所有的except後 + print "All good!" # 只有在try的時候沒有產生任何except才會被執行 +finally: # 不管什麼情況下一定會被執行 + print "We can clean up resources here" + +# 除了try/finally以外,你可以用 with 來簡單的處理清理動作 +with open("myfile.txt") as f: + for line in f: + print line + +#################################################### +## 4. 函式 +#################################################### + +# 用 "def" 來建立新函式 +def add(x, y): + print "x is {0} and y is {1}".format(x, y) + return x + y # 用 "return" 來回傳值 + +# 用參數來呼叫函式 +add(5, 6) # => 輸出 "x is 5 and y is 6" 並回傳 11 + +# 你也可以寫上參數名稱來呼叫函式 +add(y=6, x=5) # 這種狀況下,兩個參數的順序並不影響執行 + + +# 你可以定義接受多個變數的函式,用*來表示參數tuple +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# 你可以定義接受多個變數的函式,用**來表示參數dictionary +def keyword_args(**kwargs): + return kwargs + +# 呼叫看看會發生什麼事吧 +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# 如果你想要,你也可以兩個同時用 +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# 呼叫函式時,你可以做反向的操作 +# 用 * 將變數展開為順序排序的變數 +# 用 ** 將變數展開為Keyword排序的變數 +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # 等同於 foo(1, 2, 3, 4) +all_the_args(**kwargs) # 等同於 foo(a=3, b=4) +all_the_args(*args, **kwargs) # 等同於 foo(1, 2, 3, 4, a=3, b=4) + +# 你可以把args跟kwargs傳到下一個函式內 +# 分別用 * 跟 ** 將它展開就可以了 +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# 函式範圍 +x = 5 + +def set_x(num): + # 區域變數 x 和全域變數 x 不是同一個東西 + x = num # => 43 + print x # => 43 + +def set_global_x(num): + global x + print x # => 5 + x = num # 全域變數 x 在set_global_x(6)被設定為 6 + print x # => 6 + +set_x(43) +set_global_x(6) + +# Python有一級函式 +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# 也有匿名函式 +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# 還有內建的高階函式 +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# 我們可以用List列表的方式對map和filter等高階函式做更有趣的應用 +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + + +#################################################### +## 5. 類別 +#################################################### + +# 我們可以由object繼承出一個新的類別 +class Human(object): + + # 類別的參數,被所有這個類別的實體所共用 + species = "H. sapiens" + + # 基礎建構函式,當class被實體化的時候會被呼叫 + # 注意前後的雙底線 + # 代表此物件或屬性雖然在使用者控制的命名空間內,但是被python使用 + def __init__(self, name): + # 將函式引入的參數 name 指定給實體的 name 參數 + self.name = name + + # 初始化屬性 + self.age = 0 + + + # 一個實體的方法(method)。 所有的method都以self為第一個參數 + def say(self, msg): + return "{0}: {1}".format(self.name, msg) + + # 一個類別方法會被所有的實體所共用 + # 他們會以類別為第一參數的方式被呼叫 + @classmethod + def get_species(cls): + return cls.species + + # 靜態方法 + @staticmethod + def grunt(): + return "*grunt*" + + # 屬性就像是用getter取值一樣 + # 它將方法 age() 轉為同名的、只能讀取的屬性 + @property + def age(self): + return self._age + + # 這樣寫的話可以讓屬性被寫入新的值 + @age.setter + def age(self, age): + self._age = age + + # 這樣寫的話允許屬性被刪除 + @age.deleter + def age(self): + del self._age + + +# 將類別實體化 +i = Human(name="Ian") +print i.say("hi") # prints out "Ian: hi" + +j = Human("Joel") +print j.say("hello") # prints out "Joel: hello" + +# 呼叫類別方法 +i.get_species() # => "H. sapiens" + +# 更改共用的屬性 +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# 呼叫靜態方法 +Human.grunt() # => "*grunt*" + +# 更新屬性 +i.age = 42 + +# 取得屬性 +i.age # => 42 + +# 移除屬性 +del i.age +i.age # => raises an AttributeError + + +#################################################### +## 6. 模組 +#################################################### + +# 你可以引入模組來做使用 +import math +print math.sqrt(16) # => 4.0 + # math.sqrt()為取根號 + +# 你可以只從模組取出特定幾個函式 +from math import ceil, floor +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 + +# 你可以將所有的函式從模組中引入 +# 注意:不建議這麼做 +from math import * + +# 你可以用 as 簡寫模組名稱 +import math as m +math.sqrt(16) == m.sqrt(16) # => True +# 你也可以測試函示是否相等 +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True + +# Python的模組就只是一般的Python檔。 +# 你可以自己的模組自己寫、自己的模組自己引入 +# 模組的名稱和檔案名稱一樣 + +# 你可以用dir()來查看有哪些可用函式和屬性 +import math +dir(math) + + +#################################################### +## 7. 進階 +#################################################### + +# 產生器(Generator)可以讓你寫更懶惰的程式碼 +def double_numbers(iterable): + for i in iterable: + yield i + i + +# 產生器可以讓你即時的產生值 +# 不是全部產生完之後再一次回傳,產生器會在每一個遞迴時 +# 產生值。 這也意味著大於15的值不會在double_numbers中產生。 +# 這邊,xrange()做的事情和range()一樣 +# 建立一個 1-900000000 的List會消耗很多時間和記憶體空間 +# xrange() 建立一個產生器物件,而不是如range()建立整個List +# 我們用底線來避免可能和python的關鍵字重複的名稱 +xrange_ = xrange(1, 900000000) + +# 下面的程式碼會把所有的值乘以兩倍,直到出現大於30的值 +for i in double_numbers(xrange_): + print i + if i >= 30: + break + + +# 裝飾子 +# 在這個範例中,beg會綁在say上 +# Beg會呼叫say。 如果say_please為True的話,它會更改回傳的訊息 +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print say() # Can you buy me a beer? +print say(say_please=True) # Can you buy me a beer? Please! I am poor :( +``` + +## 準備好學更多了嗎? + +### 線上免費資源 + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### 或買本書? + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From a3b0585374d69e392fdb724bde30bc4048358d31 Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Wed, 12 Feb 2020 04:54:36 +0100 Subject: Rename Python 3 markdown files into 'python' ``` for f in $(find . -iname "*python3*" | grep -vE 'git'); do fnew=$(echo "$f" | sed 's/python3/python/') git mv "$f" "$fnew" done --- ar-ar/python-ar.html.markdown | 1019 +++++++++++++++++++++++++++++++++++++++ ar-ar/python3-ar.html.markdown | 1019 --------------------------------------- cs-cz/python.html.markdown | 647 +++++++++++++++++++++++++ cs-cz/python3.html.markdown | 647 ------------------------- de-de/python-de.html.markdown | 655 +++++++++++++++++++++++++ de-de/python3-de.html.markdown | 655 ------------------------- el-gr/python-gr.html.markdown | 1031 +++++++++++++++++++++++++++++++++++++++ el-gr/python3-gr.html.markdown | 1031 --------------------------------------- es-es/python-es.html.markdown | 577 ++++++++++++++++++++++ es-es/python3-es.html.markdown | 577 ---------------------- fr-fr/python-fr.html.markdown | 732 ++++++++++++++++++++++++++++ fr-fr/python3-fr.html.markdown | 732 ---------------------------- it-it/python-it.html.markdown | 1016 +++++++++++++++++++++++++++++++++++++++ it-it/python3-it.html.markdown | 1016 --------------------------------------- ja-jp/python-jp.html.markdown | 1008 ++++++++++++++++++++++++++++++++++++++ ja-jp/python3-jp.html.markdown | 1008 -------------------------------------- pt-br/python-pt.html.markdown | 746 ++++++++++++++++++++++++++++ pt-br/python3-pt.html.markdown | 746 ---------------------------- python.html.markdown | 1042 ++++++++++++++++++++++++++++++++++++++++ python3.html.markdown | 1042 ---------------------------------------- ru-ru/python-ru.html.markdown | 651 +++++++++++++++++++++++++ ru-ru/python3-ru.html.markdown | 651 ------------------------- tr-tr/python-tr.html.markdown | 640 ++++++++++++++++++++++++ tr-tr/python3-tr.html.markdown | 640 ------------------------ vi-vn/python-vi.html.markdown | 914 +++++++++++++++++++++++++++++++++++ vi-vn/python3-vi.html.markdown | 914 ----------------------------------- zh-cn/python-cn.html.markdown | 632 ++++++++++++++++++++++++ zh-cn/python3-cn.html.markdown | 632 ------------------------ 28 files changed, 11310 insertions(+), 11310 deletions(-) create mode 100644 ar-ar/python-ar.html.markdown delete mode 100644 ar-ar/python3-ar.html.markdown create mode 100644 cs-cz/python.html.markdown delete mode 100644 cs-cz/python3.html.markdown create mode 100644 de-de/python-de.html.markdown delete mode 100644 de-de/python3-de.html.markdown create mode 100644 el-gr/python-gr.html.markdown delete mode 100644 el-gr/python3-gr.html.markdown create mode 100644 es-es/python-es.html.markdown delete mode 100644 es-es/python3-es.html.markdown create mode 100644 fr-fr/python-fr.html.markdown delete mode 100644 fr-fr/python3-fr.html.markdown create mode 100644 it-it/python-it.html.markdown delete mode 100644 it-it/python3-it.html.markdown create mode 100644 ja-jp/python-jp.html.markdown delete mode 100644 ja-jp/python3-jp.html.markdown create mode 100644 pt-br/python-pt.html.markdown delete mode 100644 pt-br/python3-pt.html.markdown create mode 100644 python.html.markdown delete mode 100644 python3.html.markdown create mode 100644 ru-ru/python-ru.html.markdown delete mode 100644 ru-ru/python3-ru.html.markdown create mode 100644 tr-tr/python-tr.html.markdown delete mode 100644 tr-tr/python3-tr.html.markdown create mode 100644 vi-vn/python-vi.html.markdown delete mode 100644 vi-vn/python3-vi.html.markdown create mode 100644 zh-cn/python-cn.html.markdown delete mode 100644 zh-cn/python3-cn.html.markdown diff --git a/ar-ar/python-ar.html.markdown b/ar-ar/python-ar.html.markdown new file mode 100644 index 00000000..e1a12690 --- /dev/null +++ b/ar-ar/python-ar.html.markdown @@ -0,0 +1,1019 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] + - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] +translators: + - ["Ahmad Hegazy", "https://github.com/ahegazy"] +lang: ar-ar +filename: learnpython3-ar.py +--- + +لقد أُنشئت لغة البايثون بواسطة جايدو ڤان روسم في بداية التسعينات. هي الأن أحد أشهر اللغات الموجودة. +لقد أحببت لغة البايثون بسبب وضوحها. هي في الأساس عبارة عن سودوكود قابل للتنفيذ. + +ردود أفعالكم عن المقال مُقدرة بشدة. يمكنكم التواصل مع الكاتب الاساسي من خلال [@louiedinh](http://twitter.com/louiedinh) أو louiedinh [at] [google's email service] + +ملحوظة: هذا المقال يُطبق على بايثون 3 فقط. راجع المقال [هنا](http://learnxinyminutes.com/docs/python/) إذا أردت تعلم لغة البايثون نسخة 2.7 الأقدم + +```python + +# تعليق من سطر واحد يبدأ برمز الرقم. + +""" يمكن كتابة تعليق يتكون من أكثر من سطر + باستخدام ثلاثة علامات " + ، وعادة يُستخدم في كتابة التوثيقات. +""" + +#################################################### +## 1. أنواع البيانات البدائية والعمليات +#################################################### + +# لديك أرقام +3 # => 3 + +# العمليات الحسابية هي ما تتوقعه +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# نتائج قسمة الأرقام الصحيحية تُقرب للأصغر سواءًا كانت الأرقام موجبة أو سالبة. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # يعمل في حالة الكسور أيضا +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# ناتج القسمة هو دائما كسر +10.0 / 3 # => 3.3333333333333335 + +# عملية باقي القسمة +7 % 3 # => 1 + +# الأُس (س ** ص، رفع س لقوى ص) +2**3 # => 8 + +# أفرض ترتيب العمليات الحسابية بالأقواس +(1 + 3) * 2 # => 8 + +# القيم الثنائية هي المعروفة عموما (ﻻحظ: تكبير أول حرف) +True +False + +# أنفي بـ (not) +not True # => False +not False # => True + +# العمليات على القيم الثنائية +# ﻻحظ ﻻيهم حالة الحرف (كبير أو صغير) في "and" و "or" +True and False # => False +False or True # => True + +# True و False هما في الواقع 1 و 0 لكن بمسميات مختلفة +True + True # => 2 +True * 8 # => 8 +False - 5 # => -5 + +# عمليات المقارنة تنظر الي القيمة الرقمية لل True وال False +0 == False # => True +1 == True # => True +2 == True # => False +-5 != False # => True + +# عند استخدام المنطق الثنائي على القيم الصحيحة يتم تحويلهم الي قيم ثنائية لإجرات العمليات عليهم، لكن قيمهم الأصلية تعود +# ﻻ تخلط بين bool(قيمة صحيحة) و العمليات المنطقية الثناية and/or (&,|) +bool(0) # => False +bool(4) # => True +bool(-6) # => True +0 and 2 # => 0 +-5 or 0 # => -5 + +# مقارنة التساوي ب == +1 == 1 # => True +2 == 1 # => False + +# مقارنة الاختلاف ب != +1 != 1 # => False +2 != 1 # => True + +# مقارنات أخرى +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# لمعرفة هل القيمة في نطاق معين +1 < 2 and 2 < 3 # => True +2 < 3 and 3 < 2 # => False + +# التسلسل يجعلها تبدو أجمل +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is مقابل ==) is تتحق من أن المتغيرين يشيران إلي نفس العنصر, +# لكن == تتحقق من أن العنصرين المُشار اليهما بالمتغيرين لهما نفس القيمة. +a = [1, 2, 3, 4] # اجعل a تشير إلي قائمة جديدة, [1, 2, 3, 4] +b = a # اجعل a تُشير الي ما تُشير إليه b +b is a # => True, a و b يُشيران إلي نفس العنصر +b == a # => True, قيمة عنصر a و b متساوية +b = [1, 2, 3, 4] # اجعل b تشير الي قائمة جديدة , [1, 2, 3, 4] +b is a # => False, a و b do ﻻ يشيران إلي نفس العنصر +b == a # => True, قيمة عنصر a و b متساوية + +# يمكنك إنشاء الكلمات (تسلسلات الحروف) عن طريق " أو ' +"This is a string." +'This is also a string.' + +# يمكنك جمع هذا النوع أيضا! لكن حاول ألا تفعل هذا. +"Hello " + "world!" # => "Hello world!" +# يمكنك الربط بين الكلمات بدون استخدام '+' (لكن ليس المتغيرات) +"Hello " "world!" # => "Hello world!" + +# يمكنك معاملة الكلمات كقائمة من الحروف +"This is a string"[0] # => 'T' + +# يمكنك معرفة طول الكلمة +len("This is a string") # => 16 + +# .format يمكنك استخدامها لبناء الجمل بشكل معين, مثل هذا: +"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" + +# يمكنك تكرار معاملات بناء الجملة لتقليل الكتابة. +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# يمكنك استخدام الكلمات المفتاحية إذا لم تُرد العد. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" + +# إذا كان كود بايثون 3 الخاص بك يحتاج لبايثون 2.5 أو نسخة أقدم +# يمكنك استخدام أسلوب بناء الجمل القديم: +"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" + +# يمكنك أبضا بناء الجمل باستخدام f-strings أو حروف بناء الجمل (في بايثون 3.6 فما فوق) +name = "Reiko" +f"She said her name is {name}." # => "She said her name is Reiko" +# يمكنك ببساطة وضع أي كود بايثون داخل أقواس وستقوم بإخراج الجملة. +f"{name} is {len(name)} characters long." + + +# None عبارة عن كائن +None # => None + +# ﻻ تستخدم رمز المساواة "==" لمقارنة العناصر ب None +# استخدم is بدلا منه. يقوم بالتحقق من مساواة هوية العنصر +"etc" is None # => False +None is None # => True + +# None, 0, قوائم/جمل/قواميس/صفوف فارغة كلها تُترجم إلي False. +# كل القيم الأخرى True. +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +## 2. المتغيرات والمجموعات +#################################################### + +# بايثون لديها دالة عرض "print" +print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! + +# الافتراضي دالة print تطبع سطر جديد في النهاية. +# استخدم المعامل end لتغيير أخر الجملة المعروضة. +print("Hello, World", end="!") # => Hello, World! + +# طريقة بسيطة لطلب مدخل من الطرفية +input_string_var = input("Enter some data: ") # يقوم بإعادة البيانات ك "string" +# لاحظ: في النسخ القديمة من بايثون، دالة input() كان اسمها raw_input() + +# ﻻ يوجد تعريفات للمتغيرات، يتم تعيين قيمة المتغير مباشرة. +# العٌرف تسمية المتغيرات حروف_صغيرة_مع_خطوط_سُفلية +some_var = 5 +some_var # => 5 + +# محاولة استخدام متغير غير مُعين يعتبر خطأ +# إقرأ جزء 3.مسار التحكم لمعرفة المزيد عن التحكم في الأخطاء +some_unknown_var # يعرض خطأ NameError + +# يمكن استخدام if كتعبير واحد +# مساوِ للتعبير الأتي في لغة السي '?:' عملية ثلاثية +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# القوائم تحفظ المتسلسلات +li = [] +# يمكنك البدأ بقائمة مليئة +other_li = [4, 5, 6] + +# إضافة بيانات لأخر القائمة عن طريق append +li.append(1) # li is now [1] +li.append(2) # li is now [1, 2] +li.append(4) # li is now [1, 2, 4] +li.append(3) # li is now [1, 2, 4, 3] +# حذف أخر عنصر في القائمة عن طريق pop +li.pop() # => 3 and li is now [1, 2, 4] +# هيا نعيده ثانية +li.append(3) # li is now [1, 2, 4, 3] again. + +# يمكنك الوصول لعناصر القائمة كما تفعل في ال array +# Access a list like you would any array +li[0] # => 1 +# للوصول لأخر عنصر +li[-1] # => 3 + +# محاولة الوصول لعنصر خارج نطاق القائمة يعتبر خطأ: IndexError +li[4] # يعرض خطأ IndexError + +# يمكنك النظر للنطاقات باستخدام تركيب التقطيع +# مؤشر/رقم/فهرس البداية مُضمن، مؤشر النهاية ﻻ +# (لمحبي الرياضيات هو نطاق مفتوح/مغلق) +li[1:3] # => [2, 4] +# إحذف أول عنصر ثم إعرض القائمة +li[2:] # => [4, 3] +# إحذف أخر عنصر ثم إعرض القائمة +li[:3] # => [1, 2, 4] +# حدد عنصر ثم إحذف الذي يليه ثم حدد عنصر وهكذا +li[::2] # =>[1, 4] +# اعرض نسخة معكوسة من القائمة +li[::-1] # => [3, 4, 2, 1] +# إستخدم أي تجميعة من الطرق المذكورة لعمل تقطيعات متقدمة +# li[start:end:step] + +# عمل نسخة من طبقة واحدة باستخدم التقطيع +li2 = li[:] # => li2 = [1, 2, 4, 3] لكن عند عمل(li2 is li) سينتج False. + +# إمسح أي عنصر من القائمة باستخدام "del" +del li[2] # li is now [1, 2, 3] + +# إمسح أول ظهور لقيمة. +li.remove(2) # li is now [1, 3] +li.remove(2) # يعرض خطأ ValueError لأن 2 غير موجود في القائمة + +# أضف عنصر في خانة معينة +li.insert(1, 2) # li is now [1, 2, 3] مرة أخرى + +# أحصل على مؤشر/رقم لأول ظهور للقيمة +li.index(2) # => 1 +li.index(4) # يعرض خطأ ValueError لأن 4 غير موجودة في القائمة + +# يمكنك جمع قوائم +# لاحظ: لا يتم تعديل قيمة li و other_li +li + other_li # => [1, 2, 3, 4, 5, 6] + +# إستخدم دالة "extend()" لربط القوائم +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# راجع وجود قيمة في القائمة باستخدام "in" +1 in li # => True + +# إحصل على طول القائمة باستخدام دالة "len()" +len(li) # => 6 + + +# الصفوف تشبه القوائم لكنها غير قابلة للتغيير. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # يعرض خطأ TypeError + +# لاحظ أن صف طوله عنصر واحد يحتاج لإضافة فاصلة "," بعد أخر عنصر +# لكن الصفوف من أي طول أخر، حتى صفر لا تحتاج. +type((1)) # => +type((1,)) # => +type(()) # => + +# يمكنك عمل معظم عمليات القوائم على الصفوف. +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# يمكنك تفريغ الصفوف (أو القوائم) في متغيرات +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +# يمكنك أيضا عمل تفريغ واسع +a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 +# الصفوف تُنشأ تلقائيا إذا تركت الأقواس +d, e, f = 4, 5, 6 # تم توسعة الصف 4, 5 ,6 في المتغيرات d, e, f +# بالترتيب حيث d = 4, e = 5 و f = 6 +# الأن إنظر إلي مدى سهولة التبديل بين قيم متغيرين +e, d = d, e # d is now 5 and e is now 4 + + +# القواميس تُخزن خرائط من المفتاح للقيمة +empty_dict = {} +# هذا قاموس مملوء +filled_dict = {"one": 1, "two": 2, "three": 3} + +# لاحظ أن القواميس يجب أن تكون أنواع غير قابلة للتغيير. +# هذا للتأكد من أن المفتاح يمكن تحويله لقيمة ثابتة للوصول السريع. +# الأنواع الغير قابلة للتغير تتضمن: الأرقام الصحيحة، الكسور، الكلمات، الصفوف. +invalid_dict = {[1,2,3]: "123"} # =>يعرض خطأ TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # القيم يمكن أن تكون من أي نوع. + +# يمكنك البحث عن قيمة باستخدام [] +filled_dict["one"] # => 1 + +# يمكنك الحصول على كل المفاتيح باستخدام "keys()". +# نحتاج لإرسالها لدالة list() لتحويلها لقائمة. سنتعلم هذا لاحقًا +# لاحظ - لنسخ بايثون قبل 3.7، ترتيب مفاتيح القاموس غير مضمون. نتائجك +# يمكن ألا تساوي المثال بالأسفل. مع ذلك، من أول بايثون 3.7، +# عناصر القاموس تحتفظ بالترتيب الذي تم إضافة المفاتيح به في القاموس. +list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7 +list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+ + +# يمكنك الحصول على كل القيم باستخدام "values()". +# مرة أخرى نستخدم list() للحصول عليها كقائمة. +# نفس الكلام السابق بخصوص ترتيب المفاتيح +list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 +list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ + +# إفحص للتأكد من وجود مغتاح في القاموس باستخدام "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# البحث عن مفتاح غير موجود يعرض خطأ KeyError +filled_dict["four"] # KeyError + +# استخدم "get()" لتجنب الخطأ KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# دالة get تدعم إدخال قيمة افتراضية عند عدم وجود البحث +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" تقوم بإدخال قيمة جديدة في القاموس في حالة عدم وجود المفتاح فقط. +filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 + +# إضافة عنصر للقاموس +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict["four"] = 4 # طريقة أخرى للإضافة + +# مسح المفاتيح من القاموس باستخدام del +del filled_dict["one"] # Removes the key "one" from filled dict + +# من بايثون 3.5 فما فوق يمكنك أيضا استخدام خيارات تفريغ إضافية +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + +# المجموعات تُخزن .. مجموعات +empty_set = set() +# .تهيئة مجموعة بمجموعة قيم. نعم، تشبه قليلا تهيئة القاموس. أسف +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# مثل مفتاح القاموس، عناصر المجموعة يجب أن تكون غير قابلة للتغيير. +invalid_set = {[1], 1} # => يعرض خطأ TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# إضافة عنصر أخر للمجموعة +filled_set = some_set +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} +# المجموعات لا يمكن أن تحتوي على عناصر مكررة +filled_set.add(5) # it remains as before {1, 2, 3, 4, 5} + +# تقاطع مجموعتين باستخدام & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# اتحاد مجموعتين باستخدام | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# الفرق بين مجموعتين باستخدام - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# الفروق بين مجموعتين باستخدام ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# لفحص هل المجموعة على اليسار مجموعة عُليا للمجموعة على اليمين (تحتوي على كل عناصرها) +{1, 2} >= {1, 2, 3} # => False + +# لفحص هل المجموعة على اليسار مجموعة فرعية من المجموعة على اليمين +{1, 2} <= {1, 2, 3} # => True + +# للتأكد من وجود عن في مجموعة استخدم in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. مسار التحكم والعمليات التكرارية #Control Flow and Iterables +#################################################### + +# هيا ننشيء متغير +some_var = 5 + +# الأن الأمر if. الفجوات (المسافات قبل الأوامر) مهمة في البايثون! +# العُرف استخدام أربع مسافات. ليس تبويب. +# هذا السطر البرمجي يطبع "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # This elif clause is optional. + print("some_var is smaller than 10.") +else: # This is optional too. + print("some_var is indeed 10.") + + +""" +For عبارة عن حلقات تدور حول عناصر قوائم +:ثم تطبع + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # يمكنك استخدام format() لترجمة كلمات بشكل معين. + print("{} is a mammal".format(animal)) + +""" +"range(number)" يقوم بإعادة مجموعة من الأرقام يمكن الدوران حولها +من الصفر إلي رقم معين +ثم يطبع: + 0 + 1 + 2 + 3 +""" + +for i in range(4): + print(i) + +""" +"range(lower, upper)" يقوم بإعادة مجموعة من الأرقام يمكن الدوران حولها من القيمة السُفلى +lower حتى القيمة العُليا upper +ثم يطبع: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(lower, upper, step)" يقوم بإعادة مجموعة من الأرقام يمكن الدوران حولها من القيمة السُفلى +lower حتى القيمة العُليا upper، ثم يقوم بالزيادة قيمة الstep. +إذا لم تُحدد ال step, القيمة الأفتراضية 1. +ثم يطبع: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) + +""" +While هي عبارة عن حلقات تدور حتى عدم تحقق شرط معين. +وتطبع: + 0 + 1 + 2 + 3 +""" +x = 0 for +while x < 4: + print(x) + x += 1 # اختصار ل x = x + 1 + +# يمكنك التحكم في الأخطاء والاستثناءات باستخدام مجموعة try/except +try: + # استخدم "raise" لرفع خطأ. + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass: هو مجرد أمر ﻻ تفعل شيء. عادة تقوم بتصحيح الخطأ هنا. +except (TypeError, NameError): + pass # يمكنك التحكم في أكثر من خطأ في نفس الوقت، إذا أقتضت الضرورة +else: # فقرة اختيارية في مجموعة try/except. يجب أن يتبع جميع مجموعات معارضة الأخطاء + print("All good!") # تُنفذ في حالة أن السطور البرمجية داخل ال try لم ترفع أي خطأ +finally: # تُنفذ في كل الحالات + print("We can clean up resources here") + +# بدلا من مجموعة try/finally لتنظيف الموارد يمكنك استخدام سطر with +with open("myfile.txt") as f: + for line in f: + print(line) + +# يتيح البايثون تجريد أساسي يسمى المُكرَر. +# المُكرٍَر عبارة عن متغير يمكن التعامل معه كسلسلة. +# الكائن الذي يعود من دالة نطاق، يسمى المُكرَر. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['one', 'two', 'three']) +# هذا عبارة عن متغير يعرض عناصر مفاتيح المُكرَر. + +# يمكننا الدوران حوله. +for i in our_iterable: + print(i) # Prints one, two, three + +# مع ذلك ﻻ يمكننا الوصول للعناصر بالمؤشر. +our_iterable[1] # يرفع خطأ TypeError + +# المُكرَر هو عبارة عن عنصر يعلم كيفية إنشاء مُكرِر +our_iterator = iter(our_iterable) + +# المُكرِر هو عبارة عن عنصر يمكنه تذكر الحالة أثناء مرورنا بعناصره. +# يمكننا الحصول على العنصر التالي عن طريق "next()" +next(our_iterator) # => "one" + +# يحفظ الحالة أثناء الدوران. +next(our_iterator) # => "two" +next(our_iterator) # => "three" + +# بعد عرض المُكرِر كل عناصره، يرفع استثناء StopIteration +next(our_iterator) # يرفع StopIteration + +# يمكنك الحصول على كل عناصر المُكرر بمناداة دالة list() عليه. +list(filled_dict.keys()) # => Returns ["one", "two", "three"] + + +#################################################### +## 4. الدوال +#################################################### + +# إستخدم "def" لإنشاء دوال جديدة. +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # يمكنك إرجاع قيمة من الدالة بسطر return + +# مناداة دوال بمعطيات +add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 + +# طريقة أخرى لمناداة دوال باستخدام كلمات مفتاحية. +add(y=6, x=5) # الكلمة المفتاحية يمكن أن تُعطى بأي ترتيب. + +# يمكنك تعريف دوال تأخذ عدد متغير من المُعطيات + +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# يمكنك تعريف دوال تأخذ عدد متغير من الكلمات المفتاحية كمعطيات أيضا. +def keyword_args(**kwargs): + return kwargs + +# هيا ننادي على الدالة لنرى ماذا سيحدث +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# يمكنك فعل الأثنين معًا في نفس الوقت، إذا أردت +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# عندما تنادي على دوال، يمكنك عمل عكس المعطيات/المفاتيح! +# استخدم * لتوسعة الصفوف، واستخدم ** لتوسعة المفاتيح. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # مساوٍ ل all_the_args(1, 2, 3, 4) +all_the_args(**kwargs) # مساوٍ ل to all_the_args(a=3, b=4) +all_the_args(*args, **kwargs) # مساوٍ ل to all_the_args(1, 2, 3, 4, a=3, b=4) + +# يقوم بإعادة مجموعة من القيم (بتعيين الصفوف) +def swap(x, y): + return y, x # يقوم بإعادة مجموعة من القيم على شكل صفوف بدون الأقواس + # (لاحظ: الأقواس حُذفت لكن يمكن إضافتها) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # مرة أخرى الأقواس حُذفت لكن يمكن إضافتها. + +# مجال الدالة +x = 5 + +def set_x(num): + # المتغير المحلي x ليس هو المتغير العام x + x = num # => 43 + print(x) # => 43 + +def set_global_x(num): + global x + print(x) # => 5 + x = num #المتغير العام x الأن مساوٍ ل 6 + print(x) # => 6 + +set_x(43) +set_global_x(6) + + +# بايثون تدعم دوال الفئة أولية [first class functions] (أي أنه يمكن إرسال الدوال كمعطيات لدوال أخرى) +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# يوجد أيضا دوال مجهولة +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# يوجد دوال مدمجة من درجة أعلى +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# يمكن إشتمال القوائم على خرائط وفلاتر حسنة الشكل +# هذه القوائم تحفظ المُخرج كقائمة والتي بدورها يمكن أن تكون قائمة مداخلة +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# يمكنك بناء مجموعات وقواميس على هذا المنوال أيضا +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. الوحدات البرمجية (الموديولات) +#################################################### + +# يمكنك استدعاء موديولات +import math +print(math.sqrt(16)) # => 4.0 + +# يمكنك استدعاء دالة معينة من موديول +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# يمكنك استدعاء كل الدوال من مديول. +# تحذير: هذا الفعل غير موصى به +from math import * + +# يمكنك تصغير اسم موديول +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# موديولات البايثون عبارة عن ملفات بايثون عادية. +# يمكنك كتابة الموديولات الخاصة بك, واستدعاها. +# اسم الموديول يكون نفس اسم الملف. + +# يمكنك معرفة أي الدوال والصفات مُعرفة في الموديول. +import math +dir(math) + +# إذا كان لديك سكربت بايثون يسمى math.py +# في نفس المجلد الموجود به السكربت الخاص بك، الملف الخاص بك math.py +# سَيُستدعى بدلا من موديول البايثون بنفس الاسم +# هذا يحدث لأن المجلدات المحلية لديها أولوية عن مكتبات البايثون المُدمجة + + +#################################################### +## 6. الفئات/القوالب (الكلاسات) +#################################################### + +# نستخدم السطر البرمجي "class" لإنشاء قالب +class Human: + + # صفة القالب. مشتركة بين كل نسخ القالب + species = "H. sapiens" + + # مُهيئ إبتدائي، يُنادى عليه عندما يتم استدعاء القالب. + # لاحظ أن الشرطة السٌفلية المُكررة مرتين __ قبل وبعد الاسم تُعبر عن الكائنات + # أو الصفات المُستخدمة عن طريق بايثون لكنها تعيش في مساحة تحكم المُستخدم. + # العمليات -الدوال- (أو الكائنات أو الصفات) مثل: __init__, __str__,__repr__ ألخ. + # تُسمى عمليات خاصة (أو أحيانا تسمى عمليات سحرية أو dunder methods) + # يجب عليك ألا تُسمي مثل هذه الاسماء بنفسك. + def __init__(self, name): + # ساوِ المُعطى بالصفة name الخاصة بهذه النسخة من القالب. + self.name = name + + # هيئ الصفة + self._age = 0 + + # عملية/دالة خاصة بنسخة القالب. كل العمليات تأخذ "self" كأول مُعطى + # An instance method. All methods take "self" as the first argument + def say(self, msg): + print("{name}: {message}".format(name=self.name, message=msg)) + + # عملية أخرى خاصة بنسخة القالب. + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # عمليات القالب مشتركة بين كل أجزاء القالب + # يتم مناداتهم عن طريق جعل القالب المُنادي أول معطى + # They are called with the calling class as the first argument + @classmethod + def get_species(cls): + return cls.species + + # تُنادى العملية الثابتة بدون قالب أو نسخة قالب + @staticmethod + def grunt(): + return "*grunt*" + + # الخاصية تشبه تماما إمر الطلب + # تُحَوِل العملية age() إلي صفة مقروءة فقط بنفس الاسم. + # ﻻ حاجة لكتابة أوامر طلب أو تهيئة + @property + def age(self): + return self._age + + # هذا يتيح تهيئة الخاصية + @age.setter + def age(self, age): + self._age = age + + # هذا يتيح حذف الخاصية + @age.deleter + def age(self): + del self._age + + +# عندما يقرأ مُترجم البايثون ملف مصدري يقوم بتنفيذ كل الكود. +# فحص ال __name__ يجعل هذا الجزء من الكود يُنَفَذ فقط +# في حالة أن هذا الموديول هو البرنامج الرئيسي +if __name__ == '__main__': + # Instantiate a class + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i و j نُسخ من النوع Human, أول بكلمات أخرى: هما كائنات للقالب Human + + # نادي على عملية القالب + i.say(i.get_species()) # "Ian: H. sapiens" + # عدل الخاصية المُشتركة + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # نادي على العملية الثابتة + print(Human.grunt()) # => "*grunt*" + + # لا يمكن مناداة العملية الثابتة من نسخة الكائن + # لأن i.grunt() سيقوم تلقائيا بوضع "self" (الكائن i) كمُعطى للعملية + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # حدًث الخاصية لهذه النسخة + i.age = 42 + # أحصل على الخاصية + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # إحذف الخاصية + del i.age + # i.age # => سوف يرفع استثناء AttributeError + + +#################################################### +## 6.1 الإرث +#################################################### + +# الإرث يتيح لقالب ابن أن يُعَرف ويرث بعض عمليات/دوال ومتغيرات القالب الأب. + +# باستخدام القالب Human المُعَرف بالأعلى كأساس أو كقالب أب، +# يمكننا تعريف قالب ابن،Superhero ، يرث متغيرات القالب مثل "species", "name", و "age"، +# وأيضا العمليات، مثل "sing", "grunt" +# من القالب Human، لكنه أيضا لديه خواصه الفريدة + +# للاستفادة من التقطيع بالملف يمكنك وضع القوالب بالأعلى في ملفاتهم الخاصة، +# مثلا، human.py + +# لاستيراد دالة من ملف أخر استخدم الطريقة التالية +# from "اسم الملف بدون مُلحق" import "اسم الدالة أو القالب" + +from human import Human + +# حدد القالب/ات الأب كمُعطى أثناء تعريف القالب. +class Superhero(Human): + + # إذا أردت أن يرث القالب الابن كل تعريفات القالب الأب بدون تعديل + # يمكنك استخدام الكلمة المفتاحية "pass" (بدون شيء أخر) + # لكن في هذه الحالة تم أهمالها لإنشاء قالب ابن فريد: + # pass + + # القوالب الابن يمكنها تعديل صفات القوالب الأب + species = 'Superhuman' + + # القوالب الابن ترث تلقائيا عمليات الإنشاء الخاصة بالقالب الأب بالإضافة إلي مُعطياتهم + # لكن يمكن أيضا تعريف مُعطيات إضافية أو تعريفات + # وتعديل العمليات مثل منشيء القالب. + # هذا المُنشيء يرث المُعطى "name" من القالب "Human" + # ويضيف المعطيات"superpower" و "movies": + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # إضافة صفة جديدة للقالب + self.fictional = True + self.movie = movie + # كن على علم بالقيم الافتراضية المتغيرة، حيث أن القيم الافتراضية تُشارك + self.superpowers = superpowers + + # الدالة "super" تتيح لك الوصول لعمليات القالب الأب + # التي تم تغييرها عن طريق الابن، في هذه الحالة، العملية __init__< + # هذا السطر يُنادي على منشيء القالب الأب. + super().__init__(name) + + # تعديل العملية sing + def sing(self): + return 'Dun, dun, DUN!' + + # إضافة عملية جديدة للنسخة + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # فحص نوع النسخة + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') + + # إحصل على ترتيب قرار البحث للعملية (Method Resolution search Order) المُستخدمة بواسطة العمليات getattr() و super() + # هذه الصفة ديناميكية ويمكن أن تُحَدًث. + print(Superhero.__mro__) # => (, + # => , ) + + # نادي العملية الأب لكن استخدم صفات القالب الخاص بها. + print(sup.get_species()) # => Superhuman + + # نادي العملية المُعدلة. + print(sup.sing()) # => Dun, dun, DUN! + + # نادي العملية من القالب Human + sup.say('Spoon') # => Tick: Spoon + + # نادي عملية موجودة فقط في Superhero + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # وَرَثَ صفات القالب + sup.age = 31 + print(sup.age) # => 31 + + # صفة موجودة فقط في القالب Superhero + print('Am I Oscar eligible? ' + str(sup.movie)) + +#################################################### +## 6.2 الإرث المُتعدد +#################################################### + +# تعريف قالب أخرA +# bat.py +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # هذا القالب لديه عملية تسمى say + def say(self, msg): + msg = '... ... ...' + return msg + + # ولديه عمليته الخاصة به أيضا + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + +# تعريف قالب أخر يرث من Superhero و Bat +# superhero.py +from superhero import Superhero +from bat import Bat + +# عَرٍف Batman كقالب ابن يرث من كلا من Superhero و Bat +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # عادة لكي ترث صفة يجد أن تنادي على super: + # super(Batman, self).__init__(*args, **kwargs) + # لكننا في هذه الحالة نتعامل مع إرث متعدد هنا، و super() + # تعمل فقط مع القالب التالي في قائمة ال MRO. + # لذا بدلا من ذلك ننادي على __init__ صراحة لكل الأباء. + # استخدام *args و **kwargs يتيح طريقة نظيفة لتمرير المعطيات. + # لكل أب "تقشير طبقة من البصل". + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # تعديل قيمة الصفة name + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # إحصل على ترتيب قرار البحث للعملية (Method Resolution search Order) المُستخدمة بواسطة العمليات getattr() و super() + # هذه الصفة ديناميكية ويمكن أن تُحَدًث. + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + # نادي على العملية الخاصة بالأب لكن استخدم الصفات الخاصة بالقالب الابن + print(sup.get_species()) # => Superhuman + + # نادي على العملية المُعدلة + print(sup.sing()) # => nan nan nan nan nan batman! + + # نادي على العملية من القالب Human, لأن الترتيب في الأرث مهم. + sup.say('I agree') # => Sad Affleck: I agree + + # نادي على العملية الموجودة فقط في القالب الأب الثاني + print(sup.sonar()) # => ))) ... ((( + + # الصفة الموروثة من القالب الأب + sup.age = 100 + print(sup.age) # => 100 + + # الصفة الموروثة من القالب الأب الثاني، الذي تم تعديل قيمته الافتراضية + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False + + + +#################################################### +## 7. مُتَقدم +#################################################### + +# المولدات تُساعدك على كتابة كود كسول. +def double_numbers(iterable): + for i in iterable: + yield i + i + +# المولدات فعالة من حيث الذاكرة، لأنها تُحمٍل الذاكرة بالبيانات التي تحتاج +# لإجراء العملية عليها في الخطوة التالية في المُكَرِر. +# هذا يتيح إجراء عمليات على قيم كبيرة ممنوعة في حالات أخرى. +# ﻻحظ: `range` بديل ل `xrange` في بايثون 3. +for i in double_numbers(range(1, 900000000)): # `range` is a generator. + print(i) + if i >= 30: + break + +# كما يمكنك إنشاء قوائم اشتمال، يمكنك إنشاء مولدات اشتمال أيضا +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# يمكنك أيضا تغيير نوع مولد الاشتمال مباشرة إلي قائمة +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# المُحسنات +# في هذا المثال الدالة`beg` تُغلف الدالة `say`. +# إذا كانت say_please تساوي True +# إذا ستُغير الرسالة الراجعة من الدالة +from functools import wraps + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +``` + +## جاهز للمزيد? + +### مجانا عبر الانترنت + +* [أتمتتة المهمات المُملة عبر بايثون](https://automatetheboringstuff.com) +* [أفكار لمشروعات بلغة البايثون](http://pythonpracticeprojects.com) +* [التوثيقات الرسمية](http://docs.python.org/3/) +* [دليل المُسافر لبايثون](http://docs.python-guide.org/en/latest/) +* [دورة بايثون](http://www.python-course.eu/index.php) +* [أولى الخطوات مع بايثون](https://realpython.com/learn/python-first-steps/) +* [قائمة مُختارة من إطارات عمل بايثون الرائعة, المكتبات والبرمجيات](https://github.com/vinta/awesome-python) +* [ثلاثون خاصية وخدعة للغة البايثون ربما لم تعرف بها](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [الدليل الرسمي لنمط البايثون](https://www.python.org/dev/peps/pep-0008/) +* [بايثون 3 دوائر علوم الحاسب](http://cscircles.cemc.uwaterloo.ca/) +* [غُص في بايثون 3](http://www.diveintopython3.net/index.html) +* [دورة سريعة في البايثون للعلماء](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/ar-ar/python3-ar.html.markdown b/ar-ar/python3-ar.html.markdown deleted file mode 100644 index e1a12690..00000000 --- a/ar-ar/python3-ar.html.markdown +++ /dev/null @@ -1,1019 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["evuez", "http://github.com/evuez"] - - ["Rommel Martinez", "https://ebzzry.io"] - - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] -translators: - - ["Ahmad Hegazy", "https://github.com/ahegazy"] -lang: ar-ar -filename: learnpython3-ar.py ---- - -لقد أُنشئت لغة البايثون بواسطة جايدو ڤان روسم في بداية التسعينات. هي الأن أحد أشهر اللغات الموجودة. -لقد أحببت لغة البايثون بسبب وضوحها. هي في الأساس عبارة عن سودوكود قابل للتنفيذ. - -ردود أفعالكم عن المقال مُقدرة بشدة. يمكنكم التواصل مع الكاتب الاساسي من خلال [@louiedinh](http://twitter.com/louiedinh) أو louiedinh [at] [google's email service] - -ملحوظة: هذا المقال يُطبق على بايثون 3 فقط. راجع المقال [هنا](http://learnxinyminutes.com/docs/python/) إذا أردت تعلم لغة البايثون نسخة 2.7 الأقدم - -```python - -# تعليق من سطر واحد يبدأ برمز الرقم. - -""" يمكن كتابة تعليق يتكون من أكثر من سطر - باستخدام ثلاثة علامات " - ، وعادة يُستخدم في كتابة التوثيقات. -""" - -#################################################### -## 1. أنواع البيانات البدائية والعمليات -#################################################### - -# لديك أرقام -3 # => 3 - -# العمليات الحسابية هي ما تتوقعه -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 - -# نتائج قسمة الأرقام الصحيحية تُقرب للأصغر سواءًا كانت الأرقام موجبة أو سالبة. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # يعمل في حالة الكسور أيضا --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# ناتج القسمة هو دائما كسر -10.0 / 3 # => 3.3333333333333335 - -# عملية باقي القسمة -7 % 3 # => 1 - -# الأُس (س ** ص، رفع س لقوى ص) -2**3 # => 8 - -# أفرض ترتيب العمليات الحسابية بالأقواس -(1 + 3) * 2 # => 8 - -# القيم الثنائية هي المعروفة عموما (ﻻحظ: تكبير أول حرف) -True -False - -# أنفي بـ (not) -not True # => False -not False # => True - -# العمليات على القيم الثنائية -# ﻻحظ ﻻيهم حالة الحرف (كبير أو صغير) في "and" و "or" -True and False # => False -False or True # => True - -# True و False هما في الواقع 1 و 0 لكن بمسميات مختلفة -True + True # => 2 -True * 8 # => 8 -False - 5 # => -5 - -# عمليات المقارنة تنظر الي القيمة الرقمية لل True وال False -0 == False # => True -1 == True # => True -2 == True # => False --5 != False # => True - -# عند استخدام المنطق الثنائي على القيم الصحيحة يتم تحويلهم الي قيم ثنائية لإجرات العمليات عليهم، لكن قيمهم الأصلية تعود -# ﻻ تخلط بين bool(قيمة صحيحة) و العمليات المنطقية الثناية and/or (&,|) -bool(0) # => False -bool(4) # => True -bool(-6) # => True -0 and 2 # => 0 --5 or 0 # => -5 - -# مقارنة التساوي ب == -1 == 1 # => True -2 == 1 # => False - -# مقارنة الاختلاف ب != -1 != 1 # => False -2 != 1 # => True - -# مقارنات أخرى -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# لمعرفة هل القيمة في نطاق معين -1 < 2 and 2 < 3 # => True -2 < 3 and 3 < 2 # => False - -# التسلسل يجعلها تبدو أجمل -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# (is مقابل ==) is تتحق من أن المتغيرين يشيران إلي نفس العنصر, -# لكن == تتحقق من أن العنصرين المُشار اليهما بالمتغيرين لهما نفس القيمة. -a = [1, 2, 3, 4] # اجعل a تشير إلي قائمة جديدة, [1, 2, 3, 4] -b = a # اجعل a تُشير الي ما تُشير إليه b -b is a # => True, a و b يُشيران إلي نفس العنصر -b == a # => True, قيمة عنصر a و b متساوية -b = [1, 2, 3, 4] # اجعل b تشير الي قائمة جديدة , [1, 2, 3, 4] -b is a # => False, a و b do ﻻ يشيران إلي نفس العنصر -b == a # => True, قيمة عنصر a و b متساوية - -# يمكنك إنشاء الكلمات (تسلسلات الحروف) عن طريق " أو ' -"This is a string." -'This is also a string.' - -# يمكنك جمع هذا النوع أيضا! لكن حاول ألا تفعل هذا. -"Hello " + "world!" # => "Hello world!" -# يمكنك الربط بين الكلمات بدون استخدام '+' (لكن ليس المتغيرات) -"Hello " "world!" # => "Hello world!" - -# يمكنك معاملة الكلمات كقائمة من الحروف -"This is a string"[0] # => 'T' - -# يمكنك معرفة طول الكلمة -len("This is a string") # => 16 - -# .format يمكنك استخدامها لبناء الجمل بشكل معين, مثل هذا: -"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" - -# يمكنك تكرار معاملات بناء الجملة لتقليل الكتابة. -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# يمكنك استخدام الكلمات المفتاحية إذا لم تُرد العد. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" - -# إذا كان كود بايثون 3 الخاص بك يحتاج لبايثون 2.5 أو نسخة أقدم -# يمكنك استخدام أسلوب بناء الجمل القديم: -"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" - -# يمكنك أبضا بناء الجمل باستخدام f-strings أو حروف بناء الجمل (في بايثون 3.6 فما فوق) -name = "Reiko" -f"She said her name is {name}." # => "She said her name is Reiko" -# يمكنك ببساطة وضع أي كود بايثون داخل أقواس وستقوم بإخراج الجملة. -f"{name} is {len(name)} characters long." - - -# None عبارة عن كائن -None # => None - -# ﻻ تستخدم رمز المساواة "==" لمقارنة العناصر ب None -# استخدم is بدلا منه. يقوم بالتحقق من مساواة هوية العنصر -"etc" is None # => False -None is None # => True - -# None, 0, قوائم/جمل/قواميس/صفوف فارغة كلها تُترجم إلي False. -# كل القيم الأخرى True. -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False - -#################################################### -## 2. المتغيرات والمجموعات -#################################################### - -# بايثون لديها دالة عرض "print" -print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! - -# الافتراضي دالة print تطبع سطر جديد في النهاية. -# استخدم المعامل end لتغيير أخر الجملة المعروضة. -print("Hello, World", end="!") # => Hello, World! - -# طريقة بسيطة لطلب مدخل من الطرفية -input_string_var = input("Enter some data: ") # يقوم بإعادة البيانات ك "string" -# لاحظ: في النسخ القديمة من بايثون، دالة input() كان اسمها raw_input() - -# ﻻ يوجد تعريفات للمتغيرات، يتم تعيين قيمة المتغير مباشرة. -# العٌرف تسمية المتغيرات حروف_صغيرة_مع_خطوط_سُفلية -some_var = 5 -some_var # => 5 - -# محاولة استخدام متغير غير مُعين يعتبر خطأ -# إقرأ جزء 3.مسار التحكم لمعرفة المزيد عن التحكم في الأخطاء -some_unknown_var # يعرض خطأ NameError - -# يمكن استخدام if كتعبير واحد -# مساوِ للتعبير الأتي في لغة السي '?:' عملية ثلاثية -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# القوائم تحفظ المتسلسلات -li = [] -# يمكنك البدأ بقائمة مليئة -other_li = [4, 5, 6] - -# إضافة بيانات لأخر القائمة عن طريق append -li.append(1) # li is now [1] -li.append(2) # li is now [1, 2] -li.append(4) # li is now [1, 2, 4] -li.append(3) # li is now [1, 2, 4, 3] -# حذف أخر عنصر في القائمة عن طريق pop -li.pop() # => 3 and li is now [1, 2, 4] -# هيا نعيده ثانية -li.append(3) # li is now [1, 2, 4, 3] again. - -# يمكنك الوصول لعناصر القائمة كما تفعل في ال array -# Access a list like you would any array -li[0] # => 1 -# للوصول لأخر عنصر -li[-1] # => 3 - -# محاولة الوصول لعنصر خارج نطاق القائمة يعتبر خطأ: IndexError -li[4] # يعرض خطأ IndexError - -# يمكنك النظر للنطاقات باستخدام تركيب التقطيع -# مؤشر/رقم/فهرس البداية مُضمن، مؤشر النهاية ﻻ -# (لمحبي الرياضيات هو نطاق مفتوح/مغلق) -li[1:3] # => [2, 4] -# إحذف أول عنصر ثم إعرض القائمة -li[2:] # => [4, 3] -# إحذف أخر عنصر ثم إعرض القائمة -li[:3] # => [1, 2, 4] -# حدد عنصر ثم إحذف الذي يليه ثم حدد عنصر وهكذا -li[::2] # =>[1, 4] -# اعرض نسخة معكوسة من القائمة -li[::-1] # => [3, 4, 2, 1] -# إستخدم أي تجميعة من الطرق المذكورة لعمل تقطيعات متقدمة -# li[start:end:step] - -# عمل نسخة من طبقة واحدة باستخدم التقطيع -li2 = li[:] # => li2 = [1, 2, 4, 3] لكن عند عمل(li2 is li) سينتج False. - -# إمسح أي عنصر من القائمة باستخدام "del" -del li[2] # li is now [1, 2, 3] - -# إمسح أول ظهور لقيمة. -li.remove(2) # li is now [1, 3] -li.remove(2) # يعرض خطأ ValueError لأن 2 غير موجود في القائمة - -# أضف عنصر في خانة معينة -li.insert(1, 2) # li is now [1, 2, 3] مرة أخرى - -# أحصل على مؤشر/رقم لأول ظهور للقيمة -li.index(2) # => 1 -li.index(4) # يعرض خطأ ValueError لأن 4 غير موجودة في القائمة - -# يمكنك جمع قوائم -# لاحظ: لا يتم تعديل قيمة li و other_li -li + other_li # => [1, 2, 3, 4, 5, 6] - -# إستخدم دالة "extend()" لربط القوائم -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] - -# راجع وجود قيمة في القائمة باستخدام "in" -1 in li # => True - -# إحصل على طول القائمة باستخدام دالة "len()" -len(li) # => 6 - - -# الصفوف تشبه القوائم لكنها غير قابلة للتغيير. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # يعرض خطأ TypeError - -# لاحظ أن صف طوله عنصر واحد يحتاج لإضافة فاصلة "," بعد أخر عنصر -# لكن الصفوف من أي طول أخر، حتى صفر لا تحتاج. -type((1)) # => -type((1,)) # => -type(()) # => - -# يمكنك عمل معظم عمليات القوائم على الصفوف. -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# يمكنك تفريغ الصفوف (أو القوائم) في متغيرات -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 -# يمكنك أيضا عمل تفريغ واسع -a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 -# الصفوف تُنشأ تلقائيا إذا تركت الأقواس -d, e, f = 4, 5, 6 # تم توسعة الصف 4, 5 ,6 في المتغيرات d, e, f -# بالترتيب حيث d = 4, e = 5 و f = 6 -# الأن إنظر إلي مدى سهولة التبديل بين قيم متغيرين -e, d = d, e # d is now 5 and e is now 4 - - -# القواميس تُخزن خرائط من المفتاح للقيمة -empty_dict = {} -# هذا قاموس مملوء -filled_dict = {"one": 1, "two": 2, "three": 3} - -# لاحظ أن القواميس يجب أن تكون أنواع غير قابلة للتغيير. -# هذا للتأكد من أن المفتاح يمكن تحويله لقيمة ثابتة للوصول السريع. -# الأنواع الغير قابلة للتغير تتضمن: الأرقام الصحيحة، الكسور، الكلمات، الصفوف. -invalid_dict = {[1,2,3]: "123"} # =>يعرض خطأ TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # القيم يمكن أن تكون من أي نوع. - -# يمكنك البحث عن قيمة باستخدام [] -filled_dict["one"] # => 1 - -# يمكنك الحصول على كل المفاتيح باستخدام "keys()". -# نحتاج لإرسالها لدالة list() لتحويلها لقائمة. سنتعلم هذا لاحقًا -# لاحظ - لنسخ بايثون قبل 3.7، ترتيب مفاتيح القاموس غير مضمون. نتائجك -# يمكن ألا تساوي المثال بالأسفل. مع ذلك، من أول بايثون 3.7، -# عناصر القاموس تحتفظ بالترتيب الذي تم إضافة المفاتيح به في القاموس. -list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7 -list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+ - -# يمكنك الحصول على كل القيم باستخدام "values()". -# مرة أخرى نستخدم list() للحصول عليها كقائمة. -# نفس الكلام السابق بخصوص ترتيب المفاتيح -list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 -list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ - -# إفحص للتأكد من وجود مغتاح في القاموس باستخدام "in" -"one" in filled_dict # => True -1 in filled_dict # => False - -# البحث عن مفتاح غير موجود يعرض خطأ KeyError -filled_dict["four"] # KeyError - -# استخدم "get()" لتجنب الخطأ KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# دالة get تدعم إدخال قيمة افتراضية عند عدم وجود البحث -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# "setdefault()" تقوم بإدخال قيمة جديدة في القاموس في حالة عدم وجود المفتاح فقط. -filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 - -# إضافة عنصر للقاموس -filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -filled_dict["four"] = 4 # طريقة أخرى للإضافة - -# مسح المفاتيح من القاموس باستخدام del -del filled_dict["one"] # Removes the key "one" from filled dict - -# من بايثون 3.5 فما فوق يمكنك أيضا استخدام خيارات تفريغ إضافية -{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} -{'a': 1, **{'a': 2}} # => {'a': 2} - - -# المجموعات تُخزن .. مجموعات -empty_set = set() -# .تهيئة مجموعة بمجموعة قيم. نعم، تشبه قليلا تهيئة القاموس. أسف -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} - -# مثل مفتاح القاموس، عناصر المجموعة يجب أن تكون غير قابلة للتغيير. -invalid_set = {[1], 1} # => يعرض خطأ TypeError: unhashable type: 'list' -valid_set = {(1,), 1} - -# إضافة عنصر أخر للمجموعة -filled_set = some_set -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} -# المجموعات لا يمكن أن تحتوي على عناصر مكررة -filled_set.add(5) # it remains as before {1, 2, 3, 4, 5} - -# تقاطع مجموعتين باستخدام & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# اتحاد مجموعتين باستخدام | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# الفرق بين مجموعتين باستخدام - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# الفروق بين مجموعتين باستخدام ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# لفحص هل المجموعة على اليسار مجموعة عُليا للمجموعة على اليمين (تحتوي على كل عناصرها) -{1, 2} >= {1, 2, 3} # => False - -# لفحص هل المجموعة على اليسار مجموعة فرعية من المجموعة على اليمين -{1, 2} <= {1, 2, 3} # => True - -# للتأكد من وجود عن في مجموعة استخدم in -2 in filled_set # => True -10 in filled_set # => False - - - -#################################################### -## 3. مسار التحكم والعمليات التكرارية #Control Flow and Iterables -#################################################### - -# هيا ننشيء متغير -some_var = 5 - -# الأن الأمر if. الفجوات (المسافات قبل الأوامر) مهمة في البايثون! -# العُرف استخدام أربع مسافات. ليس تبويب. -# هذا السطر البرمجي يطبع "some_var is smaller than 10" -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # This elif clause is optional. - print("some_var is smaller than 10.") -else: # This is optional too. - print("some_var is indeed 10.") - - -""" -For عبارة عن حلقات تدور حول عناصر قوائم -:ثم تطبع - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # يمكنك استخدام format() لترجمة كلمات بشكل معين. - print("{} is a mammal".format(animal)) - -""" -"range(number)" يقوم بإعادة مجموعة من الأرقام يمكن الدوران حولها -من الصفر إلي رقم معين -ثم يطبع: - 0 - 1 - 2 - 3 -""" - -for i in range(4): - print(i) - -""" -"range(lower, upper)" يقوم بإعادة مجموعة من الأرقام يمكن الدوران حولها من القيمة السُفلى -lower حتى القيمة العُليا upper -ثم يطبع: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(lower, upper, step)" يقوم بإعادة مجموعة من الأرقام يمكن الدوران حولها من القيمة السُفلى -lower حتى القيمة العُليا upper، ثم يقوم بالزيادة قيمة الstep. -إذا لم تُحدد ال step, القيمة الأفتراضية 1. -ثم يطبع: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) - -""" -While هي عبارة عن حلقات تدور حتى عدم تحقق شرط معين. -وتطبع: - 0 - 1 - 2 - 3 -""" -x = 0 for -while x < 4: - print(x) - x += 1 # اختصار ل x = x + 1 - -# يمكنك التحكم في الأخطاء والاستثناءات باستخدام مجموعة try/except -try: - # استخدم "raise" لرفع خطأ. - raise IndexError("This is an index error") -except IndexError as e: - pass # Pass: هو مجرد أمر ﻻ تفعل شيء. عادة تقوم بتصحيح الخطأ هنا. -except (TypeError, NameError): - pass # يمكنك التحكم في أكثر من خطأ في نفس الوقت، إذا أقتضت الضرورة -else: # فقرة اختيارية في مجموعة try/except. يجب أن يتبع جميع مجموعات معارضة الأخطاء - print("All good!") # تُنفذ في حالة أن السطور البرمجية داخل ال try لم ترفع أي خطأ -finally: # تُنفذ في كل الحالات - print("We can clean up resources here") - -# بدلا من مجموعة try/finally لتنظيف الموارد يمكنك استخدام سطر with -with open("myfile.txt") as f: - for line in f: - print(line) - -# يتيح البايثون تجريد أساسي يسمى المُكرَر. -# المُكرٍَر عبارة عن متغير يمكن التعامل معه كسلسلة. -# الكائن الذي يعود من دالة نطاق، يسمى المُكرَر. - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']) -# هذا عبارة عن متغير يعرض عناصر مفاتيح المُكرَر. - -# يمكننا الدوران حوله. -for i in our_iterable: - print(i) # Prints one, two, three - -# مع ذلك ﻻ يمكننا الوصول للعناصر بالمؤشر. -our_iterable[1] # يرفع خطأ TypeError - -# المُكرَر هو عبارة عن عنصر يعلم كيفية إنشاء مُكرِر -our_iterator = iter(our_iterable) - -# المُكرِر هو عبارة عن عنصر يمكنه تذكر الحالة أثناء مرورنا بعناصره. -# يمكننا الحصول على العنصر التالي عن طريق "next()" -next(our_iterator) # => "one" - -# يحفظ الحالة أثناء الدوران. -next(our_iterator) # => "two" -next(our_iterator) # => "three" - -# بعد عرض المُكرِر كل عناصره، يرفع استثناء StopIteration -next(our_iterator) # يرفع StopIteration - -# يمكنك الحصول على كل عناصر المُكرر بمناداة دالة list() عليه. -list(filled_dict.keys()) # => Returns ["one", "two", "three"] - - -#################################################### -## 4. الدوال -#################################################### - -# إستخدم "def" لإنشاء دوال جديدة. -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # يمكنك إرجاع قيمة من الدالة بسطر return - -# مناداة دوال بمعطيات -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 - -# طريقة أخرى لمناداة دوال باستخدام كلمات مفتاحية. -add(y=6, x=5) # الكلمة المفتاحية يمكن أن تُعطى بأي ترتيب. - -# يمكنك تعريف دوال تأخذ عدد متغير من المُعطيات - -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# يمكنك تعريف دوال تأخذ عدد متغير من الكلمات المفتاحية كمعطيات أيضا. -def keyword_args(**kwargs): - return kwargs - -# هيا ننادي على الدالة لنرى ماذا سيحدث -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# يمكنك فعل الأثنين معًا في نفس الوقت، إذا أردت -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) prints: - (1, 2) - {"a": 3, "b": 4} -""" - -# عندما تنادي على دوال، يمكنك عمل عكس المعطيات/المفاتيح! -# استخدم * لتوسعة الصفوف، واستخدم ** لتوسعة المفاتيح. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # مساوٍ ل all_the_args(1, 2, 3, 4) -all_the_args(**kwargs) # مساوٍ ل to all_the_args(a=3, b=4) -all_the_args(*args, **kwargs) # مساوٍ ل to all_the_args(1, 2, 3, 4, a=3, b=4) - -# يقوم بإعادة مجموعة من القيم (بتعيين الصفوف) -def swap(x, y): - return y, x # يقوم بإعادة مجموعة من القيم على شكل صفوف بدون الأقواس - # (لاحظ: الأقواس حُذفت لكن يمكن إضافتها) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # مرة أخرى الأقواس حُذفت لكن يمكن إضافتها. - -# مجال الدالة -x = 5 - -def set_x(num): - # المتغير المحلي x ليس هو المتغير العام x - x = num # => 43 - print(x) # => 43 - -def set_global_x(num): - global x - print(x) # => 5 - x = num #المتغير العام x الأن مساوٍ ل 6 - print(x) # => 6 - -set_x(43) -set_global_x(6) - - -# بايثون تدعم دوال الفئة أولية [first class functions] (أي أنه يمكن إرسال الدوال كمعطيات لدوال أخرى) -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# يوجد أيضا دوال مجهولة -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# يوجد دوال مدمجة من درجة أعلى -list(map(add_10, [1, 2, 3])) # => [11, 12, 13] -list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] - -list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] - -# يمكن إشتمال القوائم على خرائط وفلاتر حسنة الشكل -# هذه القوائم تحفظ المُخرج كقائمة والتي بدورها يمكن أن تكون قائمة مداخلة -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# يمكنك بناء مجموعات وقواميس على هذا المنوال أيضا -{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} -{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -## 5. الوحدات البرمجية (الموديولات) -#################################################### - -# يمكنك استدعاء موديولات -import math -print(math.sqrt(16)) # => 4.0 - -# يمكنك استدعاء دالة معينة من موديول -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# يمكنك استدعاء كل الدوال من مديول. -# تحذير: هذا الفعل غير موصى به -from math import * - -# يمكنك تصغير اسم موديول -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# موديولات البايثون عبارة عن ملفات بايثون عادية. -# يمكنك كتابة الموديولات الخاصة بك, واستدعاها. -# اسم الموديول يكون نفس اسم الملف. - -# يمكنك معرفة أي الدوال والصفات مُعرفة في الموديول. -import math -dir(math) - -# إذا كان لديك سكربت بايثون يسمى math.py -# في نفس المجلد الموجود به السكربت الخاص بك، الملف الخاص بك math.py -# سَيُستدعى بدلا من موديول البايثون بنفس الاسم -# هذا يحدث لأن المجلدات المحلية لديها أولوية عن مكتبات البايثون المُدمجة - - -#################################################### -## 6. الفئات/القوالب (الكلاسات) -#################################################### - -# نستخدم السطر البرمجي "class" لإنشاء قالب -class Human: - - # صفة القالب. مشتركة بين كل نسخ القالب - species = "H. sapiens" - - # مُهيئ إبتدائي، يُنادى عليه عندما يتم استدعاء القالب. - # لاحظ أن الشرطة السٌفلية المُكررة مرتين __ قبل وبعد الاسم تُعبر عن الكائنات - # أو الصفات المُستخدمة عن طريق بايثون لكنها تعيش في مساحة تحكم المُستخدم. - # العمليات -الدوال- (أو الكائنات أو الصفات) مثل: __init__, __str__,__repr__ ألخ. - # تُسمى عمليات خاصة (أو أحيانا تسمى عمليات سحرية أو dunder methods) - # يجب عليك ألا تُسمي مثل هذه الاسماء بنفسك. - def __init__(self, name): - # ساوِ المُعطى بالصفة name الخاصة بهذه النسخة من القالب. - self.name = name - - # هيئ الصفة - self._age = 0 - - # عملية/دالة خاصة بنسخة القالب. كل العمليات تأخذ "self" كأول مُعطى - # An instance method. All methods take "self" as the first argument - def say(self, msg): - print("{name}: {message}".format(name=self.name, message=msg)) - - # عملية أخرى خاصة بنسخة القالب. - def sing(self): - return 'yo... yo... microphone check... one two... one two...' - - # عمليات القالب مشتركة بين كل أجزاء القالب - # يتم مناداتهم عن طريق جعل القالب المُنادي أول معطى - # They are called with the calling class as the first argument - @classmethod - def get_species(cls): - return cls.species - - # تُنادى العملية الثابتة بدون قالب أو نسخة قالب - @staticmethod - def grunt(): - return "*grunt*" - - # الخاصية تشبه تماما إمر الطلب - # تُحَوِل العملية age() إلي صفة مقروءة فقط بنفس الاسم. - # ﻻ حاجة لكتابة أوامر طلب أو تهيئة - @property - def age(self): - return self._age - - # هذا يتيح تهيئة الخاصية - @age.setter - def age(self, age): - self._age = age - - # هذا يتيح حذف الخاصية - @age.deleter - def age(self): - del self._age - - -# عندما يقرأ مُترجم البايثون ملف مصدري يقوم بتنفيذ كل الكود. -# فحص ال __name__ يجعل هذا الجزء من الكود يُنَفَذ فقط -# في حالة أن هذا الموديول هو البرنامج الرئيسي -if __name__ == '__main__': - # Instantiate a class - i = Human(name="Ian") - i.say("hi") # "Ian: hi" - j = Human("Joel") - j.say("hello") # "Joel: hello" - # i و j نُسخ من النوع Human, أول بكلمات أخرى: هما كائنات للقالب Human - - # نادي على عملية القالب - i.say(i.get_species()) # "Ian: H. sapiens" - # عدل الخاصية المُشتركة - Human.species = "H. neanderthalensis" - i.say(i.get_species()) # => "Ian: H. neanderthalensis" - j.say(j.get_species()) # => "Joel: H. neanderthalensis" - - # نادي على العملية الثابتة - print(Human.grunt()) # => "*grunt*" - - # لا يمكن مناداة العملية الثابتة من نسخة الكائن - # لأن i.grunt() سيقوم تلقائيا بوضع "self" (الكائن i) كمُعطى للعملية - print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given - - # حدًث الخاصية لهذه النسخة - i.age = 42 - # أحصل على الخاصية - i.say(i.age) # => "Ian: 42" - j.say(j.age) # => "Joel: 0" - # إحذف الخاصية - del i.age - # i.age # => سوف يرفع استثناء AttributeError - - -#################################################### -## 6.1 الإرث -#################################################### - -# الإرث يتيح لقالب ابن أن يُعَرف ويرث بعض عمليات/دوال ومتغيرات القالب الأب. - -# باستخدام القالب Human المُعَرف بالأعلى كأساس أو كقالب أب، -# يمكننا تعريف قالب ابن،Superhero ، يرث متغيرات القالب مثل "species", "name", و "age"، -# وأيضا العمليات، مثل "sing", "grunt" -# من القالب Human، لكنه أيضا لديه خواصه الفريدة - -# للاستفادة من التقطيع بالملف يمكنك وضع القوالب بالأعلى في ملفاتهم الخاصة، -# مثلا، human.py - -# لاستيراد دالة من ملف أخر استخدم الطريقة التالية -# from "اسم الملف بدون مُلحق" import "اسم الدالة أو القالب" - -from human import Human - -# حدد القالب/ات الأب كمُعطى أثناء تعريف القالب. -class Superhero(Human): - - # إذا أردت أن يرث القالب الابن كل تعريفات القالب الأب بدون تعديل - # يمكنك استخدام الكلمة المفتاحية "pass" (بدون شيء أخر) - # لكن في هذه الحالة تم أهمالها لإنشاء قالب ابن فريد: - # pass - - # القوالب الابن يمكنها تعديل صفات القوالب الأب - species = 'Superhuman' - - # القوالب الابن ترث تلقائيا عمليات الإنشاء الخاصة بالقالب الأب بالإضافة إلي مُعطياتهم - # لكن يمكن أيضا تعريف مُعطيات إضافية أو تعريفات - # وتعديل العمليات مثل منشيء القالب. - # هذا المُنشيء يرث المُعطى "name" من القالب "Human" - # ويضيف المعطيات"superpower" و "movies": - def __init__(self, name, movie=False, - superpowers=["super strength", "bulletproofing"]): - - # إضافة صفة جديدة للقالب - self.fictional = True - self.movie = movie - # كن على علم بالقيم الافتراضية المتغيرة، حيث أن القيم الافتراضية تُشارك - self.superpowers = superpowers - - # الدالة "super" تتيح لك الوصول لعمليات القالب الأب - # التي تم تغييرها عن طريق الابن، في هذه الحالة، العملية __init__< - # هذا السطر يُنادي على منشيء القالب الأب. - super().__init__(name) - - # تعديل العملية sing - def sing(self): - return 'Dun, dun, DUN!' - - # إضافة عملية جديدة للنسخة - def boast(self): - for power in self.superpowers: - print("I wield the power of {pow}!".format(pow=power)) - - -if __name__ == '__main__': - sup = Superhero(name="Tick") - - # فحص نوع النسخة - if isinstance(sup, Human): - print('I am human') - if type(sup) is Superhero: - print('I am a superhero') - - # إحصل على ترتيب قرار البحث للعملية (Method Resolution search Order) المُستخدمة بواسطة العمليات getattr() و super() - # هذه الصفة ديناميكية ويمكن أن تُحَدًث. - print(Superhero.__mro__) # => (, - # => , ) - - # نادي العملية الأب لكن استخدم صفات القالب الخاص بها. - print(sup.get_species()) # => Superhuman - - # نادي العملية المُعدلة. - print(sup.sing()) # => Dun, dun, DUN! - - # نادي العملية من القالب Human - sup.say('Spoon') # => Tick: Spoon - - # نادي عملية موجودة فقط في Superhero - sup.boast() # => I wield the power of super strength! - # => I wield the power of bulletproofing! - - # وَرَثَ صفات القالب - sup.age = 31 - print(sup.age) # => 31 - - # صفة موجودة فقط في القالب Superhero - print('Am I Oscar eligible? ' + str(sup.movie)) - -#################################################### -## 6.2 الإرث المُتعدد -#################################################### - -# تعريف قالب أخرA -# bat.py -class Bat: - - species = 'Baty' - - def __init__(self, can_fly=True): - self.fly = can_fly - - # هذا القالب لديه عملية تسمى say - def say(self, msg): - msg = '... ... ...' - return msg - - # ولديه عمليته الخاصة به أيضا - def sonar(self): - return '))) ... (((' - -if __name__ == '__main__': - b = Bat() - print(b.say('hello')) - print(b.fly) - -# تعريف قالب أخر يرث من Superhero و Bat -# superhero.py -from superhero import Superhero -from bat import Bat - -# عَرٍف Batman كقالب ابن يرث من كلا من Superhero و Bat -class Batman(Superhero, Bat): - - def __init__(self, *args, **kwargs): - # عادة لكي ترث صفة يجد أن تنادي على super: - # super(Batman, self).__init__(*args, **kwargs) - # لكننا في هذه الحالة نتعامل مع إرث متعدد هنا، و super() - # تعمل فقط مع القالب التالي في قائمة ال MRO. - # لذا بدلا من ذلك ننادي على __init__ صراحة لكل الأباء. - # استخدام *args و **kwargs يتيح طريقة نظيفة لتمرير المعطيات. - # لكل أب "تقشير طبقة من البصل". - Superhero.__init__(self, 'anonymous', movie=True, - superpowers=['Wealthy'], *args, **kwargs) - Bat.__init__(self, *args, can_fly=False, **kwargs) - # تعديل قيمة الصفة name - self.name = 'Sad Affleck' - - def sing(self): - return 'nan nan nan nan nan batman!' - - -if __name__ == '__main__': - sup = Batman() - - # إحصل على ترتيب قرار البحث للعملية (Method Resolution search Order) المُستخدمة بواسطة العمليات getattr() و super() - # هذه الصفة ديناميكية ويمكن أن تُحَدًث. - print(Batman.__mro__) # => (, - # => , - # => , - # => , ) - - # نادي على العملية الخاصة بالأب لكن استخدم الصفات الخاصة بالقالب الابن - print(sup.get_species()) # => Superhuman - - # نادي على العملية المُعدلة - print(sup.sing()) # => nan nan nan nan nan batman! - - # نادي على العملية من القالب Human, لأن الترتيب في الأرث مهم. - sup.say('I agree') # => Sad Affleck: I agree - - # نادي على العملية الموجودة فقط في القالب الأب الثاني - print(sup.sonar()) # => ))) ... ((( - - # الصفة الموروثة من القالب الأب - sup.age = 100 - print(sup.age) # => 100 - - # الصفة الموروثة من القالب الأب الثاني، الذي تم تعديل قيمته الافتراضية - print('Can I fly? ' + str(sup.fly)) # => Can I fly? False - - - -#################################################### -## 7. مُتَقدم -#################################################### - -# المولدات تُساعدك على كتابة كود كسول. -def double_numbers(iterable): - for i in iterable: - yield i + i - -# المولدات فعالة من حيث الذاكرة، لأنها تُحمٍل الذاكرة بالبيانات التي تحتاج -# لإجراء العملية عليها في الخطوة التالية في المُكَرِر. -# هذا يتيح إجراء عمليات على قيم كبيرة ممنوعة في حالات أخرى. -# ﻻحظ: `range` بديل ل `xrange` في بايثون 3. -for i in double_numbers(range(1, 900000000)): # `range` is a generator. - print(i) - if i >= 30: - break - -# كما يمكنك إنشاء قوائم اشتمال، يمكنك إنشاء مولدات اشتمال أيضا -values = (-x for x in [1,2,3,4,5]) -for x in values: - print(x) # prints -1 -2 -3 -4 -5 to console/terminal - -# يمكنك أيضا تغيير نوع مولد الاشتمال مباشرة إلي قائمة -values = (-x for x in [1,2,3,4,5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - - -# المُحسنات -# في هذا المثال الدالة`beg` تُغلف الدالة `say`. -# إذا كانت say_please تساوي True -# إذا ستُغير الرسالة الراجعة من الدالة -from functools import wraps - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( -``` - -## جاهز للمزيد? - -### مجانا عبر الانترنت - -* [أتمتتة المهمات المُملة عبر بايثون](https://automatetheboringstuff.com) -* [أفكار لمشروعات بلغة البايثون](http://pythonpracticeprojects.com) -* [التوثيقات الرسمية](http://docs.python.org/3/) -* [دليل المُسافر لبايثون](http://docs.python-guide.org/en/latest/) -* [دورة بايثون](http://www.python-course.eu/index.php) -* [أولى الخطوات مع بايثون](https://realpython.com/learn/python-first-steps/) -* [قائمة مُختارة من إطارات عمل بايثون الرائعة, المكتبات والبرمجيات](https://github.com/vinta/awesome-python) -* [ثلاثون خاصية وخدعة للغة البايثون ربما لم تعرف بها](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [الدليل الرسمي لنمط البايثون](https://www.python.org/dev/peps/pep-0008/) -* [بايثون 3 دوائر علوم الحاسب](http://cscircles.cemc.uwaterloo.ca/) -* [غُص في بايثون 3](http://www.diveintopython3.net/index.html) -* [دورة سريعة في البايثون للعلماء](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/cs-cz/python.html.markdown b/cs-cz/python.html.markdown new file mode 100644 index 00000000..bd3690a8 --- /dev/null +++ b/cs-cz/python.html.markdown @@ -0,0 +1,647 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Tomáš Bedřich", "http://tbedrich.cz"] +translators: + - ["Tomáš Bedřich", "http://tbedrich.cz"] +filename: learnpython3-cz.py +lang: cs-cz +--- + +Python byl vytvořen Guidem Van Rossum v raných 90. letech. Nyní je jedním z nejpopulárnějších jazyků. +Zamiloval jsem si Python pro jeho syntaktickou čistotu - je to vlastně spustitelný pseudokód. + +Vaše zpětná vazba je vítána! Můžete mě zastihnout na [@louiedinh](http://twitter.com/louiedinh) nebo louiedinh [at] [email od googlu] anglicky, +autora českého překladu pak na [@tbedrich](http://twitter.com/tbedrich) nebo ja [at] tbedrich.cz + +Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit starší Python 2.7](http://learnxinyminutes.com/docs/python/). + +```python + +# Jednořádkový komentář začíná křížkem + +""" Víceřádkové komentáře používají tři uvozovky nebo apostrofy + a jsou často využívány jako dokumentační komentáře k metodám +""" + +#################################################### +## 1. Primitivní datové typy a operátory +#################################################### + +# Čísla +3 # => 3 + +# Aritmetické operace se chovají běžným způsobem +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Až na dělení, které vrací desetinné číslo +35 / 5 # => 7.0 + +# Při celočíselném dělení je desetinná část oříznuta (pro kladná i záporná čísla) +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # celočíselně dělit lze i desetinným číslem +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Pokud použijete desetinné číslo, výsledek je jím také +3 * 2.0 # => 6.0 + +# Modulo +7 % 3 # => 1 + +# Mocnění (x na y-tou) +2**4 # => 16 + +# Pro vynucení priority použijte závorky +(1 + 3) * 2 # => 8 + +# Logické hodnoty +True +False + +# Negace se provádí pomocí not +not True # => False +not False # => True + +# Logické operátory +# U operátorů záleží na velikosti písmen +True and False # => False +False or True # => True + +# Používání logických operátorů s čísly +0 and 2 # => 0 +-5 or 0 # => -5 + +# Při porovnání s boolean hodnotou nepoužívejte operátor rovnosti "==". +# Stejně jako u hodnoty None. +# Viz PEP8: https://www.python.org/dev/peps/pep-0008/ +0 is False # => True +2 is True # => False +1 is True # => True + +# Rovnost je == +1 == 1 # => True +2 == 1 # => False + +# Nerovnost je != +1 != 1 # => False +2 != 1 # => True + +# Další porovnání +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Porovnání se dají řetězit! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + + +# Řetězce používají " nebo ' a mohou obsahovat unicode znaky +"Toto je řetězec." +'Toto je také řetězec.' + +# Řetězce se také dají slučovat +"Hello " + "world!" # => "Hello world!" +# Dají se spojovat i bez '+' +"Hello " "world!" # => "Hello world!" + +# Řetězec lze považovat za seznam znaků +"Toto je řetězec"[0] # => 'T' + +# .format lze použít ke skládání řetězců +"{} mohou být {}".format("řetězce", "skládány") + +# Formátovací argumenty můžete opakovat +"{0} {1} stříkaček stříkalo přes {0} {1} střech".format("tři sta třicet tři", "stříbrných") +# => "tři sta třicet tři stříbrných stříkaček stříkalo přes tři sta třicet tři stříbrných střech" + +# Pokud nechcete počítat, můžete použít pojmenované argumenty +"{jmeno} si dal {jidlo}".format(jmeno="Franta", jidlo="guláš") # => "Franta si dal guláš" + +# Pokud zároveň potřebujete podporovat Python 2.5 a nižší, můžete použít starší způsob formátování +"%s se dají %s jako v %s" % ("řetězce", "skládat", "jazyce C") + + +# None je objekt (jinde NULL, nil, ...) +None # => None + +# Pokud porovnáváte něco s None, nepoužívejte operátor rovnosti "==", +# použijte raději operátor "is", který testuje identitu. +"něco" is None # => False +None is None # => True + +# None, 0, a prázdný řetězec/seznam/N-tice/slovník/množina se vyhodnotí jako False +# Vše ostatní se vyhodnotí jako True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool(tuple()) # => False +bool({}) # => False +bool(set()) # => False + + +#################################################### +## 2. Proměnné a kolekce +#################################################### + +# Python má funkci print +print("Jsem 3. Python 3.") + +# Proměnné není třeba deklarovat před přiřazením +# Konvence je používat male_pismo_s_podtrzitky +nazev_promenne = 5 +nazev_promenne # => 5 +# Názvy proměnných mohou obsahovat i unicode znaky, ale nedělejte to. +# Viz PEP 3131 -- Supporting Non-ASCII Identifiers: +# https://www.python.org/dev/peps/pep-3131/ +název_proměnné = 5 + +# Přístup k předtím nedefinované proměnné vyvolá výjimku +# Odchytávání vyjímek - viz další kapitola +neznama_promenna # Vyhodí NameError + +# Seznam se používá pro ukládání sekvencí +sez = [] +# Lze ho rovnou naplnit +jiny_seznam = [4, 5, 6] + +# Na konec seznamu se přidává pomocí append +sez.append(1) # sez je nyní [1] +sez.append(2) # sez je nyní [1, 2] +sez.append(4) # sez je nyní [1, 2, 4] +sez.append(3) # sez je nyní [1, 2, 4, 3] +# Z konce se odebírá se pomocí pop +sez.pop() # => 3 a sez je nyní [1, 2, 4] +# Vložme trojku zpátky +sez.append(3) # sez je nyní znovu [1, 2, 4, 3] + +# Přístup k prvkům funguje jako v poli +sez[0] # => 1 +# Mínus počítá odzadu (-1 je poslední prvek) +sez[-1] # => 3 + +# Přístup mimo seznam vyhodí IndexError +sez[4] # Vyhodí IndexError + +# Pomocí řezů lze ze seznamu vybírat různé intervaly +# (pro matematiky: jedná se o uzavřený/otevřený interval) +sez[1:3] # => [2, 4] +# Odříznutí začátku +sez[2:] # => [4, 3] +# Odříznutí konce +sez[:3] # => [1, 2, 4] +# Vybrání každého druhého prvku +sez[::2] # =>[1, 4] +# Vrácení seznamu v opačném pořadí +sez[::-1] # => [3, 4, 2, 1] +# Lze použít jakoukoliv kombinaci parametrů pro vytvoření složitějšího řezu +# sez[zacatek:konec:krok] + +# Odebírat prvky ze seznamu lze pomocí del +del sez[2] # sez je nyní [1, 2, 3] + +# Seznamy můžete slučovat +# Hodnoty sez a jiny_seznam přitom nejsou změněny +sez + jiny_seznam # => [1, 2, 3, 4, 5, 6] + +# Spojit seznamy lze pomocí extend +sez.extend(jiny_seznam) # sez je nyní [1, 2, 3, 4, 5, 6] + +# Kontrola, jestli prvek v seznamu existuje, se provádí pomocí in +1 in sez # => True + +# Délku seznamu lze zjistit pomocí len +len(sez) # => 6 + + +# N-tice je jako seznam, ale je neměnná +ntice = (1, 2, 3) +ntice[0] # => 1 +ntice[0] = 3 # Vyhodí TypeError + +# S n-ticemi lze dělat většinu operací, jako se seznamy +len(ntice) # => 3 +ntice + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +ntice[:2] # => (1, 2) +2 in ntice # => True + +# N-tice (nebo seznamy) lze rozbalit do proměnných jedním přiřazením +a, b, c = (1, 2, 3) # a je nyní 1, b je nyní 2 a c je nyní 3 +# N-tice jsou vytvářeny automaticky, když vynecháte závorky +d, e, f = 4, 5, 6 +# Prohození proměnných je tak velmi snadné +e, d = d, e # d je nyní 5, e je nyní 4 + + +# Slovníky ukládají klíče a hodnoty +prazdny_slovnik = {} +# Lze je také rovnou naplnit +slovnik = {"jedna": 1, "dva": 2, "tři": 3} + +# Přistupovat k hodnotám lze pomocí [] +slovnik["jedna"] # => 1 + +# Všechny klíče dostaneme pomocí keys() jako iterovatelný objekt. Nyní ještě +# potřebujeme obalit volání v list(), abychom dostali seznam. To rozebereme +# později. Pozor, že jakékoliv pořadí klíčů není garantováno - může být různé. +list(slovnik.keys()) # => ["dva", "jedna", "tři"] + +# Všechny hodnoty opět jako iterovatelný objekt získáme pomocí values(). Opět +# tedy potřebujeme použít list(), abychom dostali seznam. Stejně jako +# v předchozím případě, pořadí není garantováno a může být různé +list(slovnik.values()) # => [3, 2, 1] + +# Operátorem in se lze dotázat na přítomnost klíče +"jedna" in slovnik # => True +1 in slovnik # => False + +# Přístup k neexistujícímu klíči vyhodí KeyError +slovnik["čtyři"] # Vyhodí KeyError + +# Metoda get() funguje podobně jako [], ale vrátí None místo vyhození KeyError +slovnik.get("jedna") # => 1 +slovnik.get("čtyři") # => None +# Metodě get() lze předat i výchozí hodnotu místo None +slovnik.get("jedna", 4) # => 1 +slovnik.get("čtyři", 4) # => 4 + +# metoda setdefault() vloží prvek do slovníku pouze pokud tam takový klíč není +slovnik.setdefault("pět", 5) # slovnik["pět"] je nastaven na 5 +slovnik.setdefault("pět", 6) # slovnik["pět"] je pořád 5 + +# Přidání nové hodnoty do slovníku +slovnik["čtyři"] = 4 +# Hromadně aktualizovat nebo přidat data lze pomocí update(), parametrem je opět slovník +slovnik.update({"čtyři": 4}) # slovnik je nyní {"jedna": 1, "dva": 2, "tři": 3, "čtyři": 4, "pět": 5} + +# Odebírat ze slovníku dle klíče lze pomocí del +del slovnik["jedna"] # odebere klíč "jedna" ze slovnik + + +# Množiny ukládají ... překvapivě množiny +prazdna_mnozina = set() +# Také je lze rovnou naplnit. A ano, budou se vám plést se slovníky. Bohužel. +mnozina = {1, 1, 2, 2, 3, 4} # mnozina je nyní {1, 2, 3, 4} + +# Přidání položky do množiny +mnozina.add(5) # mnozina je nyní {1, 2, 3, 4, 5} + +# Průnik lze udělat pomocí operátoru & +jina_mnozina = {3, 4, 5, 6} +mnozina & jina_mnozina # => {3, 4, 5} + +# Sjednocení pomocí operátoru | +mnozina | jina_mnozina # => {1, 2, 3, 4, 5, 6} + +# Rozdíl pomocí operátoru - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Operátorem in se lze dotázat na přítomnost prvku v množině +2 in mnozina # => True +9 in mnozina # => False + + +#################################################### +## 3. Řízení toku programu, cykly +#################################################### + +# Vytvořme si proměnnou +promenna = 5 + +# Takto vypadá podmínka. Na odsazení v Pythonu záleží! +# Vypíše "proměnná je menší než 10". +if promenna > 10: + print("proměnná je velká jak Rusko") +elif promenna < 10: # Část elif je nepovinná + print("proměnná je menší než 10") +else: # Část else je také nepovinná + print("proměnná je právě 10") + + +""" +Smyčka for umí iterovat (nejen) přes seznamy +vypíše: + pes je savec + kočka je savec + myš je savec +""" +for zvire in ["pes", "kočka", "myš"]: + # Můžete použít formát pro složení řetězce + print("{} je savec".format(zvire)) + +""" +range(cislo) vrací iterovatelný objekt čísel od 0 do cislo +vypíše: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +range(spodni_limit, horni_limit) vrací iterovatelný objekt čísel mezi limity +vypíše: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +Smyčka while se opakuje, dokud je podmínka splněna. +vypíše: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Zkrácený zápis x = x + 1. Pozor, žádné x++ neexisuje. + + +# Výjimky lze ošetřit pomocí bloku try/except(/else/finally) +try: + # Pro vyhození výjimky použijte raise + raise IndexError("Přistoupil jste k neexistujícímu prvku v seznamu.") +except IndexError as e: + print("Nastala chyba: {}".format(e)) + # Vypíše: Nastala chyba: Přistoupil jste k neexistujícímu prvku v seznamu. +except (TypeError, NameError): # Více výjimek lze zachytit najednou + pass # Pass znamená nedělej nic - nepříliš vhodný způsob ošetření chyb +else: # Volitelný blok else musí být až za bloky except + print("OK!") # Vypíše OK! v případě, že nenastala žádná výjimka +finally: # Blok finally se spustí nakonec za všech okolností + print("Uvolníme zdroje, uzavřeme soubory...") + +# Místo try/finally lze použít with pro automatické uvolnění zdrojů +with open("soubor.txt") as soubor: + for radka in soubor: + print(radka) + +# Python běžně používá iterovatelné objekty, což je prakticky cokoliv, +# co lze považovat za sekvenci. Například to, co vrací metoda range(), +# nebo otevřený soubor, jsou iterovatelné objekty. + +slovnik = {"jedna": 1, "dva": 2, "tři": 3} +iterovatelny_objekt = slovnik.keys() +print(iterovatelny_objekt) # => dict_keys(["jedna", "dva", "tři"]). Toto je iterovatelný objekt. + +# Můžeme použít cyklus for na jeho projití +for klic in iterovatelny_objekt: + print(klic) # vypíše postupně: jedna, dva, tři + +# Ale nelze přistupovat k prvkům pod jejich indexem +iterovatelny_objekt[1] # Vyhodí TypeError + +# Všechny položky iterovatelného objektu lze získat jako seznam pomocí list() +list(slovnik.keys()) # => ["jedna", "dva", "tři"] + +# Z iterovatelného objektu lze vytvořit iterátor +iterator = iter(iterovatelny_objekt) + +# Iterátor je objekt, který si pamatuje stav v rámci svého iterovatelného objektu +# Další hodnotu dostaneme voláním next() +next(iterator) # => "jedna" + +# Iterátor si udržuje svůj stav v mezi jednotlivými voláními next() +next(iterator) # => "dva" +next(iterator) # => "tři" + +# Jakmile interátor vrátí všechna svá data, vyhodí výjimku StopIteration +next(iterator) # Vyhodí StopIteration + + +#################################################### +## 4. Funkce +#################################################### + +# Pro vytvoření nové funkce použijte klíčové slovo def +def secist(x, y): + print("x je {} a y je {}".format(x, y)) + return x + y # Hodnoty se vrací pomocí return + +# Volání funkce s parametry +secist(5, 6) # => Vypíše "x je 5 a y je 6" a vrátí 11 + +# Jiný způsob, jak volat funkci, je použít pojmenované argumenty +secist(y=6, x=5) # Pojmenované argumenty můžete předat v libovolném pořadí + +# Lze definovat funkce s proměnným počtem (pozičních) argumentů +def vrat_argumenty(*argumenty): + return argumenty + +vrat_argumenty(1, 2, 3) # => (1, 2, 3) + +# Lze definovat také funkce s proměnným počtem pojmenovaných argumentů +def vrat_pojmenovane_argumenty(**pojmenovane_argumenty): + return pojmenovane_argumenty + +vrat_pojmenovane_argumenty(kdo="se bojí", nesmi="do lesa") +# => {"kdo": "se bojí", "nesmi": "do lesa"} + + +# Pokud chcete, lze použít obojí najednou +# Konvence je používat pro tyto účely názvy *args a **kwargs +def vypis_vse(*args, **kwargs): + print(args, kwargs) # print() vypíše všechny své parametry oddělené mezerou + +vypis_vse(1, 2, a=3, b=4) # Vypíše: (1, 2) {"a": 3, "b": 4} + +# * nebo ** lze použít k rozbalení N-tic nebo slovníků! +ntice = (1, 2, 3, 4) +slovnik = {"a": 3, "b": 4} +vypis_vse(ntice) # Vyhodnotí se jako vypis_vse((1, 2, 3, 4)) – jeden parametr, N-tice +vypis_vse(*ntice) # Vyhodnotí se jako vypis_vse(1, 2, 3, 4) +vypis_vse(**slovnik) # Vyhodnotí se jako vypis_vse(a=3, b=4) +vypis_vse(*ntice, **slovnik) # Vyhodnotí se jako vypis_vse(1, 2, 3, 4, a=3, b=4) + + +# Viditelnost proměnných - vytvořme si globální proměnnou x +x = 5 + +def nastavX(cislo): + # Lokální proměnná x překryje globální x + x = cislo # => 43 + print(x) # => 43 + +def nastavGlobalniX(cislo): + global x + print(x) # => 5 + x = cislo # Nastaví globální proměnnou x na 6 + print(x) # => 6 + +nastavX(43) +nastavGlobalniX(6) + + +# Funkce jsou first-class objekty +def vyrobit_scitacku(pricitane_cislo): + def scitacka(x): + return x + pricitane_cislo + return scitacka + +pricist_10 = vyrobit_scitacku(10) +pricist_10(3) # => 13 + +# Klíčové slovo lambda vytvoří anonymní funkci +(lambda parametr: parametr > 2)(3) # => True + +# Lze použít funkce map() a filter() z funkcionálního programování +map(pricist_10, [1, 2, 3]) +# => - iterovatelný objekt s obsahem: [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) +# => - iterovatelný objekt s obsahem: [6, 7] + +# S generátorovou notací lze dosáhnout podobných výsledků, ale vrací seznam +[pricist_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] +# Generátorová notace funguje i pro slovníky +{x: x**2 for x in range(1, 5)} # => {1: 1, 2: 4, 3: 9, 4: 16} +# A také pro množiny +{pismeno for pismeno in "abeceda"} # => {"d", "a", "c", "e", "b"} + + +#################################################### +## 5. Třídy +#################################################### + +# Třída Clovek je potomkem (dědí od) třídy object +class Clovek(object): + + # Atribut třídy - je sdílený všemi instancemi + druh = "H. sapiens" + + # Toto je kostruktor. Je volán, když vytváříme instanci třídy. Dvě + # podtržítka na začátku a na konci značí, že se jedná o atribut nebo + # objekt využívaný Pythonem ke speciálním účelům, ale můžete sami + # definovat jeho chování. Metody jako __init__, __str__, __repr__ + # a další se nazývají "magické metody". Nikdy nepoužívejte toto + # speciální pojmenování pro běžné metody. + def __init__(self, jmeno): + # Přiřazení parametru do atributu instance jmeno + self.jmeno = jmeno + + # Metoda instance - všechny metody instance mají "self" jako první parametr + def rekni(self, hlaska): + return "{jmeno}: {hlaska}".format(jmeno=self.jmeno, hlaska=hlaska) + + # Metoda třídy - sdílená všemi instancemi + # Dostává jako první parametr třídu, na které je volána + @classmethod + def vrat_druh(cls): + return cls.druh + + # Statická metoda je volána bez reference na třídu nebo instanci + @staticmethod + def odkaslej_si(): + return "*ehm*" + + +# Vytvoření instance +d = Clovek(jmeno="David") +a = Clovek("Adéla") +print(d.rekni("ahoj")) # Vypíše: "David: ahoj" +print(a.rekni("nazdar")) # Vypíše: "Adéla: nazdar" + +# Volání třídní metody +d.vrat_druh() # => "H. sapiens" + +# Změna atributu třídy +Clovek.druh = "H. neanderthalensis" +d.vrat_druh() # => "H. neanderthalensis" +a.vrat_druh() # => "H. neanderthalensis" + +# Volání statické metody +Clovek.odkaslej_si() # => "*ehm*" + + +#################################################### +## 6. Moduly +#################################################### + +# Lze importovat moduly +import math +print(math.sqrt(16.0)) # => 4.0 + +# Lze také importovat pouze vybrané funkce z modulu +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Můžete také importovat všechny funkce z modulu, ale radši to nedělejte +from math import * + +# Můžete si přejmenovat modul při jeho importu +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Modul v Pythonu není nic jiného, než obyčejný soubor .py +# Můžete si napsat vlastní a prostě ho importovat podle jména +from muj_modul import moje_funkce # Nyní vyhodí ImportError - muj_modul neexistuje + +# Funkcí dir() lze zjistit, co modul obsahuje +import math +dir(math) + + +#################################################### +## 7. Pokročilé +#################################################### + +# Generátory jsou funkce, které místo return obsahují yield +def nasobicka_2(sekvence): + for i in sekvence: + print("Zpracovávám číslo {}".format(i)) + yield 2 * i + +# Generátor generuje hodnoty postupně, jak jsou potřeba. Místo toho, aby vrátil +# celou sekvenci s prvky vynásobenými dvěma, provádí jeden výpočet v každé iteraci. +for nasobek in nasobicka_2([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]): + # Vypíše postupně: "Zpracovávám číslo 1", ..., "Zpracovávám číslo 5" + if nasobek >= 10: + break + +# Funkce range() je také generátor - vytváření seznamu 900000000 prvků by zabralo +# hodně času i paměti, proto se místo toho čísla generují postupně. +for nasobek in nasobicka_2(range(900000000)): + # Vypíše postupně: "Zpracovávám číslo 1", ..., "Zpracovávám číslo 5" + if nasobek >= 10: + break + + +# Dekorátory jsou funkce, které se používají pro obalení jiné funkce, čímž mohou +# přidávat nebo měnit její stávající chování. Funkci dostávají jako parametr +# a typicky místo ní vrací jinou, která uvnitř volá tu původní. + +def nekolikrat(puvodni_funkce): + def opakovaci_funkce(*args, **kwargs): + for i in range(3): + puvodni_funkce(*args, **kwargs) + + return opakovaci_funkce + + +@nekolikrat +def pozdrav(jmeno): + print("Měj se {}!".format(jmeno)) + +pozdrav("Pepo") # Vypíše 3x: "Měj se Pepo!" +``` + +## Co dál? + +Spoustu odkazů na české i anglické materiály najdete na [webu české Python komunity] +(http://python.cz/). Můžete také přijít na Pyvo, kde to společně probereme. diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown deleted file mode 100644 index bd3690a8..00000000 --- a/cs-cz/python3.html.markdown +++ /dev/null @@ -1,647 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Tomáš Bedřich", "http://tbedrich.cz"] -translators: - - ["Tomáš Bedřich", "http://tbedrich.cz"] -filename: learnpython3-cz.py -lang: cs-cz ---- - -Python byl vytvořen Guidem Van Rossum v raných 90. letech. Nyní je jedním z nejpopulárnějších jazyků. -Zamiloval jsem si Python pro jeho syntaktickou čistotu - je to vlastně spustitelný pseudokód. - -Vaše zpětná vazba je vítána! Můžete mě zastihnout na [@louiedinh](http://twitter.com/louiedinh) nebo louiedinh [at] [email od googlu] anglicky, -autora českého překladu pak na [@tbedrich](http://twitter.com/tbedrich) nebo ja [at] tbedrich.cz - -Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit starší Python 2.7](http://learnxinyminutes.com/docs/python/). - -```python - -# Jednořádkový komentář začíná křížkem - -""" Víceřádkové komentáře používají tři uvozovky nebo apostrofy - a jsou často využívány jako dokumentační komentáře k metodám -""" - -#################################################### -## 1. Primitivní datové typy a operátory -#################################################### - -# Čísla -3 # => 3 - -# Aritmetické operace se chovají běžným způsobem -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 - -# Až na dělení, které vrací desetinné číslo -35 / 5 # => 7.0 - -# Při celočíselném dělení je desetinná část oříznuta (pro kladná i záporná čísla) -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # celočíselně dělit lze i desetinným číslem --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Pokud použijete desetinné číslo, výsledek je jím také -3 * 2.0 # => 6.0 - -# Modulo -7 % 3 # => 1 - -# Mocnění (x na y-tou) -2**4 # => 16 - -# Pro vynucení priority použijte závorky -(1 + 3) * 2 # => 8 - -# Logické hodnoty -True -False - -# Negace se provádí pomocí not -not True # => False -not False # => True - -# Logické operátory -# U operátorů záleží na velikosti písmen -True and False # => False -False or True # => True - -# Používání logických operátorů s čísly -0 and 2 # => 0 --5 or 0 # => -5 - -# Při porovnání s boolean hodnotou nepoužívejte operátor rovnosti "==". -# Stejně jako u hodnoty None. -# Viz PEP8: https://www.python.org/dev/peps/pep-0008/ -0 is False # => True -2 is True # => False -1 is True # => True - -# Rovnost je == -1 == 1 # => True -2 == 1 # => False - -# Nerovnost je != -1 != 1 # => False -2 != 1 # => True - -# Další porovnání -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Porovnání se dají řetězit! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - - -# Řetězce používají " nebo ' a mohou obsahovat unicode znaky -"Toto je řetězec." -'Toto je také řetězec.' - -# Řetězce se také dají slučovat -"Hello " + "world!" # => "Hello world!" -# Dají se spojovat i bez '+' -"Hello " "world!" # => "Hello world!" - -# Řetězec lze považovat za seznam znaků -"Toto je řetězec"[0] # => 'T' - -# .format lze použít ke skládání řetězců -"{} mohou být {}".format("řetězce", "skládány") - -# Formátovací argumenty můžete opakovat -"{0} {1} stříkaček stříkalo přes {0} {1} střech".format("tři sta třicet tři", "stříbrných") -# => "tři sta třicet tři stříbrných stříkaček stříkalo přes tři sta třicet tři stříbrných střech" - -# Pokud nechcete počítat, můžete použít pojmenované argumenty -"{jmeno} si dal {jidlo}".format(jmeno="Franta", jidlo="guláš") # => "Franta si dal guláš" - -# Pokud zároveň potřebujete podporovat Python 2.5 a nižší, můžete použít starší způsob formátování -"%s se dají %s jako v %s" % ("řetězce", "skládat", "jazyce C") - - -# None je objekt (jinde NULL, nil, ...) -None # => None - -# Pokud porovnáváte něco s None, nepoužívejte operátor rovnosti "==", -# použijte raději operátor "is", který testuje identitu. -"něco" is None # => False -None is None # => True - -# None, 0, a prázdný řetězec/seznam/N-tice/slovník/množina se vyhodnotí jako False -# Vše ostatní se vyhodnotí jako True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool(tuple()) # => False -bool({}) # => False -bool(set()) # => False - - -#################################################### -## 2. Proměnné a kolekce -#################################################### - -# Python má funkci print -print("Jsem 3. Python 3.") - -# Proměnné není třeba deklarovat před přiřazením -# Konvence je používat male_pismo_s_podtrzitky -nazev_promenne = 5 -nazev_promenne # => 5 -# Názvy proměnných mohou obsahovat i unicode znaky, ale nedělejte to. -# Viz PEP 3131 -- Supporting Non-ASCII Identifiers: -# https://www.python.org/dev/peps/pep-3131/ -název_proměnné = 5 - -# Přístup k předtím nedefinované proměnné vyvolá výjimku -# Odchytávání vyjímek - viz další kapitola -neznama_promenna # Vyhodí NameError - -# Seznam se používá pro ukládání sekvencí -sez = [] -# Lze ho rovnou naplnit -jiny_seznam = [4, 5, 6] - -# Na konec seznamu se přidává pomocí append -sez.append(1) # sez je nyní [1] -sez.append(2) # sez je nyní [1, 2] -sez.append(4) # sez je nyní [1, 2, 4] -sez.append(3) # sez je nyní [1, 2, 4, 3] -# Z konce se odebírá se pomocí pop -sez.pop() # => 3 a sez je nyní [1, 2, 4] -# Vložme trojku zpátky -sez.append(3) # sez je nyní znovu [1, 2, 4, 3] - -# Přístup k prvkům funguje jako v poli -sez[0] # => 1 -# Mínus počítá odzadu (-1 je poslední prvek) -sez[-1] # => 3 - -# Přístup mimo seznam vyhodí IndexError -sez[4] # Vyhodí IndexError - -# Pomocí řezů lze ze seznamu vybírat různé intervaly -# (pro matematiky: jedná se o uzavřený/otevřený interval) -sez[1:3] # => [2, 4] -# Odříznutí začátku -sez[2:] # => [4, 3] -# Odříznutí konce -sez[:3] # => [1, 2, 4] -# Vybrání každého druhého prvku -sez[::2] # =>[1, 4] -# Vrácení seznamu v opačném pořadí -sez[::-1] # => [3, 4, 2, 1] -# Lze použít jakoukoliv kombinaci parametrů pro vytvoření složitějšího řezu -# sez[zacatek:konec:krok] - -# Odebírat prvky ze seznamu lze pomocí del -del sez[2] # sez je nyní [1, 2, 3] - -# Seznamy můžete slučovat -# Hodnoty sez a jiny_seznam přitom nejsou změněny -sez + jiny_seznam # => [1, 2, 3, 4, 5, 6] - -# Spojit seznamy lze pomocí extend -sez.extend(jiny_seznam) # sez je nyní [1, 2, 3, 4, 5, 6] - -# Kontrola, jestli prvek v seznamu existuje, se provádí pomocí in -1 in sez # => True - -# Délku seznamu lze zjistit pomocí len -len(sez) # => 6 - - -# N-tice je jako seznam, ale je neměnná -ntice = (1, 2, 3) -ntice[0] # => 1 -ntice[0] = 3 # Vyhodí TypeError - -# S n-ticemi lze dělat většinu operací, jako se seznamy -len(ntice) # => 3 -ntice + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -ntice[:2] # => (1, 2) -2 in ntice # => True - -# N-tice (nebo seznamy) lze rozbalit do proměnných jedním přiřazením -a, b, c = (1, 2, 3) # a je nyní 1, b je nyní 2 a c je nyní 3 -# N-tice jsou vytvářeny automaticky, když vynecháte závorky -d, e, f = 4, 5, 6 -# Prohození proměnných je tak velmi snadné -e, d = d, e # d je nyní 5, e je nyní 4 - - -# Slovníky ukládají klíče a hodnoty -prazdny_slovnik = {} -# Lze je také rovnou naplnit -slovnik = {"jedna": 1, "dva": 2, "tři": 3} - -# Přistupovat k hodnotám lze pomocí [] -slovnik["jedna"] # => 1 - -# Všechny klíče dostaneme pomocí keys() jako iterovatelný objekt. Nyní ještě -# potřebujeme obalit volání v list(), abychom dostali seznam. To rozebereme -# později. Pozor, že jakékoliv pořadí klíčů není garantováno - může být různé. -list(slovnik.keys()) # => ["dva", "jedna", "tři"] - -# Všechny hodnoty opět jako iterovatelný objekt získáme pomocí values(). Opět -# tedy potřebujeme použít list(), abychom dostali seznam. Stejně jako -# v předchozím případě, pořadí není garantováno a může být různé -list(slovnik.values()) # => [3, 2, 1] - -# Operátorem in se lze dotázat na přítomnost klíče -"jedna" in slovnik # => True -1 in slovnik # => False - -# Přístup k neexistujícímu klíči vyhodí KeyError -slovnik["čtyři"] # Vyhodí KeyError - -# Metoda get() funguje podobně jako [], ale vrátí None místo vyhození KeyError -slovnik.get("jedna") # => 1 -slovnik.get("čtyři") # => None -# Metodě get() lze předat i výchozí hodnotu místo None -slovnik.get("jedna", 4) # => 1 -slovnik.get("čtyři", 4) # => 4 - -# metoda setdefault() vloží prvek do slovníku pouze pokud tam takový klíč není -slovnik.setdefault("pět", 5) # slovnik["pět"] je nastaven na 5 -slovnik.setdefault("pět", 6) # slovnik["pět"] je pořád 5 - -# Přidání nové hodnoty do slovníku -slovnik["čtyři"] = 4 -# Hromadně aktualizovat nebo přidat data lze pomocí update(), parametrem je opět slovník -slovnik.update({"čtyři": 4}) # slovnik je nyní {"jedna": 1, "dva": 2, "tři": 3, "čtyři": 4, "pět": 5} - -# Odebírat ze slovníku dle klíče lze pomocí del -del slovnik["jedna"] # odebere klíč "jedna" ze slovnik - - -# Množiny ukládají ... překvapivě množiny -prazdna_mnozina = set() -# Také je lze rovnou naplnit. A ano, budou se vám plést se slovníky. Bohužel. -mnozina = {1, 1, 2, 2, 3, 4} # mnozina je nyní {1, 2, 3, 4} - -# Přidání položky do množiny -mnozina.add(5) # mnozina je nyní {1, 2, 3, 4, 5} - -# Průnik lze udělat pomocí operátoru & -jina_mnozina = {3, 4, 5, 6} -mnozina & jina_mnozina # => {3, 4, 5} - -# Sjednocení pomocí operátoru | -mnozina | jina_mnozina # => {1, 2, 3, 4, 5, 6} - -# Rozdíl pomocí operátoru - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Operátorem in se lze dotázat na přítomnost prvku v množině -2 in mnozina # => True -9 in mnozina # => False - - -#################################################### -## 3. Řízení toku programu, cykly -#################################################### - -# Vytvořme si proměnnou -promenna = 5 - -# Takto vypadá podmínka. Na odsazení v Pythonu záleží! -# Vypíše "proměnná je menší než 10". -if promenna > 10: - print("proměnná je velká jak Rusko") -elif promenna < 10: # Část elif je nepovinná - print("proměnná je menší než 10") -else: # Část else je také nepovinná - print("proměnná je právě 10") - - -""" -Smyčka for umí iterovat (nejen) přes seznamy -vypíše: - pes je savec - kočka je savec - myš je savec -""" -for zvire in ["pes", "kočka", "myš"]: - # Můžete použít formát pro složení řetězce - print("{} je savec".format(zvire)) - -""" -range(cislo) vrací iterovatelný objekt čísel od 0 do cislo -vypíše: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -range(spodni_limit, horni_limit) vrací iterovatelný objekt čísel mezi limity -vypíše: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -Smyčka while se opakuje, dokud je podmínka splněna. -vypíše: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Zkrácený zápis x = x + 1. Pozor, žádné x++ neexisuje. - - -# Výjimky lze ošetřit pomocí bloku try/except(/else/finally) -try: - # Pro vyhození výjimky použijte raise - raise IndexError("Přistoupil jste k neexistujícímu prvku v seznamu.") -except IndexError as e: - print("Nastala chyba: {}".format(e)) - # Vypíše: Nastala chyba: Přistoupil jste k neexistujícímu prvku v seznamu. -except (TypeError, NameError): # Více výjimek lze zachytit najednou - pass # Pass znamená nedělej nic - nepříliš vhodný způsob ošetření chyb -else: # Volitelný blok else musí být až za bloky except - print("OK!") # Vypíše OK! v případě, že nenastala žádná výjimka -finally: # Blok finally se spustí nakonec za všech okolností - print("Uvolníme zdroje, uzavřeme soubory...") - -# Místo try/finally lze použít with pro automatické uvolnění zdrojů -with open("soubor.txt") as soubor: - for radka in soubor: - print(radka) - -# Python běžně používá iterovatelné objekty, což je prakticky cokoliv, -# co lze považovat za sekvenci. Například to, co vrací metoda range(), -# nebo otevřený soubor, jsou iterovatelné objekty. - -slovnik = {"jedna": 1, "dva": 2, "tři": 3} -iterovatelny_objekt = slovnik.keys() -print(iterovatelny_objekt) # => dict_keys(["jedna", "dva", "tři"]). Toto je iterovatelný objekt. - -# Můžeme použít cyklus for na jeho projití -for klic in iterovatelny_objekt: - print(klic) # vypíše postupně: jedna, dva, tři - -# Ale nelze přistupovat k prvkům pod jejich indexem -iterovatelny_objekt[1] # Vyhodí TypeError - -# Všechny položky iterovatelného objektu lze získat jako seznam pomocí list() -list(slovnik.keys()) # => ["jedna", "dva", "tři"] - -# Z iterovatelného objektu lze vytvořit iterátor -iterator = iter(iterovatelny_objekt) - -# Iterátor je objekt, který si pamatuje stav v rámci svého iterovatelného objektu -# Další hodnotu dostaneme voláním next() -next(iterator) # => "jedna" - -# Iterátor si udržuje svůj stav v mezi jednotlivými voláními next() -next(iterator) # => "dva" -next(iterator) # => "tři" - -# Jakmile interátor vrátí všechna svá data, vyhodí výjimku StopIteration -next(iterator) # Vyhodí StopIteration - - -#################################################### -## 4. Funkce -#################################################### - -# Pro vytvoření nové funkce použijte klíčové slovo def -def secist(x, y): - print("x je {} a y je {}".format(x, y)) - return x + y # Hodnoty se vrací pomocí return - -# Volání funkce s parametry -secist(5, 6) # => Vypíše "x je 5 a y je 6" a vrátí 11 - -# Jiný způsob, jak volat funkci, je použít pojmenované argumenty -secist(y=6, x=5) # Pojmenované argumenty můžete předat v libovolném pořadí - -# Lze definovat funkce s proměnným počtem (pozičních) argumentů -def vrat_argumenty(*argumenty): - return argumenty - -vrat_argumenty(1, 2, 3) # => (1, 2, 3) - -# Lze definovat také funkce s proměnným počtem pojmenovaných argumentů -def vrat_pojmenovane_argumenty(**pojmenovane_argumenty): - return pojmenovane_argumenty - -vrat_pojmenovane_argumenty(kdo="se bojí", nesmi="do lesa") -# => {"kdo": "se bojí", "nesmi": "do lesa"} - - -# Pokud chcete, lze použít obojí najednou -# Konvence je používat pro tyto účely názvy *args a **kwargs -def vypis_vse(*args, **kwargs): - print(args, kwargs) # print() vypíše všechny své parametry oddělené mezerou - -vypis_vse(1, 2, a=3, b=4) # Vypíše: (1, 2) {"a": 3, "b": 4} - -# * nebo ** lze použít k rozbalení N-tic nebo slovníků! -ntice = (1, 2, 3, 4) -slovnik = {"a": 3, "b": 4} -vypis_vse(ntice) # Vyhodnotí se jako vypis_vse((1, 2, 3, 4)) – jeden parametr, N-tice -vypis_vse(*ntice) # Vyhodnotí se jako vypis_vse(1, 2, 3, 4) -vypis_vse(**slovnik) # Vyhodnotí se jako vypis_vse(a=3, b=4) -vypis_vse(*ntice, **slovnik) # Vyhodnotí se jako vypis_vse(1, 2, 3, 4, a=3, b=4) - - -# Viditelnost proměnných - vytvořme si globální proměnnou x -x = 5 - -def nastavX(cislo): - # Lokální proměnná x překryje globální x - x = cislo # => 43 - print(x) # => 43 - -def nastavGlobalniX(cislo): - global x - print(x) # => 5 - x = cislo # Nastaví globální proměnnou x na 6 - print(x) # => 6 - -nastavX(43) -nastavGlobalniX(6) - - -# Funkce jsou first-class objekty -def vyrobit_scitacku(pricitane_cislo): - def scitacka(x): - return x + pricitane_cislo - return scitacka - -pricist_10 = vyrobit_scitacku(10) -pricist_10(3) # => 13 - -# Klíčové slovo lambda vytvoří anonymní funkci -(lambda parametr: parametr > 2)(3) # => True - -# Lze použít funkce map() a filter() z funkcionálního programování -map(pricist_10, [1, 2, 3]) -# => - iterovatelný objekt s obsahem: [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) -# => - iterovatelný objekt s obsahem: [6, 7] - -# S generátorovou notací lze dosáhnout podobných výsledků, ale vrací seznam -[pricist_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] -# Generátorová notace funguje i pro slovníky -{x: x**2 for x in range(1, 5)} # => {1: 1, 2: 4, 3: 9, 4: 16} -# A také pro množiny -{pismeno for pismeno in "abeceda"} # => {"d", "a", "c", "e", "b"} - - -#################################################### -## 5. Třídy -#################################################### - -# Třída Clovek je potomkem (dědí od) třídy object -class Clovek(object): - - # Atribut třídy - je sdílený všemi instancemi - druh = "H. sapiens" - - # Toto je kostruktor. Je volán, když vytváříme instanci třídy. Dvě - # podtržítka na začátku a na konci značí, že se jedná o atribut nebo - # objekt využívaný Pythonem ke speciálním účelům, ale můžete sami - # definovat jeho chování. Metody jako __init__, __str__, __repr__ - # a další se nazývají "magické metody". Nikdy nepoužívejte toto - # speciální pojmenování pro běžné metody. - def __init__(self, jmeno): - # Přiřazení parametru do atributu instance jmeno - self.jmeno = jmeno - - # Metoda instance - všechny metody instance mají "self" jako první parametr - def rekni(self, hlaska): - return "{jmeno}: {hlaska}".format(jmeno=self.jmeno, hlaska=hlaska) - - # Metoda třídy - sdílená všemi instancemi - # Dostává jako první parametr třídu, na které je volána - @classmethod - def vrat_druh(cls): - return cls.druh - - # Statická metoda je volána bez reference na třídu nebo instanci - @staticmethod - def odkaslej_si(): - return "*ehm*" - - -# Vytvoření instance -d = Clovek(jmeno="David") -a = Clovek("Adéla") -print(d.rekni("ahoj")) # Vypíše: "David: ahoj" -print(a.rekni("nazdar")) # Vypíše: "Adéla: nazdar" - -# Volání třídní metody -d.vrat_druh() # => "H. sapiens" - -# Změna atributu třídy -Clovek.druh = "H. neanderthalensis" -d.vrat_druh() # => "H. neanderthalensis" -a.vrat_druh() # => "H. neanderthalensis" - -# Volání statické metody -Clovek.odkaslej_si() # => "*ehm*" - - -#################################################### -## 6. Moduly -#################################################### - -# Lze importovat moduly -import math -print(math.sqrt(16.0)) # => 4.0 - -# Lze také importovat pouze vybrané funkce z modulu -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Můžete také importovat všechny funkce z modulu, ale radši to nedělejte -from math import * - -# Můžete si přejmenovat modul při jeho importu -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Modul v Pythonu není nic jiného, než obyčejný soubor .py -# Můžete si napsat vlastní a prostě ho importovat podle jména -from muj_modul import moje_funkce # Nyní vyhodí ImportError - muj_modul neexistuje - -# Funkcí dir() lze zjistit, co modul obsahuje -import math -dir(math) - - -#################################################### -## 7. Pokročilé -#################################################### - -# Generátory jsou funkce, které místo return obsahují yield -def nasobicka_2(sekvence): - for i in sekvence: - print("Zpracovávám číslo {}".format(i)) - yield 2 * i - -# Generátor generuje hodnoty postupně, jak jsou potřeba. Místo toho, aby vrátil -# celou sekvenci s prvky vynásobenými dvěma, provádí jeden výpočet v každé iteraci. -for nasobek in nasobicka_2([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]): - # Vypíše postupně: "Zpracovávám číslo 1", ..., "Zpracovávám číslo 5" - if nasobek >= 10: - break - -# Funkce range() je také generátor - vytváření seznamu 900000000 prvků by zabralo -# hodně času i paměti, proto se místo toho čísla generují postupně. -for nasobek in nasobicka_2(range(900000000)): - # Vypíše postupně: "Zpracovávám číslo 1", ..., "Zpracovávám číslo 5" - if nasobek >= 10: - break - - -# Dekorátory jsou funkce, které se používají pro obalení jiné funkce, čímž mohou -# přidávat nebo měnit její stávající chování. Funkci dostávají jako parametr -# a typicky místo ní vrací jinou, která uvnitř volá tu původní. - -def nekolikrat(puvodni_funkce): - def opakovaci_funkce(*args, **kwargs): - for i in range(3): - puvodni_funkce(*args, **kwargs) - - return opakovaci_funkce - - -@nekolikrat -def pozdrav(jmeno): - print("Měj se {}!".format(jmeno)) - -pozdrav("Pepo") # Vypíše 3x: "Měj se Pepo!" -``` - -## Co dál? - -Spoustu odkazů na české i anglické materiály najdete na [webu české Python komunity] -(http://python.cz/). Můžete také přijít na Pyvo, kde to společně probereme. diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown new file mode 100644 index 00000000..4ef997a1 --- /dev/null +++ b/de-de/python-de.html.markdown @@ -0,0 +1,655 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["kultprok", "http:/www.kulturproktologie.de"] + - ["matthiaskern", "https://github.com/matthiaskern"] +filename: learnpython3-de.py +lang: de-de +--- + +Anmerkungen des ursprünglichen Autors: +Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode. + +Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service]. + +Hinweis: Dieser Beitrag bezieht sich implizit auf Python 3. Falls du lieber Python 2.7 lernen möchtest, schau [hier](http://learnxinyminutes.com/docs/python/) weiter. + +```python + +# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz) + +""" Mehrzeilige Strings werden mit + drei '-Zeichen geschrieben und werden + oft als Kommentare genutzt. +""" + +#################################################### +## 1. Primitive Datentypen und Operatoren +#################################################### + +# Die Zahlen +3 #=> 3 + +# Mathematik funktioniert so, wie man das erwartet +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 + +# Außer Division, welche automatisch Gleitkommazahlen zurückgibt +35 / 5 # => 7.0 + +# Eine Division kann mit "//" für positive sowie negative Werte abgerundet werden. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Benutzt man eine Gleitkommazahl, ist auch das Ergebnis eine solche +3 * 2.0 # => 6.0 + +# Der Rest einer Division +7 % 3 # => 1 + +# Potenz +2**4 # => 16 + +# Rangfolge wird mit Klammern erzwungen +(1 + 3) * 2 #=> 8 + +# Boolesche Ausdrücke sind primitive Datentypen +True +False + +# Mit not wird negiert +not True #=> False +not False #=> True + +# Boolesche Operatoren +# Hinweis: "and" und "or" müssen klein geschrieben werden +True and False #=> False +False or True #=> True + +# Für die Benutzung von Booleschen Operatoren und ganzen Zahlen +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Gleichheit ist == +1 == 1 #=> True +2 == 1 #=> False + +# Ungleichheit ist != +1 != 1 #=> False +2 != 1 #=> True + +# Ein paar weitere Vergleiche +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Vergleiche können verknüpft werden! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Strings werden mit " oder ' gebildet +"Das ist ein String." +'Das ist auch ein String.' + +# Strings können auch addiert werden! Vermeide dies aber lieber. +"Hallo " + "Welt!" #=> "Hallo Welt!" +# Strings können ohne "+" addiert werden +"Hallo " "welt!" # => "Hallo Welt!" + +# Ein String kann wie eine Liste von Zeichen verwendet werden +"Das ist ein String"[0] #=> 'D' + +# .format kann Strings formatieren +"{} können {} werden".format("Strings", "formatiert") + +# Schneller geht das mit Wiederholungen +"{0} mag Spagetthi, {0} liebt es zu Schwimmen und ganz besonders mag {0} {1}".format("Hans", "Blattsalat") +#=> "Hans mag Spagetthi, Hans liebt es zu Schwimmen und ganz besonders mag Hans Blattsalat" + +# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen. +"{name} will {food} essen".format(name="Bob", food="Lasagne") +#=> "Bob will Lasagne kochen" + +#Falls dein Python 3 Code auch unter Python 2.5 oder darunter laufen soll, kann das alte Format benutzt werden: +"%s können %s werden" % ("Strings", "interpoliert") + + +# None ist ein Objekt +None #=> None + +# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen +# Benutzt stattdessen `is`. Dieser Operator testet Objektidentität +"etc" is None #=> False +None is None #=> True + + + +# None, 0, und leere Strings/Listen werden alle als False bewertet. +# Alle anderen Werte sind True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Variablen und Collections +#################################################### + +# Textausgabe ist sehr einfach +print("Ich bin Python. Schön, dich kennenzulernen!") + +# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren. +some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm +some_var #=> 5 + +# Das Ansprechen einer noch nicht deklarierten Variable löst eine Exception aus. +# Unter "Kontrollstruktur" kann noch mehr über +# Ausnahmebehandlung erfahren werden. +some_unknown_var # Löst einen NameError aus + +# Listen speichern Sequenzen +li = [] +# Wir können mit einer bereits gefüllten Liste anfangen +other_li = [4, 5, 6] + +# append fügt Daten am Ende der Liste ein +li.append(1) #li ist jetzt [1] +li.append(2) #li ist jetzt [1, 2] +li.append(4) #li ist jetzt [1, 2, 4] +li.append(3) #li ist jetzt [1, 2, 4, 3] +# Vom Ende der Liste mit pop entfernen +li.pop() #=> 3 und li ist jetzt [1, 2, 4] +# und dann wieder hinzufügen +li.append(3) # li ist jetzt wieder [1, 2, 4, 3]. + +# Greife auf Listen wie auf Arrays zu +li[0] #=> 1 +# Das letzte Element ansehen +li[-1] #=> 3 + +# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError +li[4] # Verursacht einen IndexError + +# Wir können uns Ranges mit Slice-Syntax ansehen +li[1:3] #=> [2, 4] +# Den Anfang auslassen +li[2:] #=> [4, 3] +# Das Ende auslassen +li[:3] #=> [1, 2, 4] +# Jeden Zweiten Eintrag auswählen +li[::2] # =>[1, 4] +# Eine umgekehrte Kopie zurückgeben +li[::-1] # => [3, 4, 2, 1] +# Jegliche Kombination dieser Syntax machen fortgeschrittene Slices möglich +# li[Start:Ende:Schritt] + +# Ein bestimmtes Element mit del aus der Liste entfernen +del li[2] # li ist jetzt [1, 2, 3] + +# Listen können addiert werden +li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen + +# Listen mit extend verknüpfen +li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6] + +# Mit in auf Existenz eines Elements prüfen +1 in li #=> True + +# Die Länge der Liste mit len ermitteln +len(li) #=> 6 + + +# Tupel sind wie Listen, nur unveränderlich. +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Löst einen TypeError aus + +# Wir können all diese Listen-Dinge auch mit Tupeln anstellen +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Wir können Tupel (oder Listen) in Variablen entpacken +a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3 +# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen +d, e, f = 4, 5, 6 +# Es ist kinderleicht zwei Werte zu tauschen +e, d = d, e # d ist nun 5 und e ist nun 4 + + +# Dictionarys (Wörterbucher) speichern Schlüssel-Werte-Paare +empty_dict = {} +# Hier ein gefülltes Wörterbuch +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Wir können Einträge mit [] nachschlagen +filled_dict["one"] #=> 1 + +# So holen wir alle Keys (Schlüssel) als Liste +list(filled_dict.keys()) #=> ["three", "two", "one"] +# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert. +# Einzelne Resultate können anders angeordnet sein. + +# Alle Values (Werte) als Liste +list(filled_dict.values()) #=> [3, 2, 1] +# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln. + +# Das Vorhandensein eines Schlüssels im Wörterbuch mit "in" prüfen +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus +filled_dict["four"] # KeyError + +# Mit der get-Methode verhindern wir das +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen +filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt +filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5 + +# Einträge zu einem Wörterbuch hinzufügen +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 # noch ein Weg, Werte hinzuzufügen + +# Schlüssel von einem Wörterbuch entfernen +del filled_dict["one"] # Entfert den Schlüssel "one" + + +# Sets speichern Mengen +empty_set = set() +# Initialisieren wir ein Set mit ein paar Werten +some_set = {1, 1, 2, 2, 3, 4} # some_set ist jetzt {1, 2, 3, 4} + +# Neue Variablen können einer Menge gleichgesetzt werden +filled_set = some_set + +# Mehr Elemente hinzufügen +filled_set.add(5) # filled_set ist jetzt {1, 2, 3, 4, 5} + +# Schnittmengen werden mit & gebildet +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Mengen werden mit | vereinigt +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Die Differenz einer Menge mit - bilden +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Auf Vorhandensein von Elementen mit in prüfen +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Kontrollstruktur und Iteratoren +#################################################### + +# Erstellen wir mal eine Variable +some_var = 5 + +# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig! +# gibt "some_var ist kleiner als 10" aus +if some_var > 10: + print("some_var ist viel größer als 10.") +elif some_var < 10: # Dieser elif-Absatz ist optional. + print("some_var ist kleiner als 10.") +else: # Das hier ist auch optional. + print("some_var ist tatsächlich 10.") + + +""" +For-Schleifen iterieren über Listen +Ausgabe: + hund ist ein Säugetier + katze ist ein Säugetier + maus ist ein Säugetier +""" +for animal in ["hund", "katze", "maus"]: + # Wir können Strings mit format() formatieren + print("{} ist ein Säugetier".format(animal)) + +""" +`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder +Ausgabe: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(unten, oben)" gibt eine Liste von der unteren Zahl bis zur oberen Zahl aus +Ausgabe: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +While-Schleifen laufen, bis eine Bedingung erfüllt ist. +Ausgabe: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Kurzform für x = x + 1 + +# Ausnahmebehandlung mit einem try/except-Block +try: + # Mit raise wird ein Fehler ausgegeben + raise IndexError("Das hier ist ein Index-Fehler") +except IndexError as e: + pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären. +except (TypeError, NameError): + pass # Mehrere Fehler können zusammen geklärt werden, falls erforderlich. +else: # Optional, hinter allen except-Blöcken + print("Keine Probleme!") # Wird nur ausgeführt, wenn keine Ausnahmen aufgetreten sind +finally: # Wird immer ausgeführt + print("Hier können wir Ressourcen aufräumen") + +# alternativ zu einem try/finally Block um Aufzuräumen: +with open("meineDatei.txt") as f: + for line in f: + print(line) + +# Python bietet ein fundamentales Konzept der Iteration. +# Das Objekt, auf das die Iteration, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable". +# Die range Methode gibt ein solches Objekt aus. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). Dies ist ein "iterable" Objekt. + +# Über dieses können wir auch iterieren +for i in our_iterable: + print(i) # Gibt one, two, three aus + +# Allerdings können wir die einzelnen Elemente nicht mit ihrem index ausgeben +our_iterable[1] # TypeError + +# Ein iterable ist ein Objekt, das weiß wie es einen Iteratoren erschafft. +our_iterator = iter(our_iterable) + +# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es gerade hat während wir durch es gehen. +# Das jeweils nächste Objekt bekommen wir mit "next()" +next(our_iterator) #=> "one" + +# Es hält den vorherigen Status +next(our_iterator) #=> "two" +next(our_iterator) #=> "three" + +# Nachdem alle Daten ausgegeben worden sind, kommt eine StopIterator Ausnahme zurück +next(our_iterator) # Gibt StopIteration aus + +# Alle Elemente können mit "list()" ausgegeben werden +list(filled_dict.keys()) #=> ["one", "two", "three"] + + + +#################################################### +## 4. Funktionen +#################################################### + +# Mit def neue Funktionen erstellen +def add(x, y): + print("x ist %s und y ist %s" % (x, y)) + return x + y # Werte werden mit return zurückgegeben + +# Funktionen mit Parametern aufrufen +add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück + +# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente +add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden. + +# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Wir können auch Funktionen mit beliebiger Anzahl +# Schlüsselwort-Argumenten definieren +def keyword_args(**kwargs): + return kwargs + +# Rufen wir es mal auf, um zu sehen, was passiert +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Wir können beides gleichzeitig machen, wenn wir wollen +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) Ausgabe: + (1, 2) + {"a": 3, "b": 4} +""" + +# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen! +# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4) +all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4) +all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4) + + +# Anwendungsbereich von Funktionen +x = 5 + +def setX(num): + # lokale Variable x ist nicht die globale Variable x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # globale Variable x ist jetzt 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python hat First-Class-Funktionen +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Es gibt auch anonyme Funktionen +(lambda x: x > 2)(3) #=> True + +# Es gibt auch Funktionen höherer Ordnung als Built-Ins +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#################################################### +## 5. Klassen +#################################################### + +# Wir bilden die Unterklasse eines Objekts, um Klassen zu erhalten. +class Human(object): + + # Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt + species = "H. sapiens" + + # Ein simpler Konstruktor + def __init__(self, name): + # Wir weisen das Argument name dem name-Attribut der Instanz zu + self.name = name + + # Eine Instanzmethode. Alle Methoden erhalten self als erstes Argument. + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Eine Klassenmethode wird von allen Instanzen geteilt. + # Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen + @classmethod + def get_species(cls): + return cls.species + + # Eine statische Methode wird ohne Klasse oder Instanz aufgerufen + @staticmethod + def grunt(): + return "*grunt*" + + +# Eine Instanz einer Klasse erstellen +i = Human(name="Ian") +print(i.say("hi")) # gibt "Ian: hi" aus + +j = Human("Joel") +print(j.say("hello")) #gibt "Joel: hello" aus + +# Rufen wir mal unsere Klassenmethode auf +i.get_species() #=> "H. sapiens" + +# Ändern wir mal das gemeinsame Attribut +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Aufruf der statischen Methode +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Module +#################################################### + +# Wir können Module importieren +import math +print(math.sqrt(16)) #=> 4.0 + +# Wir können auch nur spezielle Funktionen eines Moduls importieren +from math import ceil, floor +print(ceil(3.7)) #=> 4.0 +print(floor(3.7)) #=> 3.0 + +# Wir können auch alle Funktionen eines Moduls importieren +# Warnung: Dies wird nicht empfohlen +from math import * + +# Wir können Modulnamen abkürzen +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Module sind in Python nur gewöhnliche Dateien. Wir +# können unsere eigenen schreiben und importieren. Der Name des +# Moduls ist der Dateiname. + +# Wir können auch die Funktionen und Attribute eines +# Moduls herausfinden. +import math +dir(math) + + +#################################################### +## 7. Fortgeschritten +#################################################### + +# Generatoren helfen um Code schnell und einfach zu schreiben +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Ein Generator erschafft Werte spontan +# Statt alle Werte auf einmal, wird bei jeder Iteration einer erschaffen. +# iteration. Das heißt, Werte größer als 15 werden nicht behandelt. +# Die range-Methode ist auch ein Generator. Im Fall einer Liste von 1-900000000 +# würde das sehr viel Zeit in Anspruch nehmen. +# Wenn wir eine variable mit einem Namen erschaffen wollen, das +# normalerweise mit einem Python - Schlüsselwort kollidieren würde, +# benutzen wir einen Unterstrich nach dem Wort. +range_ = range(1, 900000000) +# Alle Nummern bis zu einem Ergebnis von >=30 werden verdoppelt +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Dekoratoren +# In diesem Beispiel die Methode beg umwickelt say +# Beim Aufruf von beg, say wird aufgerufen +# Falls say_please true ist, ändert sich die ausgegebene Nachricht +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( + +``` + +## Lust auf mehr? + +### Kostenlos online (Englisch) + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### Totholz (Englisch) + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/de-de/python3-de.html.markdown b/de-de/python3-de.html.markdown deleted file mode 100644 index 4ef997a1..00000000 --- a/de-de/python3-de.html.markdown +++ /dev/null @@ -1,655 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://ldinh.ca"] -translators: - - ["kultprok", "http:/www.kulturproktologie.de"] - - ["matthiaskern", "https://github.com/matthiaskern"] -filename: learnpython3-de.py -lang: de-de ---- - -Anmerkungen des ursprünglichen Autors: -Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode. - -Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service]. - -Hinweis: Dieser Beitrag bezieht sich implizit auf Python 3. Falls du lieber Python 2.7 lernen möchtest, schau [hier](http://learnxinyminutes.com/docs/python/) weiter. - -```python - -# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz) - -""" Mehrzeilige Strings werden mit - drei '-Zeichen geschrieben und werden - oft als Kommentare genutzt. -""" - -#################################################### -## 1. Primitive Datentypen und Operatoren -#################################################### - -# Die Zahlen -3 #=> 3 - -# Mathematik funktioniert so, wie man das erwartet -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 - -# Außer Division, welche automatisch Gleitkommazahlen zurückgibt -35 / 5 # => 7.0 - -# Eine Division kann mit "//" für positive sowie negative Werte abgerundet werden. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # works on floats too --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Benutzt man eine Gleitkommazahl, ist auch das Ergebnis eine solche -3 * 2.0 # => 6.0 - -# Der Rest einer Division -7 % 3 # => 1 - -# Potenz -2**4 # => 16 - -# Rangfolge wird mit Klammern erzwungen -(1 + 3) * 2 #=> 8 - -# Boolesche Ausdrücke sind primitive Datentypen -True -False - -# Mit not wird negiert -not True #=> False -not False #=> True - -# Boolesche Operatoren -# Hinweis: "and" und "or" müssen klein geschrieben werden -True and False #=> False -False or True #=> True - -# Für die Benutzung von Booleschen Operatoren und ganzen Zahlen -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True - -# Gleichheit ist == -1 == 1 #=> True -2 == 1 #=> False - -# Ungleichheit ist != -1 != 1 #=> False -2 != 1 #=> True - -# Ein paar weitere Vergleiche -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True - -# Vergleiche können verknüpft werden! -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False - -# Strings werden mit " oder ' gebildet -"Das ist ein String." -'Das ist auch ein String.' - -# Strings können auch addiert werden! Vermeide dies aber lieber. -"Hallo " + "Welt!" #=> "Hallo Welt!" -# Strings können ohne "+" addiert werden -"Hallo " "welt!" # => "Hallo Welt!" - -# Ein String kann wie eine Liste von Zeichen verwendet werden -"Das ist ein String"[0] #=> 'D' - -# .format kann Strings formatieren -"{} können {} werden".format("Strings", "formatiert") - -# Schneller geht das mit Wiederholungen -"{0} mag Spagetthi, {0} liebt es zu Schwimmen und ganz besonders mag {0} {1}".format("Hans", "Blattsalat") -#=> "Hans mag Spagetthi, Hans liebt es zu Schwimmen und ganz besonders mag Hans Blattsalat" - -# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen. -"{name} will {food} essen".format(name="Bob", food="Lasagne") -#=> "Bob will Lasagne kochen" - -#Falls dein Python 3 Code auch unter Python 2.5 oder darunter laufen soll, kann das alte Format benutzt werden: -"%s können %s werden" % ("Strings", "interpoliert") - - -# None ist ein Objekt -None #=> None - -# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen -# Benutzt stattdessen `is`. Dieser Operator testet Objektidentität -"etc" is None #=> False -None is None #=> True - - - -# None, 0, und leere Strings/Listen werden alle als False bewertet. -# Alle anderen Werte sind True -bool(0) # => False -bool("") # => False -bool([]) #=> False -bool({}) #=> False - - -#################################################### -## 2. Variablen und Collections -#################################################### - -# Textausgabe ist sehr einfach -print("Ich bin Python. Schön, dich kennenzulernen!") - -# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren. -some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm -some_var #=> 5 - -# Das Ansprechen einer noch nicht deklarierten Variable löst eine Exception aus. -# Unter "Kontrollstruktur" kann noch mehr über -# Ausnahmebehandlung erfahren werden. -some_unknown_var # Löst einen NameError aus - -# Listen speichern Sequenzen -li = [] -# Wir können mit einer bereits gefüllten Liste anfangen -other_li = [4, 5, 6] - -# append fügt Daten am Ende der Liste ein -li.append(1) #li ist jetzt [1] -li.append(2) #li ist jetzt [1, 2] -li.append(4) #li ist jetzt [1, 2, 4] -li.append(3) #li ist jetzt [1, 2, 4, 3] -# Vom Ende der Liste mit pop entfernen -li.pop() #=> 3 und li ist jetzt [1, 2, 4] -# und dann wieder hinzufügen -li.append(3) # li ist jetzt wieder [1, 2, 4, 3]. - -# Greife auf Listen wie auf Arrays zu -li[0] #=> 1 -# Das letzte Element ansehen -li[-1] #=> 3 - -# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError -li[4] # Verursacht einen IndexError - -# Wir können uns Ranges mit Slice-Syntax ansehen -li[1:3] #=> [2, 4] -# Den Anfang auslassen -li[2:] #=> [4, 3] -# Das Ende auslassen -li[:3] #=> [1, 2, 4] -# Jeden Zweiten Eintrag auswählen -li[::2] # =>[1, 4] -# Eine umgekehrte Kopie zurückgeben -li[::-1] # => [3, 4, 2, 1] -# Jegliche Kombination dieser Syntax machen fortgeschrittene Slices möglich -# li[Start:Ende:Schritt] - -# Ein bestimmtes Element mit del aus der Liste entfernen -del li[2] # li ist jetzt [1, 2, 3] - -# Listen können addiert werden -li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen - -# Listen mit extend verknüpfen -li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6] - -# Mit in auf Existenz eines Elements prüfen -1 in li #=> True - -# Die Länge der Liste mit len ermitteln -len(li) #=> 6 - - -# Tupel sind wie Listen, nur unveränderlich. -tup = (1, 2, 3) -tup[0] #=> 1 -tup[0] = 3 # Löst einen TypeError aus - -# Wir können all diese Listen-Dinge auch mit Tupeln anstellen -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True - -# Wir können Tupel (oder Listen) in Variablen entpacken -a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3 -# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen -d, e, f = 4, 5, 6 -# Es ist kinderleicht zwei Werte zu tauschen -e, d = d, e # d ist nun 5 und e ist nun 4 - - -# Dictionarys (Wörterbucher) speichern Schlüssel-Werte-Paare -empty_dict = {} -# Hier ein gefülltes Wörterbuch -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Wir können Einträge mit [] nachschlagen -filled_dict["one"] #=> 1 - -# So holen wir alle Keys (Schlüssel) als Liste -list(filled_dict.keys()) #=> ["three", "two", "one"] -# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert. -# Einzelne Resultate können anders angeordnet sein. - -# Alle Values (Werte) als Liste -list(filled_dict.values()) #=> [3, 2, 1] -# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln. - -# Das Vorhandensein eines Schlüssels im Wörterbuch mit "in" prüfen -"one" in filled_dict #=> True -1 in filled_dict #=> False - -# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus -filled_dict["four"] # KeyError - -# Mit der get-Methode verhindern wir das -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None -# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt -filled_dict.get("one", 4) #=> 1 -filled_dict.get("four", 4) #=> 4 - -# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen -filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt -filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5 - -# Einträge zu einem Wörterbuch hinzufügen -filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} -#filled_dict["four"] = 4 # noch ein Weg, Werte hinzuzufügen - -# Schlüssel von einem Wörterbuch entfernen -del filled_dict["one"] # Entfert den Schlüssel "one" - - -# Sets speichern Mengen -empty_set = set() -# Initialisieren wir ein Set mit ein paar Werten -some_set = {1, 1, 2, 2, 3, 4} # some_set ist jetzt {1, 2, 3, 4} - -# Neue Variablen können einer Menge gleichgesetzt werden -filled_set = some_set - -# Mehr Elemente hinzufügen -filled_set.add(5) # filled_set ist jetzt {1, 2, 3, 4, 5} - -# Schnittmengen werden mit & gebildet -other_set = {3, 4, 5, 6} -filled_set & other_set #=> {3, 4, 5} - -# Mengen werden mit | vereinigt -filled_set | other_set #=> {1, 2, 3, 4, 5, 6} - -# Die Differenz einer Menge mit - bilden -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# Auf Vorhandensein von Elementen mit in prüfen -2 in filled_set #=> True -10 in filled_set #=> False - - -#################################################### -## 3. Kontrollstruktur und Iteratoren -#################################################### - -# Erstellen wir mal eine Variable -some_var = 5 - -# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig! -# gibt "some_var ist kleiner als 10" aus -if some_var > 10: - print("some_var ist viel größer als 10.") -elif some_var < 10: # Dieser elif-Absatz ist optional. - print("some_var ist kleiner als 10.") -else: # Das hier ist auch optional. - print("some_var ist tatsächlich 10.") - - -""" -For-Schleifen iterieren über Listen -Ausgabe: - hund ist ein Säugetier - katze ist ein Säugetier - maus ist ein Säugetier -""" -for animal in ["hund", "katze", "maus"]: - # Wir können Strings mit format() formatieren - print("{} ist ein Säugetier".format(animal)) - -""" -`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder -Ausgabe: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(unten, oben)" gibt eine Liste von der unteren Zahl bis zur oberen Zahl aus -Ausgabe: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -While-Schleifen laufen, bis eine Bedingung erfüllt ist. -Ausgabe: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Kurzform für x = x + 1 - -# Ausnahmebehandlung mit einem try/except-Block -try: - # Mit raise wird ein Fehler ausgegeben - raise IndexError("Das hier ist ein Index-Fehler") -except IndexError as e: - pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären. -except (TypeError, NameError): - pass # Mehrere Fehler können zusammen geklärt werden, falls erforderlich. -else: # Optional, hinter allen except-Blöcken - print("Keine Probleme!") # Wird nur ausgeführt, wenn keine Ausnahmen aufgetreten sind -finally: # Wird immer ausgeführt - print("Hier können wir Ressourcen aufräumen") - -# alternativ zu einem try/finally Block um Aufzuräumen: -with open("meineDatei.txt") as f: - for line in f: - print(line) - -# Python bietet ein fundamentales Konzept der Iteration. -# Das Objekt, auf das die Iteration, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable". -# Die range Methode gibt ein solches Objekt aus. - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) #=> range(1,10). Dies ist ein "iterable" Objekt. - -# Über dieses können wir auch iterieren -for i in our_iterable: - print(i) # Gibt one, two, three aus - -# Allerdings können wir die einzelnen Elemente nicht mit ihrem index ausgeben -our_iterable[1] # TypeError - -# Ein iterable ist ein Objekt, das weiß wie es einen Iteratoren erschafft. -our_iterator = iter(our_iterable) - -# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es gerade hat während wir durch es gehen. -# Das jeweils nächste Objekt bekommen wir mit "next()" -next(our_iterator) #=> "one" - -# Es hält den vorherigen Status -next(our_iterator) #=> "two" -next(our_iterator) #=> "three" - -# Nachdem alle Daten ausgegeben worden sind, kommt eine StopIterator Ausnahme zurück -next(our_iterator) # Gibt StopIteration aus - -# Alle Elemente können mit "list()" ausgegeben werden -list(filled_dict.keys()) #=> ["one", "two", "three"] - - - -#################################################### -## 4. Funktionen -#################################################### - -# Mit def neue Funktionen erstellen -def add(x, y): - print("x ist %s und y ist %s" % (x, y)) - return x + y # Werte werden mit return zurückgegeben - -# Funktionen mit Parametern aufrufen -add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück - -# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente -add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden. - -# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# Wir können auch Funktionen mit beliebiger Anzahl -# Schlüsselwort-Argumenten definieren -def keyword_args(**kwargs): - return kwargs - -# Rufen wir es mal auf, um zu sehen, was passiert -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} - -# Wir können beides gleichzeitig machen, wenn wir wollen -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) Ausgabe: - (1, 2) - {"a": 3, "b": 4} -""" - -# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen! -# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4) -all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4) -all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4) - - -# Anwendungsbereich von Funktionen -x = 5 - -def setX(num): - # lokale Variable x ist nicht die globale Variable x - x = num # => 43 - print (x) # => 43 - -def setGlobalX(num): - global x - print (x) # => 5 - x = num # globale Variable x ist jetzt 6 - print (x) # => 6 - -setX(43) -setGlobalX(6) - - -# Python hat First-Class-Funktionen -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) #=> 13 - -# Es gibt auch anonyme Funktionen -(lambda x: x > 2)(3) #=> True - -# Es gibt auch Funktionen höherer Ordnung als Built-Ins -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] - -#################################################### -## 5. Klassen -#################################################### - -# Wir bilden die Unterklasse eines Objekts, um Klassen zu erhalten. -class Human(object): - - # Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt - species = "H. sapiens" - - # Ein simpler Konstruktor - def __init__(self, name): - # Wir weisen das Argument name dem name-Attribut der Instanz zu - self.name = name - - # Eine Instanzmethode. Alle Methoden erhalten self als erstes Argument. - def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) - - # Eine Klassenmethode wird von allen Instanzen geteilt. - # Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen - @classmethod - def get_species(cls): - return cls.species - - # Eine statische Methode wird ohne Klasse oder Instanz aufgerufen - @staticmethod - def grunt(): - return "*grunt*" - - -# Eine Instanz einer Klasse erstellen -i = Human(name="Ian") -print(i.say("hi")) # gibt "Ian: hi" aus - -j = Human("Joel") -print(j.say("hello")) #gibt "Joel: hello" aus - -# Rufen wir mal unsere Klassenmethode auf -i.get_species() #=> "H. sapiens" - -# Ändern wir mal das gemeinsame Attribut -Human.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" - -# Aufruf der statischen Methode -Human.grunt() #=> "*grunt*" - - -#################################################### -## 6. Module -#################################################### - -# Wir können Module importieren -import math -print(math.sqrt(16)) #=> 4.0 - -# Wir können auch nur spezielle Funktionen eines Moduls importieren -from math import ceil, floor -print(ceil(3.7)) #=> 4.0 -print(floor(3.7)) #=> 3.0 - -# Wir können auch alle Funktionen eines Moduls importieren -# Warnung: Dies wird nicht empfohlen -from math import * - -# Wir können Modulnamen abkürzen -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Module sind in Python nur gewöhnliche Dateien. Wir -# können unsere eigenen schreiben und importieren. Der Name des -# Moduls ist der Dateiname. - -# Wir können auch die Funktionen und Attribute eines -# Moduls herausfinden. -import math -dir(math) - - -#################################################### -## 7. Fortgeschritten -#################################################### - -# Generatoren helfen um Code schnell und einfach zu schreiben -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Ein Generator erschafft Werte spontan -# Statt alle Werte auf einmal, wird bei jeder Iteration einer erschaffen. -# iteration. Das heißt, Werte größer als 15 werden nicht behandelt. -# Die range-Methode ist auch ein Generator. Im Fall einer Liste von 1-900000000 -# würde das sehr viel Zeit in Anspruch nehmen. -# Wenn wir eine variable mit einem Namen erschaffen wollen, das -# normalerweise mit einem Python - Schlüsselwort kollidieren würde, -# benutzen wir einen Unterstrich nach dem Wort. -range_ = range(1, 900000000) -# Alle Nummern bis zu einem Ergebnis von >=30 werden verdoppelt -for i in double_numbers(range_): - print(i) - if i >= 30: - break - - -# Dekoratoren -# In diesem Beispiel die Methode beg umwickelt say -# Beim Aufruf von beg, say wird aufgerufen -# Falls say_please true ist, ändert sich die ausgegebene Nachricht -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( - -``` - -## Lust auf mehr? - -### Kostenlos online (Englisch) - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) - -### Totholz (Englisch) - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/el-gr/python-gr.html.markdown b/el-gr/python-gr.html.markdown new file mode 100644 index 00000000..445b85ba --- /dev/null +++ b/el-gr/python-gr.html.markdown @@ -0,0 +1,1031 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] + - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] +filename: learnpython3-gr.py +lang: el-gr +--- + +Η Python δημιουργήθηκε από τον Guido van Rossum στις αρχές των 90s. Πλέον είναι μία από τις πιο +δημοφιλείς γλώσσες. Ερωτευεται κανείς την python για τη συντακτική της απλότητα. +Βασικά είναι εκτελέσιμος ψευδοκώδικας. + +Το Feedback είναι πάντα δεκτό! Μπορείτε να με βρείτε στο [@haritonaras](http://twitter.com/haritonaras) +ή τον αρχικό συγγραφέα στο [@louiedinh](http://twitter.com/louiedinh) ή στο +louiedinh [at] [google's email service] + +Σημείωση: Το παρόν άρθρο ασχολείται μόνο με την Python 3. Δείτε [εδώ](http://learnxinyminutes.com/docs/python/) αν θέλετε να μάθετε την παλιά Python 2.7 + +```python + +# Τα σχόλια μίας γραμμής ξεκινούν με # + +""" Τα σχόλια πολλαπλών γραμμών μπορούν + να γραφούν με τρία ", και συχνά χρησιμοποιούνται + ως documentation. +""" + +#################################################### +## 1. Primitive (πρωταρχικοί) Τύποι Δεδομένων και Τελεστές +#################################################### + +# Αφού έχει αριθμούς +3 # => 3 + +# Λογικά θα έχει και Μαθηματικά... +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# Η διαίρεση ακεραίων κάνει στρογγυλοποίηση προς τα κάτω για θετικούς και αρνητικούς αριθμούς +5 // 3 # => 1 +-5 // 3 # => -2 +5.0 // 3.0 # => 1.0 # works on floats too +-5.0 // 3.0 # => -2.0 + +# Το αποτέλεσμα της διαίρεσης είναι πάντα float +10.0 / 3 # => 3.3333333333333335 + +# Modulo τελεστής +7 % 3 # => 1 + +# Ύψωση σε δύναμη (x**y, x στην y-οστή δύναμη) +2**3 # => 8 + +# Ελέγχουμε την προτεραιότητα πράξεων με παρενθέσεις +(1 + 3) * 2 # => 8 + +# Οι Boolean τιμές είναι primitives (Σημ.: τα κεφαλαία) +True +False + +# άρνηση με το not +not True # => False +not False # => True + +# Boolean τελεστές +# Σημ. ότι τα "and" και "or" είναι case-sensitive +True and False # => False +False or True # => True + +# Τα True και False είναι 1 και 0 αλλά με διαφορετικά keywords +True + True # => 2 +True * 8 # => 8 +False - 5 # => -5 + +# Μπορούμε να δούμε τις αριθμητικές τιμές των True και False μέσω των τελεστών σύγκρισης +0 == False # => True +1 == True # => True +2 == True # => False +-5 != False # => True + +# Χρησιμοποιώντας τελεστές boolean σε ακεραίους, οι ακέραιοι γίνονται cast σε +# boolean ώστε να γίνει η αποτίμηση της έκφρασης. +# Το αποτέλεσμα όμως είναι non-cast, δηλαδή ίδιου τύπου με τα αρχικά ορίσματα +# Μην μπερδεύετε τις bool(ints) και bitwise and/or (&,|) +bool(0) # => False +bool(4) # => True +bool(-6) # => True +0 and 2 # => 0 +-5 or 0 # => -5 + +# Ισότητα == +1 == 1 # => True +2 == 1 # => False + +# Διάφορο != +1 != 1 # => False +2 != 1 # => True + +# Περισσότερες συγκρίσεις +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Κοιτάζουμε αν μία τιμή ανήκει σε ένα εύρος +1 < 2 and 2 < 3 # => True +2 < 3 and 3 < 2 # => False +# Το Chaining (αλυσίδωση? :P) κάνει το παραπάνω πιο όμορφα +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) το is ελέγχει αν δύο μεταβλητές αναφέρονται στο ίδιο αντικείμενο, +# αλλά το == ελέγχει αν τα αντικείμενα στα οποία αναφέρονται οι μεταβλητές έχουν τις ίδιες τιμές +a = [1, 2, 3, 4] # το a δείχνει σε μία νέα λίστα, [1,2,3,4] +b = a # το b δείχνει στο αντικείμενο που δείχνει το a +b is a # => True, a και b αναφέρονται στο ίδιο αντικείμενο +b == a # => True, τα αντικείμενα των a κι b είναι ίσα +b = [1, 2, 3, 4] # Το b δείχνει σε μία νέα λίστα, [1, 2, 3, 4] +b is a # => False, a και b δεν αναφέρονται στο ίδιο αντικείμενο +b == a # => True, τα αντικείμενα των a και b είναι ίσα + +# Τα Strings (συμβολοσειρές) δημιουργούνται με " ή ' +"This is a string." +'This is also a string.' + +# Μπορούμε και να προσθέτουμε Strings, αλλά προσπαθήστε να μην το κάνετε +"Hello " + "world!" # => "Hello world!" +# Τα String literals (αλλά όχι οι μεταβλητές) μπορούν να συντμιθούν και χωρίς το '+' +"Hello " "world!" # => "Hello world!" + +# Μπορούμε να φερθούμε σε string σαν να είναι λίστα από χαρακτήρες +"This is a string"[0] # => 'T' + +# Μπορούμε να βρούμε το μήκος ενός string +len("This is a string") # => 16 + +# Το .format μπορεί να χρησιμοποιηθεί για να μορφοποιήσουμε strings, όπως εδώ: +"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" + +# Μπορείς να επαναλάβεις τα ορίσματα του formatting για να γλιτώσεις λίγο χρονο +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# Μπορείς να χρησιμοποιήσεις keywords αν βαριέσαι το μέτρημα. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" + +# Αν ο κώδικας Python 3 που γράφεις πρόκειται να τρέξει και με python 2.5 ή παλιότερη +# μπορείς επίσης να χρησιμοποιήσεις το παλιό τρόπο για formatting: +"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" + +# Μπορείς επίσης να μορφοποιήσεις χρησιμοποιώντας τα f-strings / formatted string literals (σε Python 3.6+) +name = "Reiko" +f"She said her name is {name}." # => "She said her name is Reiko" +# Μπορείς βασικά να βάλεις οποιαδήποτε έκφραση Python στα άγκιστρα και θα εμφανιστεί στο string. +f"{name} is {len(name)} characters long." + + +# το None είναι ένα αντικείμενο (object) +None # => None + +# Μη χρησιμοποιείτε το σύμβολο ισότητας "==" για να συγκρίνετε αντικείμενα με το None +# Χρησιμοποιείτε το "is". Αυτό ελέγχει για ισότητα της ταυτότητας του αντικειμένου. +"etc" is None # => False +None is None # => True + +# Τα None, 0, και τα κενά strings/lists/dicts/tuples αποτιμούνται στην τιμή False +# All other values are True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +## 2. Μεταβλητές (variables) και Συλλογές (collections) +#################################################### + +# Η Python έχει μία συνάρτηση print() +print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! + +# By default, η συνάρτηση print() τυπώνει και ένα χαρακτήρα αλλαγής γραμμμής στο τέλος +# Χρησιμοποιείτε το προαιρετικό όρισμο end για να τυπώνει οτιδήποτε άλλο +print("Hello, World", end="!") # => Hello, World! + +# Απλός τρόπος για να πάρουμε δεδομένα εισόδου από το console +input_string_var = input("Enter some data: ") # επιστρέφει τα δεδομένα ως string +# Σημ.: Στις προηγούμενες εκδόσεις της Python, η μέθοδος input() ονομαζόταν raw_input() + +# Δεν υπάρχουν δηλώσεις, μόνο αναθέσεις τιμών. +# Η σύμβαση είναι να χρησιμοποιούμε μικρά γράμματα με κάτω παύλες +some_var = 5 +some_var # => 5 + +# Η πρόσβαση σε μεταβλητή που δεν έχει λάβει τιμή είναι εξαίρεση +# Δες τον Έλεγχο Ροής για να μάθεις περισσότερα για το χειρισμό εξαιρέσεων +some_unknown_var # Προκαλέι ένα NameError + +# Η παρακάτω έκφραση μπορεί να χρησιμποιηθεί ισοδύναμα με τον τελεστή '?' της C +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Οι λίστες κρατούν ακολουθίς +li = [] +# Μπορείς να αρχίσεις με μία προ-γεμισμένη λίστα +other_li = [4, 5, 6] + +# Και να βάλεις πράγματα στο τέλος με την μέθοδο append +li.append(1) # η li τώρα είναι [1] +li.append(2) # η li τώρα είναι [1, 2] +li.append(4) # η li τώρα είναι [1, 2, 4] +li.append(3) # η li τώρα είναι [1, 2, 4, 3] +# Αφαιρούμε από το τέλος με την μέθοδο pop +li.pop() # => 3 και η li γίνεται [1, 2, 4] +# Ας βάλουμε το 3 πίσω στη θέση του +li.append(3) # η li γίνεται πάλι [1, 2, 4, 3]. + +# Προσπελαύνουμε τις λίστες όπως τους πίνακες σε άλλες γλώσσες +li[0] # => 1 +# Το τελευταίο στοιχείο... +li[-1] # => 3 + +# Όταν βγαίνουμε εκτός ορίων της λίστας προκαλείται IndexError +li[4] # προκαλεί IndexError + +# Μπορείς να δεις ranges μιας λίστας με το slice syntax ':' +# Ο δείκτης εκίνησης περιλαμβάνεται στο διάστημα, ο δείκτης τερματισμού όχι +# (είναι ανοικτό/κλειστό διάστημα για τους φίλους των μαθηματικών) +li[1:3] # => [2, 4] +# Αγνόησε την αρχή και επίστρεψε τη λίστα +li[2:] # => [4, 3] +# Αγνόησε το τέλος και επίστρεψε τη λίστα +li[:3] # => [1, 2, 4] +# Διάλεξε κάθε δεύτερο στοιχείο +li[::2] # =>[1, 4] +# Επίστρεψε ένα reversed αντίγραφο της λίστας +li[::-1] # => [3, 4, 2, 1] +# Χρησιμοποιείστε οποιαδήποτε συνδυασμό αυτών για να φτιάξετε πιο προχωρημένα slices +# li[start:end:step] + +# Φτιάξε ένα αντίγραφο της λίστας χρησιμοποιώντας slices +li2 = li[:] # => li2 = [1, 2, 4, 3] αλλά το (li2 is li) επιστρέφει False + +# Αφαίρεσε οποιοδήποτε στοιχείο από λίστα με την εντολή "del" +del li[2] # η li γίνεται [1, 2, 3] + +# Αφαιρούμε το πρώτο στιγμυότυπο μιας τιμής +li.remove(2) # η li γίνεται [1, 3] +li.remove(2) # Προκαλεί ένα ValueError καθώς το 2 δεν βρίσκεται στη λίστα. + +# Εισαγωγή ενός στοιχείου σε συγκεκριμένη θέση +li.insert(1, 2) # η li γίνεται πάλι [1, 2, 3] + +# Βρες το index (δείκτη) του πρώτου στοιχείου με τιμή ίση με το όρισμα +li.index(2) # => 1 +li.index(4) # Προκαλεί ValueError καθώς το 4 δεν βρίσκεται στη λίστα + +# Μπορείς να προσθέτεις λίστες +# Σημ.: οι τιμές των li, other_li δεν αλλάζουν. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Σύντμιση λιστών με τη μέθοδο "extend()" +li.extend(other_li) # Τώρα η li είναι [1, 2, 3, 4, 5, 6] + +# Ελεγχος της ύπαρξης στοιχείου σε λίστα με το "in" +1 in li # => True + +# Εξατάζουμε το μήκος με "len()" +len(li) # => 6 + + +# Τα Tuples είναι σαν τις λίστες αλλά είναι αμετάβλητα (immutable). +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Προκαλεί TypeError + +# Σημειώστε ότι ένα tuple μήκους 1 πρέπει να έχει ένα κόμμα μετά το τελευταίο στοιχείο +# αλλά τα tuples άλλων μηκών, ακόμα και μηδενικού μήκους, δεν χρειάζονται κόμμα. +type((1)) # => +type((1,)) # => +type(()) # => + +# Μπορείς να εφαρμόσεις τις περισσότερες μεθόδους των λιστών και στα tuples +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Μπορείς να κάνεις unpack/"ξεπακετάρεις" tuples σε μεταβλητές +a, b, c = (1, 2, 3) # a == 1, b == 2 και c == 3 +# Μπορείς επίσης να επεκτείνεις το unpacking +a, *b, c = (1, 2, 3, 4) # a == 1, b == [2, 3] και c == 4 +# Τα Tuples δημιουργούνται by deafult αν δεν βάλεις παρενθέσεις +d, e, f = 4, 5, 6 # το tuple 4, 5, 6 "ξεπακετάρεται" στις μεταβλητές d, e και f +# αντίστοιχα έτσι ώστε να γίνεται d = 4, e = 5 and f = 6 +# Δείτε πόσο εύκολα μπορούμε να εναλλάσουμε δύο τιμές +e, d = d, e # το d παίρνει την τιμή 5 και το e παίρνει την τιμή 4 + + +# Τα λεξικά (Dictionaries) αποθηκεύουν απεικονίσεις από κλειδιά σε τιμές +empty_dict = {} +# Εδώ έχουμε ένα προ-γεμισμένο dictionary +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Σημ. ότι τα κλειδιά για τα dictionaries πρέπει να είναι αμετάβλητοι τύποι +# (immutable) αυτό γίνετια για να διασφαλίσουμε ότι τα κλειδιά μπορούν να +# μετατρέπονται σε σταθερές τιμές κατακερματισμού (hash values) για γρήγορη εύρεση. +# Μερικοί αμετάβλητοι τύποι είναι τα ints, floats, strings, tuples. +invalid_dict = {[1,2,3]: "123"} # => Προκαλεί TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Οι τιμές όμως μπορούν να έχουν οποιοδήποτε τύπο. + +# Βρίσκουμε τιμές με [] +filled_dict["one"] # => 1 + +# Μπορείς να πάρεις όλα τα κλειδιά με τη μέθοδο "keys()". +# Πρέπει να "τυλίξουμε" την κλήση με list() για να το μετατρέψουμε σε λίστα +# Θα μιλήσουμε για αυτά αργότερα. Σημ. - σε εκδόσεις Python < 3.7, η σειρά που +# εμφανίζονται τα κλειδιά δεν είναι εγγυημένη. Τα αποτελέσματά σας ίσως να μην +# είναι ακριβώς ίδια με τα παρακάτω. Στην έκδοση 3.7 πάντως, τα αντικείμενα του +# λεξικού διατηρούν τη σειρά με την οποία εισήχθησαν στο dictionary +list(filled_dict.keys()) # => ["three", "two", "one"] σε Python <3.7 +list(filled_dict.keys()) # => ["one", "two", "three"] σε Python 3.7+ + +# Παίρνουμε όλες τις τιμές ενός iterable με τη μέθοδο "values()". Και πάλι +# χρειάζεται να το περιτυλίξουμε σε list() +# Σημ. - όπως παραπάνω σχετικά με τη σειρά των keys +list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 +list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ + +# Έλεγχος της ύπαρξης κλειδιών σε ένα dictionary με το "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# Αν ψάξεις την τιμή ανύπαρκτου κλειδιού προκαλείται KeyError +filled_dict["four"] # KeyError + +# Χρησιμοποιούμε τη μέθοδο "get()" για να αποφύγουμε το KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# στο δεύτερο argument της get() μπορούμε να βάλουμε μία τιμή που πρέπει να +# επιστρέψει αν δεν υπάρχει το key που ψάχνουμε +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# το "setdefault()" εισάγει στο dictionary μόνο αν δεν υπάρχει το κλειδί +filled_dict.setdefault("five", 5) # filled_dict["five"] γίνεται 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] μένει 5 (υπαρκτό κλειδί) + +# Προσθήκη σε dictionary +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict["four"] = 4 # β' τρόπος + +# Αφαίρεση κλειδιών από dictionary με del +del filled_dict["one"] # Αφαιρεί το κλειδί "one" από το filled_dict + +# Από την Python 3.5 μπορείς να χρησιμοποιήσεις και πρόσθετες επιλογές για unpacking +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + + +# τα Sets -όπως όλοι περιμένουμε- αποθηκεύουν σύνολα +empty_set = set() +# Αρχικοποιούμε ένα set με μερικές τιμές. Ναι, μοιάζει λίγο με dictionary, Sorry. +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# Παρομοίως με τα κλειδιά του dictionary, τα στοιχεία ενός συνόλου πρέπει να είναι +# αμετάβλητα (immutable) +invalid_set = {[1], 1} # => Προκαλεί TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Προσθέτουμε άλλο ένα στοιχείο στο σύνολο +filled_set = some_set +filled_set.add(5) # το filled_set είναι τώρα {1, 2, 3, 4, 5} +# Τα σύνολα δεν έχουν διπλοτυπα αντικείμενα +filled_set.add(5) # το σύνολο παραμένει ίδιο {1, 2, 3, 4, 5} + +# το & κάνει την τομή δύο συνόλων. +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# και το | την ένωση +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Η διαφορά συνόλων με το - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Το ^ επιστρέφει τη συμμετρική διαφορά +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Ελεγχος για το αν το δεξιά σύνολο είναι υπερσύνολο του δεξιού +{1, 2} >= {1, 2, 3} # => False + +# Ελεγχος για το αν το δεξιά σύνολο είναι υποσύνολο του δεξιού +{1, 2} <= {1, 2, 3} # => True + +# με το in κάνουμε έλεγχο ύπαρξης στοιχείο σε σετ +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Έλεγχος Ροής και Iterables +#################################################### + +# Φτιάχνουμε μία μεταβλητή +some_var = 5 + +# Εδώ έχουμε ένα if statement. Η στοίχιση είναι σημαντική στην Python! +# Η σύμβαση είναι να χρησιμοποιούμε 4 κενά, όχι tabs. +# Το παρακάτω τυπώνει "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # το (else if) -> elif μέρος είναι προαιρετικό. + print("some_var is smaller than 10.") +else: # και το else είναι προαιρετικό. + print("some_var is indeed 10.") + + +""" +τα for loops τρέχουν πάνω σε lists +το παρακάτω τυπώνει: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # You can use format() to interpolate formatted strings + print("{} is a mammal".format(animal)) + +""" +το "range(number)" επιστρέφει ένα iterable με αριθμούς +από το μηδέν μέχρι τον δωσμένο αριθμό number (κλειστό/ανοικτό διάστημα) +Το παρακάτω τυπώνει: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +το "range(lower, upper)" επιστρέφει ένα iterable με αριθμούς +από το lower εώς το upper (κλειστό/ανοικτό διάστημα) +το παρακάτω τυπώνει: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +το "range(lower, upper, step)" επιστρέφει ένα iterable με αριθμούς +από το lower μέχρι το upper, με βήμα step +αν δεν δώσουμε τιμή βήματος, το default βήμα είναι 1. +το παρακάτω τυπώνει: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +τα While loops τρέχουν μέχρι μία συνθήκη να γίνει ψευδής. +το παρακάτω τυπώνει: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Shorthand for x = x + 1 + +# Χειριζόμαστε εξαιρέσεις με ένα try/except block +try: + # Χρησιμοποιούμε το "raise" για να πετάξουμε ένα error + raise IndexError("This is an index error") +except IndexError as e: + pass # το Pass δεν κάνει τίποτα. Συνήθως κάνουμε ανάκτηση. +except (TypeError, NameError): + pass # Μπορούμε να χειριζόμαστε πολλές εξαιρέσεις μαζί, αν χρειαστεί +else: # Προαιρετικό στο try/except block. Πρέπει να ακολουθεί όλα τα except blocks + print("All good!") # τρέχει μόνο αν ο κώδικας στο try δεν προκαλεί εξαιρέσεις +finally: # Εκτελείται ό,τι και να γίνει + print("We can clean up resources here") + +# Αντί για try/finally για να καθαρίσουμε τους πόρους, μπορούμε να χρησιμοποιούμε το +# with expression as target: + pass to cleanup resources you can use a with statement +with open("myfile.txt") as f: + for line in f: + print(line) + +# Η Python προσφέρει μία θεμελιώδη αφαίρεση (abstraction) που λέγεται Iterable. +# iterable είναι ένα αντικείμενο που μπορεί να χρησιμοποιηθεί ως ακολουθία. +# Το αντικείμενο που επιστρέφει η συνάρτηση range, είναι ένα iterable. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['one', 'two', 'three']). +# Αυτό είναι ένα αντικείμενο που υλοποιεί την iterable διεπαφή μας. + +# μπορούμε να τρέχουμε loops πάνω του. +for i in our_iterable: + print(i) # Prints one, two, three + +# Ωστόσο δεν μπορούμε να προσπελάσουμε τα στοιχεία του με index. +our_iterable[1] # προκαλεί a TypeError + +# Ένα iterable είναι ένα αντικείμενο που ξέρει πώς να δημιουργήσει έναν iterator. +our_iterator = iter(our_iterable) + +# Ο iterator μας είναι ένα αντικείμενο που μπορεί να θυμάται την κατάσταση όπως το διατρέχουμε. +# Παίρνουμε το επόμενο αντικείμενο με το "next()" +next(our_iterator) # => "one" + +# Διατηρεί την κατάσταση καθώς επαναλαμβάνουμε. +next(our_iterator) # => "two" +next(our_iterator) # => "three" + +# Όταν ο iterator έχει επιστρέψει όλα τα δεδομένα του, προκαλεί ένα μια εξαίρεση StopIteration. +next(our_iterator) # προκαλεί StopIteration + +# Μπορείς να πάρεις όλα τα αντικείμενα ενός iteratior καλώντας list() πάνω του. +list(filled_dict.keys()) # => Επιστρέφει ["one", "two", "three"] + + +#################################################### +## 4. Συναρτήσεις +#################################################### + +# Χρησιμποιούμε το "def" για να ορίσουμε νέες συναρτήσεις +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # επιστρέφει τιμές με την εντολή return + +# Καλούμε συναρτήσεις με παραμέτρους +add(5, 6) # => τυπώνει "x is 5 and y is 6" και επιστρέφει 11 + +# Ένας άλλος τρόπος να καλέσεις συνάρτησει είναι με keyword arguments (ορίσματα λέξεις-κλειδιά) +add(y=6, x=5) # τα Keyword arguments μπορούν να δωθούν με οποιαδήποτε σειρά. + +# Μπορείς να ορίσεις συναρτήσεις που δέχονται μεταβλητό πλήθος ορισμάτων +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Μπορούμε να ορίσουμε και συναρτήσεις που δέχονται μεταβλητό πλήθος keyword arguments +def keyword_args(**kwargs): + return kwargs + +# Για να δούμε τι γίνεται αν την καλέσουμε +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# Μπορείς να κάνεις και τα δύο ταυτόχρονα αν θες +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) τυπώνει: + (1, 2) + {"a": 3, "b": 4} +""" + +# Όταν καλείς συναρτήσεις μπορείς να κάνεις και το αντίστροφο από args/kwargs! +# Χρησιμοποίησε το * για να επεκτείνεις tuples και χρησιμοποίησε το ** για να επεκτείλεις kwargs +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # ισοδύναμο με all_the_args(1, 2, 3, 4) +all_the_args(**kwargs) # ισοδύναμο με all_the_args(a=3, b=4) +all_the_args(*args, **kwargs) # ισοδύναμο με all_the_args(1, 2, 3, 4, a=3, b=4) + +# Επιστρέφουμε πλειάδα τιμών (με tuple assignments) +def swap(x, y): + return y, x # Επιστρέφει πολλές τιμές ως tuple χωρίς την παρένθεση + # (Σημ.: οι παρενθέσεις έχουν παραλειφθεί αλλά μπορούν να γραφούν) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Ξανά, οι παρενθέσεις έχουν παραληφθεί αλλά μπορούν να γραφούν + +# Εμβέλεια συναρτήσεων +x = 5 + +def set_x(num): + # Η τοπική μεταβλητή x δεν είναι η ίδια με την global μεταβλητή x + x = num # => 43 + print(x) # => 43 + +def set_global_x(num): + global x + print(x) # => 5 + x = num # η global μεταβλητή x τώρα είναι 6 + print(x) # => 6 + +set_x(43) +set_global_x(6) + + +# Η Python έχει πρώτης τάξης συναρτήσεις +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Αλλά έχει και anonymous συναρτήσεις. +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Υπάρχουν ενσωματωμένες συναρτήσεις μεγαλύτερης τάξης +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# Μπορούμε να χρησιμοποιήσουμε list comprehensions για ωραία maps και filters +# το List comprehension αποθηκεύει την έξοδο ως μία λίστα που μπορεί και η ίδια +# να είναι μια εμφωλευμένη λίστα +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# Μπορείς επίσης να κατασκευάσεις set και dict comprehensions. +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Modules +#################################################### + +# Μπορείς να κάνεις import modules +import math +print(math.sqrt(16)) # => 4.0 + +# Μπορείς να πάρεις συγκεκριμένες συναρτήσεις από ένα module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Μπορείς να κάνεις import όλες τις συναρτήσεις από ένα module. +# Προσοχή: δεν προτείνεται +from math import * + +# Μπορείς να δημιουργείς συντομογραφίες για τα ονόματα των modules +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Τα Python modules είναι απλά αρχεία Python. Μπορείς να δημιουργήσεις τα δικά σου +# και να τα κάνεις import το όνομα του module είναι ίδιο με το όνομα του αρχείου + +# μπορείς να βρεις ποιες συναρτήσεις και γνωρίσματα ορίζονται στο module +import math +dir(math) + +# Αν έχεις ένα Python script με όνομα math.py στον ίδιο φάκελο με το τρέχον script +# το αρχείο math.py θα φορτωθεί και όχι το built-in Python module +# Αυτό συμβαίνει επειδή τα τοπικά αρχεία έχουν προτεραιότητα έναντι των built-in +# βιβλιοθηκών της Python + + +#################################################### +## 6. Κλάσεις - Classes +#################################################### + +# χρησιμοποιούμε το "class" statement για να δημιουργήσουμε μια κλάση +class Human: + + # Ένα γνώρισμα της κλάσης. Είναι κοινό για όλα τα στιγμιότυπα αυτής. + species = "H. sapiens" + + # Βασικός initializer, καλείται όταν δημιουργείται στιγμιότυπο της κλάσης. + # Σημ. οι διπλές κάτω παύλες πριν και μετά υποδηλώνουν αντικείμενα + # ή γνωρίσματα που χρησιμοποιούνται από την Python αλλά ζουν σε ελεγχόμενα από + # το χρήση namespaces. + # Μέθοδοι (ή αντικείμενα ή γνωρίσματα) σαν τα __init__, __str__, __repr__ κλπ + # είναι ειδικές μέθοδοι (λέγονται και dunder (double underscore) μέθοδοι) + # Δεν πρέπει να δηλώνεις δικές σου τέτοιες συναρτήσεις + def __init__(self, name): + # Εκχώρησε στο attribute name του object το όρισμα + self.name = name + + # Αρχικοποίησε την ιδιότητα + self._age = 0 + + # Μία μέθοδος στιγμιότυπου (instance method). Όλες οι μέθοδοι παίρνουν το + # "self" ως πρώτο όρισμα + def say(self, msg): + print("{name}: {message}".format(name=self.name, message=msg)) + + # Ακόμα μία instance method + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # Μία μέθοδος κλάσεις είναι κοινή ανάμεσα σε όλα τα instances. + # Καλούνται με calling class ώς πρώτο όρισμα + @classmethod + def get_species(cls): + return cls.species + + # Μία στατική μέθοδος καλείται χωρίς αναφορά σε κλάση ή στιγμιότυπο + @staticmethod + def grunt(): + return "*grunt*" + + # Ένα property είναι ακριβώς σαν ένα getter. + # Μετατρέπει τη μέθοδο age σε ένα γνώρισμα (attribute) μόνο-για-ανάγνωση + # με το ίδιο όνομα. + # Δεν χρειάζεται να γράφουμε τετριμένους getters και setters στην Python όμως. + @property + def age(self): + return self._age + + # Αυτό επιτρέπει στο property να γίνει set + @age.setter + def age(self, age): + self._age = age + + # Αυτό επιτρέπει σε ένα property να διαγραφεί + @age.deleter + def age(self): + del self._age + + +# Όταν ο διερμηνέας της Python διαβάζει αρχείο πηγαίου κώδικα τον εκτελεί όλο. +# Αυτός ο έλεγχος του __name__ σιγουρεύει ότι αυτό το block κώδικα τρέχει μόνο +# αυτό το module είναι το κύριο πρόγραμμα (και όχι imported) +if __name__ == '__main__': + # Δημιουργούμε στιγμιότυπο κλάσης + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # τα i και j είναι στιγμιότυπα του τύπου Human + + # Καλούμε τη μέθοδο της κλάσης + i.say(i.get_species()) # "Ian: H. sapiens" + # Αλλάζουμε το κοινό attribute των αντικειμένων της κλάσης + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Καλούμε τη static μέθοδο + print(Human.grunt()) # => "*grunt*" + + # Δεν μπορούμε να καλέσουμε τη στατική μέθοδο με ένα στιγμιότυπο + # επειδή το i.grunt() θα βάλει αυτόματα το self (δηλαδή το αντικείμενο i) ως όρισμα + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # Ενημερώνουμε το property για αυτό το στγμιότυπο + i.age = 42 + # Παίρνουμε το property + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # Διαγράφουμε το property + del i.age + # i.age # => αυτό θα προκαλούσε AttributeError + + +#################################################### +## 6.1 Κληρονομικότητα - Inheritance +#################################################### + +# Η κληρονομικότητα επιτρέπει σε νέες κλάσεις-παιδιά να οριστούν και να υιοθετήσουν +# μεθόδους και μεταβλητές από την κλάση-γονέα. + +# Χρησιμοποιώντας την κλάση Human που ορίστηκε πριν ως τη βασική κλάση (ή κλάση-γονέα) +# μπορούμε να ορίσουμε τις κλάσεις-παιδιά Superhero, που κληρονομεί μεταβλητές όπως +# "species", "name", και "age", καθώς και μεθόδους όπως "sing" και "grunt" +# από την κλάση Human, αλλά επίσης έχει τις δικές του ξεχωριστές ιδιότητες + +# Για να εκμεταλλευτείς το modularization κατά αρχείο, μπορείς να βάλεις την παραπάνω κλάση +# σε δικό της αρχείο, ας πούμε human.py + +# Για να κάνουμε import συναρτήσεις από άλλα αρχεία χρησιμοποιούμε το παρακάτω format +# from "filename-without-extension" import "function-or-class" + +from human import Human + + +# Προσδιόρισε την/τις parent class(es) ως παραμέτρους της κλάσης που ορίζεται +class Superhero(Human): + + # Αν η κλάση-παιδί πρέπει να κληρονομήσει όλους τους οεισμούς της κλάσης-γονέα + # χωρίς καμία αλλαγή, μπορείς απλά να γράψεις pass (και τίποτα άλλο) + # αλλά σε αυτή την περίπτωση είναι σχολιασμένο για να επιτρέψει τη δημιουργία + # ξεχωριστής κλάσης-παιδιού: + # pass + + # Η κλάση παιδί μπορεί να υπερφορτώσει (override) τα attributes της κλάσης από την οποία κληρονομεί + species = 'Superhuman' + + # Τα παιδιά αυτόματα, κληρονομούν τον constructo της κλάσης-γονέα + # συμπεριλαμβανομένων των ορισμάτων, αλλά μπορείς και να ορίσεις πρόσθετα ορίσματα + # ή ορισμούς και να κάνεις override τις μεθόδους, όπως τον constructor. + # Αυτός ο constructor κληρονομεί το όρισμα "name" από την κλάση Human και + # προσθέτει τα ορίσματα "superpower" και "movie": + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # πρόσθήκη επιπλέον attributes της κλάσης: + self.fictional = True + self.movie = movie + # έχετε το νου σας τις μεταβλητές (mutable) default τιμές, καθώς είναι κοινές + self.superpowers = superpowers + + # Η συνάρτηση "super" επιτρέπει την πρόσβαση στις μεθόδους της κλάσης-γονέα + # που είναι υπερφορτωμένες από το παιδί. Σε αυτή την περίπτωση τη μέθοδο __init__ + # Το παρακάτω καλεί τον constructor της κλάσης-γονέα: + super().__init__(name) + + # υπερφόρτωση της μεθόδου sing + def sing(self): + return 'Dun, dun, DUN!' + + # προσθήκη νέας μεθόδου που εφαρμόζεται σε στιγμιότυπα + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # Έλεγχος για το αν το στιγμιότυπο sup ανήκει στην κλάση Human + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') +# TODO: + # Παίρνουμε το Method Resolution search Order που χρησιμοποιούν οι getattr() και super() + # Αυτό το attribute είναι δυναμικό και μπορεί να ανανεωθεί + print(Superhero.__mro__) # => (, + # => , ) + + # Καλούμε μέθοδο της κλάσης-γονέα, αλλά χρησιμοποιεί το δικό της attribute + print(sup.get_species()) # => Superhuman + + # Καλεί την υπερφορτωμένη μέθοδο + print(sup.sing()) # => Dun, dun, DUN! + + # Καλεί μέθοδο από την κλάση Human + sup.say('Spoon') # => Tick: Spoon + + # Καλεί μέθοδο που υπάρχει μόνο στην κλάση Superhero + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # Κληρονομημένο class attribute + sup.age = 31 + print(sup.age) # => 31 + + # Attribute που υπάρχει μόνο στην μέσα στην κλάση Superhero + print('Am I Oscar eligible? ' + str(sup.movie)) + +#################################################### +## 6.2 Πολλαπλή Κληρονομικότητα - Multiple Inheritance +#################################################### + +# Ένας ακόμη ορισμός κλάσης +# bat.py +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # Αυτή η κλάση έχει επίσης μία μέθοδο say + def say(self, msg): + msg = '... ... ...' + return msg + + # Και τη δική της μέθοδο sonar + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + + +# Και ορίζουμε μία ακόμα κλάση που κληρονομεί από τις κλάσεις Superhero και Bat +# superhero.py +from superhero import Superhero +from bat import Bat + +# Ας πούμε αυτή την κλάση Batman +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # Τυπικά γα να κληρονομήουμε attributes πρέπει να καλέσουμε τη super: + # super(Batman, self).__init__(*args, **kwargs) + # Ωστόσο έχουμε να κάνουμε με πολλαπλή κληρονομικότητα εδώ, και το super() + # δουλεύει μόνο με την αμέσως ανώτερη κλάση στην ιεραρχία. + # Οπότε, καλούμε ρητά την __init__ για όλους τους πρόγονους + # Η χρήση των *args και **kwargs επιτρέπει έναν καθαρό τρόπο για να περνάμε ορίσματα + # με κάθε κλάση-γονέα να "βγάζει μία φλούδα από το κρεμμύδι". + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # υπερφορτώνουμε την τιμή του γνωρίσματος name + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # + # Λάβε το Method Resolution search Order που χρησιμοποιείται από το getattr() και το super(). + # Αυτό το attribute είναι δυναμικό και μπορεί να ενημερωθεί + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + # Καλεί την μέθοδο της κλάσης-πατέρα αλλά χρησιμοποιεί το attribute της δικής του κλάσης + print(sup.get_species()) # => Superhuman + + # Καλεί την υπερφορτωμένη μέθοδο + print(sup.sing()) # => nan nan nan nan nan batman! + + # Καλεί μέθοδο από την κλάση Human, επειδή μετράει η σειρά της κληρονομιάς + sup.say('I agree') # => Sad Affleck: I agree + + # Καλεί μέθοδο που ανήκει μόνο στον δεύτερο πρόγονο + print(sup.sonar()) # => ))) ... ((( + + # Attribute της κληρονομημένης κλάσης + sup.age = 100 + print(sup.age) # => 100 + + # Κληρονομούμενο attribute από τον δεύτερο πρόγονο του οποίου η default τιμή + # έχει υπερφορτωθεί. + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False + + + +#################################################### +## 7. Προχωρημένα +#################################################### + +# Με τους Generators μπορείς να γράψεις τεμπέλικο κώδικα. +def double_numbers(iterable): + for i in iterable: + yield i + i +# Οι Generators είναι αποδοτικοί από άποψη μνήμης επειδή φορτώνουν μόνο τα δεδομένα +# που είναι αναγκαία για να επεξεργαστούμε την επόμενη τιμή του iterable. +# Αυτό μας επιτρέπει να κάνουμε πράξεις σε τιμές που υπό άλλες συνθήκες θα ήταν +# απαγορευτικά μεγάλες. +for i in double_numbers(range(1, 900000000)): # το `range` είναι ένας generator. + print(i) + if i >= 30: + break + +# Όπως μπορείς να δημιουργήσεις list comprehension, έτσι μπορείς να δημιουργήσεις και +# generator comprehensions +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # τυπώνει -1 -2 -3 -4 -5 στο console/terminal + +# Μπορείς επίσης να μετατρέψεις ένα generator comprehension απευθείας σε λίστα. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# Decorators +# σε αυτό το παράδειγμα το `beg` τυλίγει το `say`. Αν το say_please είναι True τότε +# θα αλλάξει το μήνυμα που επιστρέφεται. +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +``` + +## Έτοιμοι για περισσότερα? + +### Δωρεάν Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/el-gr/python3-gr.html.markdown b/el-gr/python3-gr.html.markdown deleted file mode 100644 index 445b85ba..00000000 --- a/el-gr/python3-gr.html.markdown +++ /dev/null @@ -1,1031 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["evuez", "http://github.com/evuez"] - - ["Rommel Martinez", "https://ebzzry.io"] - - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] -filename: learnpython3-gr.py -lang: el-gr ---- - -Η Python δημιουργήθηκε από τον Guido van Rossum στις αρχές των 90s. Πλέον είναι μία από τις πιο -δημοφιλείς γλώσσες. Ερωτευεται κανείς την python για τη συντακτική της απλότητα. -Βασικά είναι εκτελέσιμος ψευδοκώδικας. - -Το Feedback είναι πάντα δεκτό! Μπορείτε να με βρείτε στο [@haritonaras](http://twitter.com/haritonaras) -ή τον αρχικό συγγραφέα στο [@louiedinh](http://twitter.com/louiedinh) ή στο -louiedinh [at] [google's email service] - -Σημείωση: Το παρόν άρθρο ασχολείται μόνο με την Python 3. Δείτε [εδώ](http://learnxinyminutes.com/docs/python/) αν θέλετε να μάθετε την παλιά Python 2.7 - -```python - -# Τα σχόλια μίας γραμμής ξεκινούν με # - -""" Τα σχόλια πολλαπλών γραμμών μπορούν - να γραφούν με τρία ", και συχνά χρησιμοποιούνται - ως documentation. -""" - -#################################################### -## 1. Primitive (πρωταρχικοί) Τύποι Δεδομένων και Τελεστές -#################################################### - -# Αφού έχει αριθμούς -3 # => 3 - -# Λογικά θα έχει και Μαθηματικά... -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 - -# Η διαίρεση ακεραίων κάνει στρογγυλοποίηση προς τα κάτω για θετικούς και αρνητικούς αριθμούς -5 // 3 # => 1 --5 // 3 # => -2 -5.0 // 3.0 # => 1.0 # works on floats too --5.0 // 3.0 # => -2.0 - -# Το αποτέλεσμα της διαίρεσης είναι πάντα float -10.0 / 3 # => 3.3333333333333335 - -# Modulo τελεστής -7 % 3 # => 1 - -# Ύψωση σε δύναμη (x**y, x στην y-οστή δύναμη) -2**3 # => 8 - -# Ελέγχουμε την προτεραιότητα πράξεων με παρενθέσεις -(1 + 3) * 2 # => 8 - -# Οι Boolean τιμές είναι primitives (Σημ.: τα κεφαλαία) -True -False - -# άρνηση με το not -not True # => False -not False # => True - -# Boolean τελεστές -# Σημ. ότι τα "and" και "or" είναι case-sensitive -True and False # => False -False or True # => True - -# Τα True και False είναι 1 και 0 αλλά με διαφορετικά keywords -True + True # => 2 -True * 8 # => 8 -False - 5 # => -5 - -# Μπορούμε να δούμε τις αριθμητικές τιμές των True και False μέσω των τελεστών σύγκρισης -0 == False # => True -1 == True # => True -2 == True # => False --5 != False # => True - -# Χρησιμοποιώντας τελεστές boolean σε ακεραίους, οι ακέραιοι γίνονται cast σε -# boolean ώστε να γίνει η αποτίμηση της έκφρασης. -# Το αποτέλεσμα όμως είναι non-cast, δηλαδή ίδιου τύπου με τα αρχικά ορίσματα -# Μην μπερδεύετε τις bool(ints) και bitwise and/or (&,|) -bool(0) # => False -bool(4) # => True -bool(-6) # => True -0 and 2 # => 0 --5 or 0 # => -5 - -# Ισότητα == -1 == 1 # => True -2 == 1 # => False - -# Διάφορο != -1 != 1 # => False -2 != 1 # => True - -# Περισσότερες συγκρίσεις -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Κοιτάζουμε αν μία τιμή ανήκει σε ένα εύρος -1 < 2 and 2 < 3 # => True -2 < 3 and 3 < 2 # => False -# Το Chaining (αλυσίδωση? :P) κάνει το παραπάνω πιο όμορφα -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# (is vs. ==) το is ελέγχει αν δύο μεταβλητές αναφέρονται στο ίδιο αντικείμενο, -# αλλά το == ελέγχει αν τα αντικείμενα στα οποία αναφέρονται οι μεταβλητές έχουν τις ίδιες τιμές -a = [1, 2, 3, 4] # το a δείχνει σε μία νέα λίστα, [1,2,3,4] -b = a # το b δείχνει στο αντικείμενο που δείχνει το a -b is a # => True, a και b αναφέρονται στο ίδιο αντικείμενο -b == a # => True, τα αντικείμενα των a κι b είναι ίσα -b = [1, 2, 3, 4] # Το b δείχνει σε μία νέα λίστα, [1, 2, 3, 4] -b is a # => False, a και b δεν αναφέρονται στο ίδιο αντικείμενο -b == a # => True, τα αντικείμενα των a και b είναι ίσα - -# Τα Strings (συμβολοσειρές) δημιουργούνται με " ή ' -"This is a string." -'This is also a string.' - -# Μπορούμε και να προσθέτουμε Strings, αλλά προσπαθήστε να μην το κάνετε -"Hello " + "world!" # => "Hello world!" -# Τα String literals (αλλά όχι οι μεταβλητές) μπορούν να συντμιθούν και χωρίς το '+' -"Hello " "world!" # => "Hello world!" - -# Μπορούμε να φερθούμε σε string σαν να είναι λίστα από χαρακτήρες -"This is a string"[0] # => 'T' - -# Μπορούμε να βρούμε το μήκος ενός string -len("This is a string") # => 16 - -# Το .format μπορεί να χρησιμοποιηθεί για να μορφοποιήσουμε strings, όπως εδώ: -"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" - -# Μπορείς να επαναλάβεις τα ορίσματα του formatting για να γλιτώσεις λίγο χρονο -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# Μπορείς να χρησιμοποιήσεις keywords αν βαριέσαι το μέτρημα. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" - -# Αν ο κώδικας Python 3 που γράφεις πρόκειται να τρέξει και με python 2.5 ή παλιότερη -# μπορείς επίσης να χρησιμοποιήσεις το παλιό τρόπο για formatting: -"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" - -# Μπορείς επίσης να μορφοποιήσεις χρησιμοποιώντας τα f-strings / formatted string literals (σε Python 3.6+) -name = "Reiko" -f"She said her name is {name}." # => "She said her name is Reiko" -# Μπορείς βασικά να βάλεις οποιαδήποτε έκφραση Python στα άγκιστρα και θα εμφανιστεί στο string. -f"{name} is {len(name)} characters long." - - -# το None είναι ένα αντικείμενο (object) -None # => None - -# Μη χρησιμοποιείτε το σύμβολο ισότητας "==" για να συγκρίνετε αντικείμενα με το None -# Χρησιμοποιείτε το "is". Αυτό ελέγχει για ισότητα της ταυτότητας του αντικειμένου. -"etc" is None # => False -None is None # => True - -# Τα None, 0, και τα κενά strings/lists/dicts/tuples αποτιμούνται στην τιμή False -# All other values are True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False - -#################################################### -## 2. Μεταβλητές (variables) και Συλλογές (collections) -#################################################### - -# Η Python έχει μία συνάρτηση print() -print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! - -# By default, η συνάρτηση print() τυπώνει και ένα χαρακτήρα αλλαγής γραμμμής στο τέλος -# Χρησιμοποιείτε το προαιρετικό όρισμο end για να τυπώνει οτιδήποτε άλλο -print("Hello, World", end="!") # => Hello, World! - -# Απλός τρόπος για να πάρουμε δεδομένα εισόδου από το console -input_string_var = input("Enter some data: ") # επιστρέφει τα δεδομένα ως string -# Σημ.: Στις προηγούμενες εκδόσεις της Python, η μέθοδος input() ονομαζόταν raw_input() - -# Δεν υπάρχουν δηλώσεις, μόνο αναθέσεις τιμών. -# Η σύμβαση είναι να χρησιμοποιούμε μικρά γράμματα με κάτω παύλες -some_var = 5 -some_var # => 5 - -# Η πρόσβαση σε μεταβλητή που δεν έχει λάβει τιμή είναι εξαίρεση -# Δες τον Έλεγχο Ροής για να μάθεις περισσότερα για το χειρισμό εξαιρέσεων -some_unknown_var # Προκαλέι ένα NameError - -# Η παρακάτω έκφραση μπορεί να χρησιμποιηθεί ισοδύναμα με τον τελεστή '?' της C -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# Οι λίστες κρατούν ακολουθίς -li = [] -# Μπορείς να αρχίσεις με μία προ-γεμισμένη λίστα -other_li = [4, 5, 6] - -# Και να βάλεις πράγματα στο τέλος με την μέθοδο append -li.append(1) # η li τώρα είναι [1] -li.append(2) # η li τώρα είναι [1, 2] -li.append(4) # η li τώρα είναι [1, 2, 4] -li.append(3) # η li τώρα είναι [1, 2, 4, 3] -# Αφαιρούμε από το τέλος με την μέθοδο pop -li.pop() # => 3 και η li γίνεται [1, 2, 4] -# Ας βάλουμε το 3 πίσω στη θέση του -li.append(3) # η li γίνεται πάλι [1, 2, 4, 3]. - -# Προσπελαύνουμε τις λίστες όπως τους πίνακες σε άλλες γλώσσες -li[0] # => 1 -# Το τελευταίο στοιχείο... -li[-1] # => 3 - -# Όταν βγαίνουμε εκτός ορίων της λίστας προκαλείται IndexError -li[4] # προκαλεί IndexError - -# Μπορείς να δεις ranges μιας λίστας με το slice syntax ':' -# Ο δείκτης εκίνησης περιλαμβάνεται στο διάστημα, ο δείκτης τερματισμού όχι -# (είναι ανοικτό/κλειστό διάστημα για τους φίλους των μαθηματικών) -li[1:3] # => [2, 4] -# Αγνόησε την αρχή και επίστρεψε τη λίστα -li[2:] # => [4, 3] -# Αγνόησε το τέλος και επίστρεψε τη λίστα -li[:3] # => [1, 2, 4] -# Διάλεξε κάθε δεύτερο στοιχείο -li[::2] # =>[1, 4] -# Επίστρεψε ένα reversed αντίγραφο της λίστας -li[::-1] # => [3, 4, 2, 1] -# Χρησιμοποιείστε οποιαδήποτε συνδυασμό αυτών για να φτιάξετε πιο προχωρημένα slices -# li[start:end:step] - -# Φτιάξε ένα αντίγραφο της λίστας χρησιμοποιώντας slices -li2 = li[:] # => li2 = [1, 2, 4, 3] αλλά το (li2 is li) επιστρέφει False - -# Αφαίρεσε οποιοδήποτε στοιχείο από λίστα με την εντολή "del" -del li[2] # η li γίνεται [1, 2, 3] - -# Αφαιρούμε το πρώτο στιγμυότυπο μιας τιμής -li.remove(2) # η li γίνεται [1, 3] -li.remove(2) # Προκαλεί ένα ValueError καθώς το 2 δεν βρίσκεται στη λίστα. - -# Εισαγωγή ενός στοιχείου σε συγκεκριμένη θέση -li.insert(1, 2) # η li γίνεται πάλι [1, 2, 3] - -# Βρες το index (δείκτη) του πρώτου στοιχείου με τιμή ίση με το όρισμα -li.index(2) # => 1 -li.index(4) # Προκαλεί ValueError καθώς το 4 δεν βρίσκεται στη λίστα - -# Μπορείς να προσθέτεις λίστες -# Σημ.: οι τιμές των li, other_li δεν αλλάζουν. -li + other_li # => [1, 2, 3, 4, 5, 6] - -# Σύντμιση λιστών με τη μέθοδο "extend()" -li.extend(other_li) # Τώρα η li είναι [1, 2, 3, 4, 5, 6] - -# Ελεγχος της ύπαρξης στοιχείου σε λίστα με το "in" -1 in li # => True - -# Εξατάζουμε το μήκος με "len()" -len(li) # => 6 - - -# Τα Tuples είναι σαν τις λίστες αλλά είναι αμετάβλητα (immutable). -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Προκαλεί TypeError - -# Σημειώστε ότι ένα tuple μήκους 1 πρέπει να έχει ένα κόμμα μετά το τελευταίο στοιχείο -# αλλά τα tuples άλλων μηκών, ακόμα και μηδενικού μήκους, δεν χρειάζονται κόμμα. -type((1)) # => -type((1,)) # => -type(()) # => - -# Μπορείς να εφαρμόσεις τις περισσότερες μεθόδους των λιστών και στα tuples -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Μπορείς να κάνεις unpack/"ξεπακετάρεις" tuples σε μεταβλητές -a, b, c = (1, 2, 3) # a == 1, b == 2 και c == 3 -# Μπορείς επίσης να επεκτείνεις το unpacking -a, *b, c = (1, 2, 3, 4) # a == 1, b == [2, 3] και c == 4 -# Τα Tuples δημιουργούνται by deafult αν δεν βάλεις παρενθέσεις -d, e, f = 4, 5, 6 # το tuple 4, 5, 6 "ξεπακετάρεται" στις μεταβλητές d, e και f -# αντίστοιχα έτσι ώστε να γίνεται d = 4, e = 5 and f = 6 -# Δείτε πόσο εύκολα μπορούμε να εναλλάσουμε δύο τιμές -e, d = d, e # το d παίρνει την τιμή 5 και το e παίρνει την τιμή 4 - - -# Τα λεξικά (Dictionaries) αποθηκεύουν απεικονίσεις από κλειδιά σε τιμές -empty_dict = {} -# Εδώ έχουμε ένα προ-γεμισμένο dictionary -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Σημ. ότι τα κλειδιά για τα dictionaries πρέπει να είναι αμετάβλητοι τύποι -# (immutable) αυτό γίνετια για να διασφαλίσουμε ότι τα κλειδιά μπορούν να -# μετατρέπονται σε σταθερές τιμές κατακερματισμού (hash values) για γρήγορη εύρεση. -# Μερικοί αμετάβλητοι τύποι είναι τα ints, floats, strings, tuples. -invalid_dict = {[1,2,3]: "123"} # => Προκαλεί TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # Οι τιμές όμως μπορούν να έχουν οποιοδήποτε τύπο. - -# Βρίσκουμε τιμές με [] -filled_dict["one"] # => 1 - -# Μπορείς να πάρεις όλα τα κλειδιά με τη μέθοδο "keys()". -# Πρέπει να "τυλίξουμε" την κλήση με list() για να το μετατρέψουμε σε λίστα -# Θα μιλήσουμε για αυτά αργότερα. Σημ. - σε εκδόσεις Python < 3.7, η σειρά που -# εμφανίζονται τα κλειδιά δεν είναι εγγυημένη. Τα αποτελέσματά σας ίσως να μην -# είναι ακριβώς ίδια με τα παρακάτω. Στην έκδοση 3.7 πάντως, τα αντικείμενα του -# λεξικού διατηρούν τη σειρά με την οποία εισήχθησαν στο dictionary -list(filled_dict.keys()) # => ["three", "two", "one"] σε Python <3.7 -list(filled_dict.keys()) # => ["one", "two", "three"] σε Python 3.7+ - -# Παίρνουμε όλες τις τιμές ενός iterable με τη μέθοδο "values()". Και πάλι -# χρειάζεται να το περιτυλίξουμε σε list() -# Σημ. - όπως παραπάνω σχετικά με τη σειρά των keys -list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 -list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ - -# Έλεγχος της ύπαρξης κλειδιών σε ένα dictionary με το "in" -"one" in filled_dict # => True -1 in filled_dict # => False - -# Αν ψάξεις την τιμή ανύπαρκτου κλειδιού προκαλείται KeyError -filled_dict["four"] # KeyError - -# Χρησιμοποιούμε τη μέθοδο "get()" για να αποφύγουμε το KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# στο δεύτερο argument της get() μπορούμε να βάλουμε μία τιμή που πρέπει να -# επιστρέψει αν δεν υπάρχει το key που ψάχνουμε -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# το "setdefault()" εισάγει στο dictionary μόνο αν δεν υπάρχει το κλειδί -filled_dict.setdefault("five", 5) # filled_dict["five"] γίνεται 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] μένει 5 (υπαρκτό κλειδί) - -# Προσθήκη σε dictionary -filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -filled_dict["four"] = 4 # β' τρόπος - -# Αφαίρεση κλειδιών από dictionary με del -del filled_dict["one"] # Αφαιρεί το κλειδί "one" από το filled_dict - -# Από την Python 3.5 μπορείς να χρησιμοποιήσεις και πρόσθετες επιλογές για unpacking -{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} -{'a': 1, **{'a': 2}} # => {'a': 2} - - - -# τα Sets -όπως όλοι περιμένουμε- αποθηκεύουν σύνολα -empty_set = set() -# Αρχικοποιούμε ένα set με μερικές τιμές. Ναι, μοιάζει λίγο με dictionary, Sorry. -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} - -# Παρομοίως με τα κλειδιά του dictionary, τα στοιχεία ενός συνόλου πρέπει να είναι -# αμετάβλητα (immutable) -invalid_set = {[1], 1} # => Προκαλεί TypeError: unhashable type: 'list' -valid_set = {(1,), 1} - -# Προσθέτουμε άλλο ένα στοιχείο στο σύνολο -filled_set = some_set -filled_set.add(5) # το filled_set είναι τώρα {1, 2, 3, 4, 5} -# Τα σύνολα δεν έχουν διπλοτυπα αντικείμενα -filled_set.add(5) # το σύνολο παραμένει ίδιο {1, 2, 3, 4, 5} - -# το & κάνει την τομή δύο συνόλων. -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# και το | την ένωση -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Η διαφορά συνόλων με το - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Το ^ επιστρέφει τη συμμετρική διαφορά -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Ελεγχος για το αν το δεξιά σύνολο είναι υπερσύνολο του δεξιού -{1, 2} >= {1, 2, 3} # => False - -# Ελεγχος για το αν το δεξιά σύνολο είναι υποσύνολο του δεξιού -{1, 2} <= {1, 2, 3} # => True - -# με το in κάνουμε έλεγχο ύπαρξης στοιχείο σε σετ -2 in filled_set # => True -10 in filled_set # => False - - - -#################################################### -## 3. Έλεγχος Ροής και Iterables -#################################################### - -# Φτιάχνουμε μία μεταβλητή -some_var = 5 - -# Εδώ έχουμε ένα if statement. Η στοίχιση είναι σημαντική στην Python! -# Η σύμβαση είναι να χρησιμοποιούμε 4 κενά, όχι tabs. -# Το παρακάτω τυπώνει "some_var is smaller than 10" -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # το (else if) -> elif μέρος είναι προαιρετικό. - print("some_var is smaller than 10.") -else: # και το else είναι προαιρετικό. - print("some_var is indeed 10.") - - -""" -τα for loops τρέχουν πάνω σε lists -το παρακάτω τυπώνει: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # You can use format() to interpolate formatted strings - print("{} is a mammal".format(animal)) - -""" -το "range(number)" επιστρέφει ένα iterable με αριθμούς -από το μηδέν μέχρι τον δωσμένο αριθμό number (κλειστό/ανοικτό διάστημα) -Το παρακάτω τυπώνει: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -το "range(lower, upper)" επιστρέφει ένα iterable με αριθμούς -από το lower εώς το upper (κλειστό/ανοικτό διάστημα) -το παρακάτω τυπώνει: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -το "range(lower, upper, step)" επιστρέφει ένα iterable με αριθμούς -από το lower μέχρι το upper, με βήμα step -αν δεν δώσουμε τιμή βήματος, το default βήμα είναι 1. -το παρακάτω τυπώνει: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) -""" - -τα While loops τρέχουν μέχρι μία συνθήκη να γίνει ψευδής. -το παρακάτω τυπώνει: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Shorthand for x = x + 1 - -# Χειριζόμαστε εξαιρέσεις με ένα try/except block -try: - # Χρησιμοποιούμε το "raise" για να πετάξουμε ένα error - raise IndexError("This is an index error") -except IndexError as e: - pass # το Pass δεν κάνει τίποτα. Συνήθως κάνουμε ανάκτηση. -except (TypeError, NameError): - pass # Μπορούμε να χειριζόμαστε πολλές εξαιρέσεις μαζί, αν χρειαστεί -else: # Προαιρετικό στο try/except block. Πρέπει να ακολουθεί όλα τα except blocks - print("All good!") # τρέχει μόνο αν ο κώδικας στο try δεν προκαλεί εξαιρέσεις -finally: # Εκτελείται ό,τι και να γίνει - print("We can clean up resources here") - -# Αντί για try/finally για να καθαρίσουμε τους πόρους, μπορούμε να χρησιμοποιούμε το -# with expression as target: - pass to cleanup resources you can use a with statement -with open("myfile.txt") as f: - for line in f: - print(line) - -# Η Python προσφέρει μία θεμελιώδη αφαίρεση (abstraction) που λέγεται Iterable. -# iterable είναι ένα αντικείμενο που μπορεί να χρησιμοποιηθεί ως ακολουθία. -# Το αντικείμενο που επιστρέφει η συνάρτηση range, είναι ένα iterable. - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']). -# Αυτό είναι ένα αντικείμενο που υλοποιεί την iterable διεπαφή μας. - -# μπορούμε να τρέχουμε loops πάνω του. -for i in our_iterable: - print(i) # Prints one, two, three - -# Ωστόσο δεν μπορούμε να προσπελάσουμε τα στοιχεία του με index. -our_iterable[1] # προκαλεί a TypeError - -# Ένα iterable είναι ένα αντικείμενο που ξέρει πώς να δημιουργήσει έναν iterator. -our_iterator = iter(our_iterable) - -# Ο iterator μας είναι ένα αντικείμενο που μπορεί να θυμάται την κατάσταση όπως το διατρέχουμε. -# Παίρνουμε το επόμενο αντικείμενο με το "next()" -next(our_iterator) # => "one" - -# Διατηρεί την κατάσταση καθώς επαναλαμβάνουμε. -next(our_iterator) # => "two" -next(our_iterator) # => "three" - -# Όταν ο iterator έχει επιστρέψει όλα τα δεδομένα του, προκαλεί ένα μια εξαίρεση StopIteration. -next(our_iterator) # προκαλεί StopIteration - -# Μπορείς να πάρεις όλα τα αντικείμενα ενός iteratior καλώντας list() πάνω του. -list(filled_dict.keys()) # => Επιστρέφει ["one", "two", "three"] - - -#################################################### -## 4. Συναρτήσεις -#################################################### - -# Χρησιμποιούμε το "def" για να ορίσουμε νέες συναρτήσεις -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # επιστρέφει τιμές με την εντολή return - -# Καλούμε συναρτήσεις με παραμέτρους -add(5, 6) # => τυπώνει "x is 5 and y is 6" και επιστρέφει 11 - -# Ένας άλλος τρόπος να καλέσεις συνάρτησει είναι με keyword arguments (ορίσματα λέξεις-κλειδιά) -add(y=6, x=5) # τα Keyword arguments μπορούν να δωθούν με οποιαδήποτε σειρά. - -# Μπορείς να ορίσεις συναρτήσεις που δέχονται μεταβλητό πλήθος ορισμάτων -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# Μπορούμε να ορίσουμε και συναρτήσεις που δέχονται μεταβλητό πλήθος keyword arguments -def keyword_args(**kwargs): - return kwargs - -# Για να δούμε τι γίνεται αν την καλέσουμε -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# Μπορείς να κάνεις και τα δύο ταυτόχρονα αν θες -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) τυπώνει: - (1, 2) - {"a": 3, "b": 4} -""" - -# Όταν καλείς συναρτήσεις μπορείς να κάνεις και το αντίστροφο από args/kwargs! -# Χρησιμοποίησε το * για να επεκτείνεις tuples και χρησιμοποίησε το ** για να επεκτείλεις kwargs -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # ισοδύναμο με all_the_args(1, 2, 3, 4) -all_the_args(**kwargs) # ισοδύναμο με all_the_args(a=3, b=4) -all_the_args(*args, **kwargs) # ισοδύναμο με all_the_args(1, 2, 3, 4, a=3, b=4) - -# Επιστρέφουμε πλειάδα τιμών (με tuple assignments) -def swap(x, y): - return y, x # Επιστρέφει πολλές τιμές ως tuple χωρίς την παρένθεση - # (Σημ.: οι παρενθέσεις έχουν παραλειφθεί αλλά μπορούν να γραφούν) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # Ξανά, οι παρενθέσεις έχουν παραληφθεί αλλά μπορούν να γραφούν - -# Εμβέλεια συναρτήσεων -x = 5 - -def set_x(num): - # Η τοπική μεταβλητή x δεν είναι η ίδια με την global μεταβλητή x - x = num # => 43 - print(x) # => 43 - -def set_global_x(num): - global x - print(x) # => 5 - x = num # η global μεταβλητή x τώρα είναι 6 - print(x) # => 6 - -set_x(43) -set_global_x(6) - - -# Η Python έχει πρώτης τάξης συναρτήσεις -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Αλλά έχει και anonymous συναρτήσεις. -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# Υπάρχουν ενσωματωμένες συναρτήσεις μεγαλύτερης τάξης -list(map(add_10, [1, 2, 3])) # => [11, 12, 13] -list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] - -list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] - -# Μπορούμε να χρησιμοποιήσουμε list comprehensions για ωραία maps και filters -# το List comprehension αποθηκεύει την έξοδο ως μία λίστα που μπορεί και η ίδια -# να είναι μια εμφωλευμένη λίστα -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# Μπορείς επίσης να κατασκευάσεις set και dict comprehensions. -{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} -{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -## 5. Modules -#################################################### - -# Μπορείς να κάνεις import modules -import math -print(math.sqrt(16)) # => 4.0 - -# Μπορείς να πάρεις συγκεκριμένες συναρτήσεις από ένα module -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Μπορείς να κάνεις import όλες τις συναρτήσεις από ένα module. -# Προσοχή: δεν προτείνεται -from math import * - -# Μπορείς να δημιουργείς συντομογραφίες για τα ονόματα των modules -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Τα Python modules είναι απλά αρχεία Python. Μπορείς να δημιουργήσεις τα δικά σου -# και να τα κάνεις import το όνομα του module είναι ίδιο με το όνομα του αρχείου - -# μπορείς να βρεις ποιες συναρτήσεις και γνωρίσματα ορίζονται στο module -import math -dir(math) - -# Αν έχεις ένα Python script με όνομα math.py στον ίδιο φάκελο με το τρέχον script -# το αρχείο math.py θα φορτωθεί και όχι το built-in Python module -# Αυτό συμβαίνει επειδή τα τοπικά αρχεία έχουν προτεραιότητα έναντι των built-in -# βιβλιοθηκών της Python - - -#################################################### -## 6. Κλάσεις - Classes -#################################################### - -# χρησιμοποιούμε το "class" statement για να δημιουργήσουμε μια κλάση -class Human: - - # Ένα γνώρισμα της κλάσης. Είναι κοινό για όλα τα στιγμιότυπα αυτής. - species = "H. sapiens" - - # Βασικός initializer, καλείται όταν δημιουργείται στιγμιότυπο της κλάσης. - # Σημ. οι διπλές κάτω παύλες πριν και μετά υποδηλώνουν αντικείμενα - # ή γνωρίσματα που χρησιμοποιούνται από την Python αλλά ζουν σε ελεγχόμενα από - # το χρήση namespaces. - # Μέθοδοι (ή αντικείμενα ή γνωρίσματα) σαν τα __init__, __str__, __repr__ κλπ - # είναι ειδικές μέθοδοι (λέγονται και dunder (double underscore) μέθοδοι) - # Δεν πρέπει να δηλώνεις δικές σου τέτοιες συναρτήσεις - def __init__(self, name): - # Εκχώρησε στο attribute name του object το όρισμα - self.name = name - - # Αρχικοποίησε την ιδιότητα - self._age = 0 - - # Μία μέθοδος στιγμιότυπου (instance method). Όλες οι μέθοδοι παίρνουν το - # "self" ως πρώτο όρισμα - def say(self, msg): - print("{name}: {message}".format(name=self.name, message=msg)) - - # Ακόμα μία instance method - def sing(self): - return 'yo... yo... microphone check... one two... one two...' - - # Μία μέθοδος κλάσεις είναι κοινή ανάμεσα σε όλα τα instances. - # Καλούνται με calling class ώς πρώτο όρισμα - @classmethod - def get_species(cls): - return cls.species - - # Μία στατική μέθοδος καλείται χωρίς αναφορά σε κλάση ή στιγμιότυπο - @staticmethod - def grunt(): - return "*grunt*" - - # Ένα property είναι ακριβώς σαν ένα getter. - # Μετατρέπει τη μέθοδο age σε ένα γνώρισμα (attribute) μόνο-για-ανάγνωση - # με το ίδιο όνομα. - # Δεν χρειάζεται να γράφουμε τετριμένους getters και setters στην Python όμως. - @property - def age(self): - return self._age - - # Αυτό επιτρέπει στο property να γίνει set - @age.setter - def age(self, age): - self._age = age - - # Αυτό επιτρέπει σε ένα property να διαγραφεί - @age.deleter - def age(self): - del self._age - - -# Όταν ο διερμηνέας της Python διαβάζει αρχείο πηγαίου κώδικα τον εκτελεί όλο. -# Αυτός ο έλεγχος του __name__ σιγουρεύει ότι αυτό το block κώδικα τρέχει μόνο -# αυτό το module είναι το κύριο πρόγραμμα (και όχι imported) -if __name__ == '__main__': - # Δημιουργούμε στιγμιότυπο κλάσης - i = Human(name="Ian") - i.say("hi") # "Ian: hi" - j = Human("Joel") - j.say("hello") # "Joel: hello" - # τα i και j είναι στιγμιότυπα του τύπου Human - - # Καλούμε τη μέθοδο της κλάσης - i.say(i.get_species()) # "Ian: H. sapiens" - # Αλλάζουμε το κοινό attribute των αντικειμένων της κλάσης - Human.species = "H. neanderthalensis" - i.say(i.get_species()) # => "Ian: H. neanderthalensis" - j.say(j.get_species()) # => "Joel: H. neanderthalensis" - - # Καλούμε τη static μέθοδο - print(Human.grunt()) # => "*grunt*" - - # Δεν μπορούμε να καλέσουμε τη στατική μέθοδο με ένα στιγμιότυπο - # επειδή το i.grunt() θα βάλει αυτόματα το self (δηλαδή το αντικείμενο i) ως όρισμα - print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given - - # Ενημερώνουμε το property για αυτό το στγμιότυπο - i.age = 42 - # Παίρνουμε το property - i.say(i.age) # => "Ian: 42" - j.say(j.age) # => "Joel: 0" - # Διαγράφουμε το property - del i.age - # i.age # => αυτό θα προκαλούσε AttributeError - - -#################################################### -## 6.1 Κληρονομικότητα - Inheritance -#################################################### - -# Η κληρονομικότητα επιτρέπει σε νέες κλάσεις-παιδιά να οριστούν και να υιοθετήσουν -# μεθόδους και μεταβλητές από την κλάση-γονέα. - -# Χρησιμοποιώντας την κλάση Human που ορίστηκε πριν ως τη βασική κλάση (ή κλάση-γονέα) -# μπορούμε να ορίσουμε τις κλάσεις-παιδιά Superhero, που κληρονομεί μεταβλητές όπως -# "species", "name", και "age", καθώς και μεθόδους όπως "sing" και "grunt" -# από την κλάση Human, αλλά επίσης έχει τις δικές του ξεχωριστές ιδιότητες - -# Για να εκμεταλλευτείς το modularization κατά αρχείο, μπορείς να βάλεις την παραπάνω κλάση -# σε δικό της αρχείο, ας πούμε human.py - -# Για να κάνουμε import συναρτήσεις από άλλα αρχεία χρησιμοποιούμε το παρακάτω format -# from "filename-without-extension" import "function-or-class" - -from human import Human - - -# Προσδιόρισε την/τις parent class(es) ως παραμέτρους της κλάσης που ορίζεται -class Superhero(Human): - - # Αν η κλάση-παιδί πρέπει να κληρονομήσει όλους τους οεισμούς της κλάσης-γονέα - # χωρίς καμία αλλαγή, μπορείς απλά να γράψεις pass (και τίποτα άλλο) - # αλλά σε αυτή την περίπτωση είναι σχολιασμένο για να επιτρέψει τη δημιουργία - # ξεχωριστής κλάσης-παιδιού: - # pass - - # Η κλάση παιδί μπορεί να υπερφορτώσει (override) τα attributes της κλάσης από την οποία κληρονομεί - species = 'Superhuman' - - # Τα παιδιά αυτόματα, κληρονομούν τον constructo της κλάσης-γονέα - # συμπεριλαμβανομένων των ορισμάτων, αλλά μπορείς και να ορίσεις πρόσθετα ορίσματα - # ή ορισμούς και να κάνεις override τις μεθόδους, όπως τον constructor. - # Αυτός ο constructor κληρονομεί το όρισμα "name" από την κλάση Human και - # προσθέτει τα ορίσματα "superpower" και "movie": - def __init__(self, name, movie=False, - superpowers=["super strength", "bulletproofing"]): - - # πρόσθήκη επιπλέον attributes της κλάσης: - self.fictional = True - self.movie = movie - # έχετε το νου σας τις μεταβλητές (mutable) default τιμές, καθώς είναι κοινές - self.superpowers = superpowers - - # Η συνάρτηση "super" επιτρέπει την πρόσβαση στις μεθόδους της κλάσης-γονέα - # που είναι υπερφορτωμένες από το παιδί. Σε αυτή την περίπτωση τη μέθοδο __init__ - # Το παρακάτω καλεί τον constructor της κλάσης-γονέα: - super().__init__(name) - - # υπερφόρτωση της μεθόδου sing - def sing(self): - return 'Dun, dun, DUN!' - - # προσθήκη νέας μεθόδου που εφαρμόζεται σε στιγμιότυπα - def boast(self): - for power in self.superpowers: - print("I wield the power of {pow}!".format(pow=power)) - - -if __name__ == '__main__': - sup = Superhero(name="Tick") - - # Έλεγχος για το αν το στιγμιότυπο sup ανήκει στην κλάση Human - if isinstance(sup, Human): - print('I am human') - if type(sup) is Superhero: - print('I am a superhero') -# TODO: - # Παίρνουμε το Method Resolution search Order που χρησιμοποιούν οι getattr() και super() - # Αυτό το attribute είναι δυναμικό και μπορεί να ανανεωθεί - print(Superhero.__mro__) # => (, - # => , ) - - # Καλούμε μέθοδο της κλάσης-γονέα, αλλά χρησιμοποιεί το δικό της attribute - print(sup.get_species()) # => Superhuman - - # Καλεί την υπερφορτωμένη μέθοδο - print(sup.sing()) # => Dun, dun, DUN! - - # Καλεί μέθοδο από την κλάση Human - sup.say('Spoon') # => Tick: Spoon - - # Καλεί μέθοδο που υπάρχει μόνο στην κλάση Superhero - sup.boast() # => I wield the power of super strength! - # => I wield the power of bulletproofing! - - # Κληρονομημένο class attribute - sup.age = 31 - print(sup.age) # => 31 - - # Attribute που υπάρχει μόνο στην μέσα στην κλάση Superhero - print('Am I Oscar eligible? ' + str(sup.movie)) - -#################################################### -## 6.2 Πολλαπλή Κληρονομικότητα - Multiple Inheritance -#################################################### - -# Ένας ακόμη ορισμός κλάσης -# bat.py -class Bat: - - species = 'Baty' - - def __init__(self, can_fly=True): - self.fly = can_fly - - # Αυτή η κλάση έχει επίσης μία μέθοδο say - def say(self, msg): - msg = '... ... ...' - return msg - - # Και τη δική της μέθοδο sonar - def sonar(self): - return '))) ... (((' - -if __name__ == '__main__': - b = Bat() - print(b.say('hello')) - print(b.fly) - - -# Και ορίζουμε μία ακόμα κλάση που κληρονομεί από τις κλάσεις Superhero και Bat -# superhero.py -from superhero import Superhero -from bat import Bat - -# Ας πούμε αυτή την κλάση Batman -class Batman(Superhero, Bat): - - def __init__(self, *args, **kwargs): - # Τυπικά γα να κληρονομήουμε attributes πρέπει να καλέσουμε τη super: - # super(Batman, self).__init__(*args, **kwargs) - # Ωστόσο έχουμε να κάνουμε με πολλαπλή κληρονομικότητα εδώ, και το super() - # δουλεύει μόνο με την αμέσως ανώτερη κλάση στην ιεραρχία. - # Οπότε, καλούμε ρητά την __init__ για όλους τους πρόγονους - # Η χρήση των *args και **kwargs επιτρέπει έναν καθαρό τρόπο για να περνάμε ορίσματα - # με κάθε κλάση-γονέα να "βγάζει μία φλούδα από το κρεμμύδι". - Superhero.__init__(self, 'anonymous', movie=True, - superpowers=['Wealthy'], *args, **kwargs) - Bat.__init__(self, *args, can_fly=False, **kwargs) - # υπερφορτώνουμε την τιμή του γνωρίσματος name - self.name = 'Sad Affleck' - - def sing(self): - return 'nan nan nan nan nan batman!' - - -if __name__ == '__main__': - sup = Batman() - - # - # Λάβε το Method Resolution search Order που χρησιμοποιείται από το getattr() και το super(). - # Αυτό το attribute είναι δυναμικό και μπορεί να ενημερωθεί - print(Batman.__mro__) # => (, - # => , - # => , - # => , ) - - # Καλεί την μέθοδο της κλάσης-πατέρα αλλά χρησιμοποιεί το attribute της δικής του κλάσης - print(sup.get_species()) # => Superhuman - - # Καλεί την υπερφορτωμένη μέθοδο - print(sup.sing()) # => nan nan nan nan nan batman! - - # Καλεί μέθοδο από την κλάση Human, επειδή μετράει η σειρά της κληρονομιάς - sup.say('I agree') # => Sad Affleck: I agree - - # Καλεί μέθοδο που ανήκει μόνο στον δεύτερο πρόγονο - print(sup.sonar()) # => ))) ... ((( - - # Attribute της κληρονομημένης κλάσης - sup.age = 100 - print(sup.age) # => 100 - - # Κληρονομούμενο attribute από τον δεύτερο πρόγονο του οποίου η default τιμή - # έχει υπερφορτωθεί. - print('Can I fly? ' + str(sup.fly)) # => Can I fly? False - - - -#################################################### -## 7. Προχωρημένα -#################################################### - -# Με τους Generators μπορείς να γράψεις τεμπέλικο κώδικα. -def double_numbers(iterable): - for i in iterable: - yield i + i -# Οι Generators είναι αποδοτικοί από άποψη μνήμης επειδή φορτώνουν μόνο τα δεδομένα -# που είναι αναγκαία για να επεξεργαστούμε την επόμενη τιμή του iterable. -# Αυτό μας επιτρέπει να κάνουμε πράξεις σε τιμές που υπό άλλες συνθήκες θα ήταν -# απαγορευτικά μεγάλες. -for i in double_numbers(range(1, 900000000)): # το `range` είναι ένας generator. - print(i) - if i >= 30: - break - -# Όπως μπορείς να δημιουργήσεις list comprehension, έτσι μπορείς να δημιουργήσεις και -# generator comprehensions -values = (-x for x in [1,2,3,4,5]) -for x in values: - print(x) # τυπώνει -1 -2 -3 -4 -5 στο console/terminal - -# Μπορείς επίσης να μετατρέψεις ένα generator comprehension απευθείας σε λίστα. -values = (-x for x in [1,2,3,4,5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - - -# Decorators -# σε αυτό το παράδειγμα το `beg` τυλίγει το `say`. Αν το say_please είναι True τότε -# θα αλλάξει το μήνυμα που επιστρέφεται. -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( -``` - -## Έτοιμοι για περισσότερα? - -### Δωρεάν Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) -* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) -* [Dive Into Python 3](http://www.diveintopython3.net/index.html) -* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown new file mode 100644 index 00000000..3236e73a --- /dev/null +++ b/es-es/python-es.html.markdown @@ -0,0 +1,577 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] +translators: + - ["Camilo Garrido", "http://twitter.com/hirohope"] +lang: es-es +filename: learnpython3-es.py +--- + +Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno +de los lenguajes más populares en existencia. Me enamoré de Python por su claridad sintáctica. +Es básicamente pseudocódigo ejecutable. + +¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google] + +```python + +# Comentarios de una línea comienzan con una almohadilla (o signo gato) + +""" Strings multilinea pueden escribirse + usando tres "'s, y comunmente son usados + como comentarios. +""" + +#################################################### +## 1. Tipos de datos primitivos y operadores. +#################################################### + +# Tienes números +3 #=> 3 + +# Matemática es lo que esperarías +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 + +# Excepto la división la cual por defecto retorna un número 'float' (número de coma flotante) +35 / 5 # => 7.0 +# Sin embargo también tienes disponible división entera +34 // 5 # => 6 + +# Cuando usas un float, los resultados son floats +3 * 2.0 # => 6.0 + +# Refuerza la precedencia con paréntesis +(1 + 3) * 2 # => 8 + + +# Valores 'boolean' (booleanos) son primitivos +True +False + +# Niega con 'not' +not True # => False +not False # => True + + +# Igualdad es == +1 == 1 # => True +2 == 1 # => False + +# Desigualdad es != +1 != 1 # => False +2 != 1 # => True + +# Más comparaciones +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# ¡Las comparaciones pueden ser concatenadas! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Strings se crean con " o ' +"Esto es un string." +'Esto también es un string' + +# ¡Strings también pueden ser sumados! +"Hola " + "mundo!" #=> "Hola mundo!" + +# Un string puede ser tratado como una lista de caracteres +"Esto es un string"[0] #=> 'E' + +# .format puede ser usaro para darle formato a los strings, así: +"{} pueden ser {}".format("strings", "interpolados") + +# Puedes reutilizar los argumentos de formato si estos se repiten. +"{0} sé ligero, {0} sé rápido, {0} brinca sobre la {1}".format("Jack", "vela") #=> "Jack sé ligero, Jack sé rápido, Jack brinca sobre la vela" +# Puedes usar palabras claves si no quieres contar. +"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") #=> "Bob quiere comer lasaña" +# También puedes interpolar cadenas usando variables en el contexto +nombre = 'Bob' +comida = 'Lasaña' +f'{nombre} quiere comer {comida}' #=> "Bob quiere comer lasaña" + +# None es un objeto +None # => None + +# No uses el símbolo de igualdad `==` para comparar objetos con None +# Usa `is` en su lugar +"etc" is None #=> False +None is None #=> True + +# None, 0, y strings/listas/diccionarios/conjuntos vacíos(as) todos se evalúan como False. +# Todos los otros valores son True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False +bool(set()) #=> False + + +#################################################### +## 2. Variables y Colecciones +#################################################### + +# Python tiene una función para imprimir +print("Soy Python. Encantado de conocerte") + +# No hay necesidad de declarar las variables antes de asignarlas. +una_variable = 5 # La convención es usar guiones_bajos_con_minúsculas +una_variable #=> 5 + +# Acceder a variables no asignadas previamente es una excepción. +# Ve Control de Flujo para aprender más sobre el manejo de excepciones. +otra_variable # Levanta un error de nombre + +# Listas almacena secuencias +lista = [] +# Puedes empezar con una lista prellenada +otra_lista = [4, 5, 6] + +# Añadir cosas al final de una lista con 'append' +lista.append(1) #lista ahora es [1] +lista.append(2) #lista ahora es [1, 2] +lista.append(4) #lista ahora es [1, 2, 4] +lista.append(3) #lista ahora es [1, 2, 4, 3] +# Remueve del final de la lista con 'pop' +lista.pop() #=> 3 y lista ahora es [1, 2, 4] +# Pongámoslo de vuelta +lista.append(3) # Nuevamente lista ahora es [1, 2, 4, 3]. + +# Accede a una lista como lo harías con cualquier arreglo +lista[0] #=> 1 +# Mira el último elemento +lista[-1] #=> 3 + +# Mirar fuera de los límites es un error 'IndexError' +lista[4] # Levanta la excepción IndexError + +# Puedes mirar por rango con la sintáxis de trozo. +# (Es un rango cerrado/abierto para ustedes los matemáticos.) +lista[1:3] #=> [2, 4] +# Omite el inicio +lista[2:] #=> [4, 3] +# Omite el final +lista[:3] #=> [1, 2, 4] +# Selecciona cada dos elementos +lista[::2] # =>[1, 4] +# Invierte la lista +lista[::-1] # => [3, 4, 2, 1] +# Usa cualquier combinación de estos para crear trozos avanzados +# lista[inicio:final:pasos] + +# Remueve elementos arbitrarios de una lista con 'del' +del lista[2] # lista ahora es [1, 2, 3] + +# Puedes sumar listas +lista + otra_lista #=> [1, 2, 3, 4, 5, 6] - Nota: lista y otra_lista no se tocan + +# Concatenar listas con 'extend' +lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6] + +# Verifica la existencia en una lista con 'in' +1 in lista #=> True + +# Examina el largo de una lista con 'len' +len(lista) #=> 6 + + +# Tuplas son como listas pero son inmutables. +tupla = (1, 2, 3) +tupla[0] #=> 1 +tupla[0] = 3 # Levanta un error TypeError + +# También puedes hacer todas esas cosas que haces con listas +len(tupla) #=> 3 +tupla + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tupla[:2] #=> (1, 2) +2 in tupla #=> True + +# Puedes desempacar tuplas (o listas) en variables +a, b, c = (1, 2, 3) # a ahora es 1, b ahora es 2 y c ahora es 3 +# Tuplas son creadas por defecto si omites los paréntesis +d, e, f = 4, 5, 6 +# Ahora mira que fácil es intercambiar dos valores +e, d = d, e # d ahora es 5 y e ahora es 4 + + +# Diccionarios relacionan llaves y valores +dicc_vacio = {} +# Aquí está un diccionario prellenado +dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} + +# Busca valores con [] +dicc_lleno["uno"] #=> 1 + +# Obtén todas las llaves como una lista con 'keys()'. Necesitamos envolver la llamada en 'list()' porque obtenemos un iterable. Hablaremos de eso luego. +list(dicc_lleno.keys()) #=> ["tres", "dos", "uno"] +# Nota - El orden de las llaves del diccionario no está garantizada. +# Tus resultados podrían no ser los mismos del ejemplo. + +# Obtén todos los valores como una lista. Nuevamente necesitamos envolverlas en una lista para sacarlas del iterable. +list(dicc_lleno.values()) #=> [3, 2, 1] +# Nota - Lo mismo que con las llaves, no se garantiza el orden. + +# Verifica la existencia de una llave en el diccionario con 'in' +"uno" in dicc_lleno #=> True +1 in dicc_lleno #=> False + +# Buscar una llave inexistente deriva en KeyError +dicc_lleno["cuatro"] # KeyError + +# Usa el método 'get' para evitar la excepción KeyError +dicc_lleno.get("uno") #=> 1 +dicc_lleno.get("cuatro") #=> None +# El método 'get' soporta un argumento por defecto cuando el valor no existe. +dicc_lleno.get("uno", 4) #=> 1 +dicc_lleno.get("cuatro", 4) #=> 4 + +# El método 'setdefault' inserta en un diccionario solo si la llave no está presente +dicc_lleno.setdefault("cinco", 5) #dicc_lleno["cinco"] es puesto con valor 5 +dicc_lleno.setdefault("cinco", 6) #dicc_lleno["cinco"] todavía es 5 + + +# Remueve llaves de un diccionario con 'del' +del dicc_lleno['uno'] # Remueve la llave 'uno' de dicc_lleno + +# Sets (conjuntos) almacenan ... bueno, conjuntos +conjunto_vacio = set() +# Inicializar un conjunto con montón de valores. Yeah, se ve un poco como un diccionario. Lo siento. +un_conjunto = {1,2,2,3,4} # un_conjunto ahora es {1, 2, 3, 4} + +# Añade más valores a un conjunto +conjunto_lleno.add(5) # conjunto_lleno ahora es {1, 2, 3, 4, 5} + +# Haz intersección de conjuntos con & +otro_conjunto = {3, 4, 5, 6} +conjunto_lleno & otro_conjunto #=> {3, 4, 5} + +# Haz unión de conjuntos con | +conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} + +# Haz diferencia de conjuntos con - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Verifica la existencia en un conjunto con 'in' +2 in conjunto_lleno #=> True +10 in conjunto_lleno #=> False + + +#################################################### +## 3. Control de Flujo +#################################################### + +# Creemos una variable para experimentar +some_var = 5 + +# Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python! +# imprime "una_variable es menor que 10" +if una_variable > 10: + print("una_variable es completamente mas grande que 10.") +elif una_variable < 10: # Este condición 'elif' es opcional. + print("una_variable es mas chica que 10.") +else: # Esto también es opcional. + print("una_variable es de hecho 10.") + +""" +For itera sobre iterables (listas, cadenas, diccionarios, tuplas, generadores...) +imprime: + perro es un mamifero + gato es un mamifero + raton es un mamifero +""" +for animal in ["perro", "gato", "raton"]: + print("{} es un mamifero".format(animal)) + +""" +`range(número)` retorna un generador de números +desde cero hasta el número dado +imprime: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +While itera hasta que una condición no se cumple. +imprime: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # versión corta de x = x + 1 + +# Maneja excepciones con un bloque try/except +try: + # Usa raise para levantar un error + raise IndexError("Este es un error de indice") +except IndexError as e: + pass # Pass no hace nada. Usualmente harias alguna recuperacion aqui. + +# Python oferce una abstracción fundamental llamada Iterable. +# Un iterable es un objeto que puede ser tratado como una sequencia. +# El objeto es retornado por la función 'range' es un iterable. + +dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} +nuestro_iterable = dicc_lleno.keys() +print(nuestro_iterable) #=> dict_keys(['uno', 'dos', 'tres']). Este es un objeto que implementa nuestra interfaz Iterable + +Podemos recorrerla. +for i in nuestro_iterable: + print(i) # Imprime uno, dos, tres + +# Aunque no podemos selecionar un elemento por su índice. +nuestro_iterable[1] # Genera un TypeError + +# Un iterable es un objeto que sabe como crear un iterador. +nuestro_iterator = iter(nuestro_iterable) + +# Nuestro iterador es un objeto que puede recordar el estado mientras lo recorremos. +# Obtenemos el siguiente objeto llamando la función __next__. +nuestro_iterator.__next__() #=> "uno" + +# Mantiene el estado mientras llamamos __next__. +nuestro_iterator.__next__() #=> "dos" +nuestro_iterator.__next__() #=> "tres" + +# Después que el iterador ha retornado todos sus datos, da una excepción StopIterator. +nuestro_iterator.__next__() # Genera StopIteration + +# Puedes obtener todos los elementos de un iterador llamando a list() en el. +list(dicc_lleno.keys()) #=> Retorna ["uno", "dos", "tres"] + + + +#################################################### +## 4. Funciones +#################################################### + +# Usa 'def' para crear nuevas funciones +def add(x, y): + print("x es {} y y es {}".format(x, y)) + return x + y # Retorna valores con una la declaración return + +# Llamando funciones con parámetros +add(5, 6) #=> imprime "x es 5 y y es 6" y retorna 11 + +# Otra forma de llamar funciones es con argumentos de palabras claves +add(y=6, x=5) # Argumentos de palabra clave pueden ir en cualquier orden. + + +# Puedes definir funciones que tomen un número variable de argumentos +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Puedes definir funciones que toman un número variable de argumentos +# de palabras claves +def keyword_args(**kwargs): + return kwargs + +# Llamémosla para ver que sucede +keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"} + + +# Puedes hacer ambas a la vez si quieres +def todos_los_argumentos(*args, **kwargs): + print args + print kwargs +""" +todos_los_argumentos(1, 2, a=3, b=4) imprime: + (1, 2) + {"a": 3, "b": 4} +""" + +# ¡Cuando llames funciones, puedes hacer lo opuesto a varargs/kwargs! +# Usa * para expandir tuplas y usa ** para expandir argumentos de palabras claves. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +todos_los_argumentos(*args) # es equivalente a foo(1, 2, 3, 4) +todos_los_argumentos(**kwargs) # es equivalente a foo(a=3, b=4) +todos_los_argumentos(*args, **kwargs) # es equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# Python tiene funciones de primera clase +def crear_suma(x): + def suma(y): + return x + y + return suma + +sumar_10 = crear_suma(10) +sumar_10(3) #=> 13 + +# También hay funciones anónimas +(lambda x: x > 2)(3) #=> True + +# Hay funciones integradas de orden superior +map(sumar_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Podemos usar listas por comprensión para mapeos y filtros agradables +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] +# también hay diccionarios +{k:k**2 for k in range(3)} #=> {0: 0, 1: 1, 2: 4} +# y conjuntos por comprensión +{c for c in "la cadena"} #=> {'d', 'l', 'a', 'n', ' ', 'c', 'e'} + +#################################################### +## 5. Classes +#################################################### + + +# Heredamos de object para obtener una clase. +class Humano(object): + + # Un atributo de clase es compartido por todas las instancias de esta clase + especie = "H. sapiens" + + # Constructor basico + def __init__(self, nombre): + # Asigna el argumento al atributo nombre de la instancia + self.nombre = nombre + + # Un metodo de instancia. Todos los metodos toman self como primer argumento + def decir(self, msg): + return "%s: %s" % (self.nombre, msg) + + # Un metodo de clase es compartido a través de todas las instancias + # Son llamados con la clase como primer argumento + @classmethod + def get_especie(cls): + return cls.especie + + # Un metodo estatico es llamado sin la clase o instancia como referencia + @staticmethod + def roncar(): + return "*roncar*" + + +# Instancia una clase +i = Humano(nombre="Ian") +print i.decir("hi") # imprime "Ian: hi" + +j = Humano("Joel") +print j.decir("hello") #imprime "Joel: hello" + +# Llama nuestro método de clase +i.get_especie() #=> "H. sapiens" + +# Cambia los atributos compartidos +Humano.especie = "H. neanderthalensis" +i.get_especie() #=> "H. neanderthalensis" +j.get_especie() #=> "H. neanderthalensis" + +# Llama al método estático +Humano.roncar() #=> "*roncar*" + + +#################################################### +## 6. Módulos +#################################################### + +# Puedes importar módulos +import math +print(math.sqrt(16)) #=> 4.0 + +# Puedes obtener funciones específicas desde un módulo +from math import ceil, floor +print(ceil(3.7)) #=> 4.0 +print(floor(3.7))#=> 3.0 + +# Puedes importar todas las funciones de un módulo +# Precaución: Esto no es recomendable +from math import * + +# Puedes acortar los nombres de los módulos +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Los módulos de Python son sólo archivos ordinarios de Python. +# Puedes escribir tus propios módulos e importarlos. El nombre del módulo +# es el mismo del nombre del archivo. + +# Puedes encontrar que funciones y atributos definen un módulo. +import math +dir(math) + + +#################################################### +## 7. Avanzado +#################################################### + +# Los generadores te ayudan a hacer un código perezoso (lazy) +def duplicar_numeros(iterable): + for i in iterable: + yield i + i + +# Un generador crea valores sobre la marcha. +# En vez de generar y retornar todos los valores de una vez, crea uno en cada iteración. +# Esto significa que valores más grandes que 15 no serán procesados en 'duplicar_numeros'. +# Fíjate que 'range' es un generador. Crear una lista 1-900000000 tomaría mucho tiempo en crearse. +_rango = range(1, 900000000) +# Duplicará todos los números hasta que un resultado >= se encuentre. +for i in duplicar_numeros(_rango): + print(i) + if i >= 30: + break + + +# Decoradores +# en este ejemplo 'pedir' envuelve a 'decir' +# Pedir llamará a 'decir'. Si decir_por_favor es True entonces cambiará el mensaje a retornar +from functools import wraps + + +def pedir(_decir): + @wraps(_decir) + def wrapper(*args, **kwargs): + mensaje, decir_por_favor = _decir(*args, **kwargs) + if decir_por_favor: + return "{} {}".format(mensaje, "¡Por favor! Soy pobre :(") + return mensaje + + return wrapper + + +@pedir +def say(decir_por_favor=False): + mensaje = "¿Puedes comprarme una cerveza?" + return mensaje, decir_por_favor + + +print(decir()) # ¿Puedes comprarme una cerveza? +print(decir(decir_por_favor=True)) # ¿Puedes comprarme una cerveza? ¡Por favor! Soy pobre :() +``` + +## ¿Listo para más? + +### Gratis y en línea + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/3/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### Encuadernados + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/es-es/python3-es.html.markdown b/es-es/python3-es.html.markdown deleted file mode 100644 index 3236e73a..00000000 --- a/es-es/python3-es.html.markdown +++ /dev/null @@ -1,577 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] -translators: - - ["Camilo Garrido", "http://twitter.com/hirohope"] -lang: es-es -filename: learnpython3-es.py ---- - -Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno -de los lenguajes más populares en existencia. Me enamoré de Python por su claridad sintáctica. -Es básicamente pseudocódigo ejecutable. - -¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google] - -```python - -# Comentarios de una línea comienzan con una almohadilla (o signo gato) - -""" Strings multilinea pueden escribirse - usando tres "'s, y comunmente son usados - como comentarios. -""" - -#################################################### -## 1. Tipos de datos primitivos y operadores. -#################################################### - -# Tienes números -3 #=> 3 - -# Matemática es lo que esperarías -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 - -# Excepto la división la cual por defecto retorna un número 'float' (número de coma flotante) -35 / 5 # => 7.0 -# Sin embargo también tienes disponible división entera -34 // 5 # => 6 - -# Cuando usas un float, los resultados son floats -3 * 2.0 # => 6.0 - -# Refuerza la precedencia con paréntesis -(1 + 3) * 2 # => 8 - - -# Valores 'boolean' (booleanos) son primitivos -True -False - -# Niega con 'not' -not True # => False -not False # => True - - -# Igualdad es == -1 == 1 # => True -2 == 1 # => False - -# Desigualdad es != -1 != 1 # => False -2 != 1 # => True - -# Más comparaciones -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# ¡Las comparaciones pueden ser concatenadas! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# Strings se crean con " o ' -"Esto es un string." -'Esto también es un string' - -# ¡Strings también pueden ser sumados! -"Hola " + "mundo!" #=> "Hola mundo!" - -# Un string puede ser tratado como una lista de caracteres -"Esto es un string"[0] #=> 'E' - -# .format puede ser usaro para darle formato a los strings, así: -"{} pueden ser {}".format("strings", "interpolados") - -# Puedes reutilizar los argumentos de formato si estos se repiten. -"{0} sé ligero, {0} sé rápido, {0} brinca sobre la {1}".format("Jack", "vela") #=> "Jack sé ligero, Jack sé rápido, Jack brinca sobre la vela" -# Puedes usar palabras claves si no quieres contar. -"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") #=> "Bob quiere comer lasaña" -# También puedes interpolar cadenas usando variables en el contexto -nombre = 'Bob' -comida = 'Lasaña' -f'{nombre} quiere comer {comida}' #=> "Bob quiere comer lasaña" - -# None es un objeto -None # => None - -# No uses el símbolo de igualdad `==` para comparar objetos con None -# Usa `is` en su lugar -"etc" is None #=> False -None is None #=> True - -# None, 0, y strings/listas/diccionarios/conjuntos vacíos(as) todos se evalúan como False. -# Todos los otros valores son True -bool(0) # => False -bool("") # => False -bool([]) #=> False -bool({}) #=> False -bool(set()) #=> False - - -#################################################### -## 2. Variables y Colecciones -#################################################### - -# Python tiene una función para imprimir -print("Soy Python. Encantado de conocerte") - -# No hay necesidad de declarar las variables antes de asignarlas. -una_variable = 5 # La convención es usar guiones_bajos_con_minúsculas -una_variable #=> 5 - -# Acceder a variables no asignadas previamente es una excepción. -# Ve Control de Flujo para aprender más sobre el manejo de excepciones. -otra_variable # Levanta un error de nombre - -# Listas almacena secuencias -lista = [] -# Puedes empezar con una lista prellenada -otra_lista = [4, 5, 6] - -# Añadir cosas al final de una lista con 'append' -lista.append(1) #lista ahora es [1] -lista.append(2) #lista ahora es [1, 2] -lista.append(4) #lista ahora es [1, 2, 4] -lista.append(3) #lista ahora es [1, 2, 4, 3] -# Remueve del final de la lista con 'pop' -lista.pop() #=> 3 y lista ahora es [1, 2, 4] -# Pongámoslo de vuelta -lista.append(3) # Nuevamente lista ahora es [1, 2, 4, 3]. - -# Accede a una lista como lo harías con cualquier arreglo -lista[0] #=> 1 -# Mira el último elemento -lista[-1] #=> 3 - -# Mirar fuera de los límites es un error 'IndexError' -lista[4] # Levanta la excepción IndexError - -# Puedes mirar por rango con la sintáxis de trozo. -# (Es un rango cerrado/abierto para ustedes los matemáticos.) -lista[1:3] #=> [2, 4] -# Omite el inicio -lista[2:] #=> [4, 3] -# Omite el final -lista[:3] #=> [1, 2, 4] -# Selecciona cada dos elementos -lista[::2] # =>[1, 4] -# Invierte la lista -lista[::-1] # => [3, 4, 2, 1] -# Usa cualquier combinación de estos para crear trozos avanzados -# lista[inicio:final:pasos] - -# Remueve elementos arbitrarios de una lista con 'del' -del lista[2] # lista ahora es [1, 2, 3] - -# Puedes sumar listas -lista + otra_lista #=> [1, 2, 3, 4, 5, 6] - Nota: lista y otra_lista no se tocan - -# Concatenar listas con 'extend' -lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6] - -# Verifica la existencia en una lista con 'in' -1 in lista #=> True - -# Examina el largo de una lista con 'len' -len(lista) #=> 6 - - -# Tuplas son como listas pero son inmutables. -tupla = (1, 2, 3) -tupla[0] #=> 1 -tupla[0] = 3 # Levanta un error TypeError - -# También puedes hacer todas esas cosas que haces con listas -len(tupla) #=> 3 -tupla + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tupla[:2] #=> (1, 2) -2 in tupla #=> True - -# Puedes desempacar tuplas (o listas) en variables -a, b, c = (1, 2, 3) # a ahora es 1, b ahora es 2 y c ahora es 3 -# Tuplas son creadas por defecto si omites los paréntesis -d, e, f = 4, 5, 6 -# Ahora mira que fácil es intercambiar dos valores -e, d = d, e # d ahora es 5 y e ahora es 4 - - -# Diccionarios relacionan llaves y valores -dicc_vacio = {} -# Aquí está un diccionario prellenado -dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} - -# Busca valores con [] -dicc_lleno["uno"] #=> 1 - -# Obtén todas las llaves como una lista con 'keys()'. Necesitamos envolver la llamada en 'list()' porque obtenemos un iterable. Hablaremos de eso luego. -list(dicc_lleno.keys()) #=> ["tres", "dos", "uno"] -# Nota - El orden de las llaves del diccionario no está garantizada. -# Tus resultados podrían no ser los mismos del ejemplo. - -# Obtén todos los valores como una lista. Nuevamente necesitamos envolverlas en una lista para sacarlas del iterable. -list(dicc_lleno.values()) #=> [3, 2, 1] -# Nota - Lo mismo que con las llaves, no se garantiza el orden. - -# Verifica la existencia de una llave en el diccionario con 'in' -"uno" in dicc_lleno #=> True -1 in dicc_lleno #=> False - -# Buscar una llave inexistente deriva en KeyError -dicc_lleno["cuatro"] # KeyError - -# Usa el método 'get' para evitar la excepción KeyError -dicc_lleno.get("uno") #=> 1 -dicc_lleno.get("cuatro") #=> None -# El método 'get' soporta un argumento por defecto cuando el valor no existe. -dicc_lleno.get("uno", 4) #=> 1 -dicc_lleno.get("cuatro", 4) #=> 4 - -# El método 'setdefault' inserta en un diccionario solo si la llave no está presente -dicc_lleno.setdefault("cinco", 5) #dicc_lleno["cinco"] es puesto con valor 5 -dicc_lleno.setdefault("cinco", 6) #dicc_lleno["cinco"] todavía es 5 - - -# Remueve llaves de un diccionario con 'del' -del dicc_lleno['uno'] # Remueve la llave 'uno' de dicc_lleno - -# Sets (conjuntos) almacenan ... bueno, conjuntos -conjunto_vacio = set() -# Inicializar un conjunto con montón de valores. Yeah, se ve un poco como un diccionario. Lo siento. -un_conjunto = {1,2,2,3,4} # un_conjunto ahora es {1, 2, 3, 4} - -# Añade más valores a un conjunto -conjunto_lleno.add(5) # conjunto_lleno ahora es {1, 2, 3, 4, 5} - -# Haz intersección de conjuntos con & -otro_conjunto = {3, 4, 5, 6} -conjunto_lleno & otro_conjunto #=> {3, 4, 5} - -# Haz unión de conjuntos con | -conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} - -# Haz diferencia de conjuntos con - -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# Verifica la existencia en un conjunto con 'in' -2 in conjunto_lleno #=> True -10 in conjunto_lleno #=> False - - -#################################################### -## 3. Control de Flujo -#################################################### - -# Creemos una variable para experimentar -some_var = 5 - -# Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python! -# imprime "una_variable es menor que 10" -if una_variable > 10: - print("una_variable es completamente mas grande que 10.") -elif una_variable < 10: # Este condición 'elif' es opcional. - print("una_variable es mas chica que 10.") -else: # Esto también es opcional. - print("una_variable es de hecho 10.") - -""" -For itera sobre iterables (listas, cadenas, diccionarios, tuplas, generadores...) -imprime: - perro es un mamifero - gato es un mamifero - raton es un mamifero -""" -for animal in ["perro", "gato", "raton"]: - print("{} es un mamifero".format(animal)) - -""" -`range(número)` retorna un generador de números -desde cero hasta el número dado -imprime: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -While itera hasta que una condición no se cumple. -imprime: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # versión corta de x = x + 1 - -# Maneja excepciones con un bloque try/except -try: - # Usa raise para levantar un error - raise IndexError("Este es un error de indice") -except IndexError as e: - pass # Pass no hace nada. Usualmente harias alguna recuperacion aqui. - -# Python oferce una abstracción fundamental llamada Iterable. -# Un iterable es un objeto que puede ser tratado como una sequencia. -# El objeto es retornado por la función 'range' es un iterable. - -dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} -nuestro_iterable = dicc_lleno.keys() -print(nuestro_iterable) #=> dict_keys(['uno', 'dos', 'tres']). Este es un objeto que implementa nuestra interfaz Iterable - -Podemos recorrerla. -for i in nuestro_iterable: - print(i) # Imprime uno, dos, tres - -# Aunque no podemos selecionar un elemento por su índice. -nuestro_iterable[1] # Genera un TypeError - -# Un iterable es un objeto que sabe como crear un iterador. -nuestro_iterator = iter(nuestro_iterable) - -# Nuestro iterador es un objeto que puede recordar el estado mientras lo recorremos. -# Obtenemos el siguiente objeto llamando la función __next__. -nuestro_iterator.__next__() #=> "uno" - -# Mantiene el estado mientras llamamos __next__. -nuestro_iterator.__next__() #=> "dos" -nuestro_iterator.__next__() #=> "tres" - -# Después que el iterador ha retornado todos sus datos, da una excepción StopIterator. -nuestro_iterator.__next__() # Genera StopIteration - -# Puedes obtener todos los elementos de un iterador llamando a list() en el. -list(dicc_lleno.keys()) #=> Retorna ["uno", "dos", "tres"] - - - -#################################################### -## 4. Funciones -#################################################### - -# Usa 'def' para crear nuevas funciones -def add(x, y): - print("x es {} y y es {}".format(x, y)) - return x + y # Retorna valores con una la declaración return - -# Llamando funciones con parámetros -add(5, 6) #=> imprime "x es 5 y y es 6" y retorna 11 - -# Otra forma de llamar funciones es con argumentos de palabras claves -add(y=6, x=5) # Argumentos de palabra clave pueden ir en cualquier orden. - - -# Puedes definir funciones que tomen un número variable de argumentos -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# Puedes definir funciones que toman un número variable de argumentos -# de palabras claves -def keyword_args(**kwargs): - return kwargs - -# Llamémosla para ver que sucede -keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"} - - -# Puedes hacer ambas a la vez si quieres -def todos_los_argumentos(*args, **kwargs): - print args - print kwargs -""" -todos_los_argumentos(1, 2, a=3, b=4) imprime: - (1, 2) - {"a": 3, "b": 4} -""" - -# ¡Cuando llames funciones, puedes hacer lo opuesto a varargs/kwargs! -# Usa * para expandir tuplas y usa ** para expandir argumentos de palabras claves. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -todos_los_argumentos(*args) # es equivalente a foo(1, 2, 3, 4) -todos_los_argumentos(**kwargs) # es equivalente a foo(a=3, b=4) -todos_los_argumentos(*args, **kwargs) # es equivalente a foo(1, 2, 3, 4, a=3, b=4) - -# Python tiene funciones de primera clase -def crear_suma(x): - def suma(y): - return x + y - return suma - -sumar_10 = crear_suma(10) -sumar_10(3) #=> 13 - -# También hay funciones anónimas -(lambda x: x > 2)(3) #=> True - -# Hay funciones integradas de orden superior -map(sumar_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# Podemos usar listas por comprensión para mapeos y filtros agradables -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] -# también hay diccionarios -{k:k**2 for k in range(3)} #=> {0: 0, 1: 1, 2: 4} -# y conjuntos por comprensión -{c for c in "la cadena"} #=> {'d', 'l', 'a', 'n', ' ', 'c', 'e'} - -#################################################### -## 5. Classes -#################################################### - - -# Heredamos de object para obtener una clase. -class Humano(object): - - # Un atributo de clase es compartido por todas las instancias de esta clase - especie = "H. sapiens" - - # Constructor basico - def __init__(self, nombre): - # Asigna el argumento al atributo nombre de la instancia - self.nombre = nombre - - # Un metodo de instancia. Todos los metodos toman self como primer argumento - def decir(self, msg): - return "%s: %s" % (self.nombre, msg) - - # Un metodo de clase es compartido a través de todas las instancias - # Son llamados con la clase como primer argumento - @classmethod - def get_especie(cls): - return cls.especie - - # Un metodo estatico es llamado sin la clase o instancia como referencia - @staticmethod - def roncar(): - return "*roncar*" - - -# Instancia una clase -i = Humano(nombre="Ian") -print i.decir("hi") # imprime "Ian: hi" - -j = Humano("Joel") -print j.decir("hello") #imprime "Joel: hello" - -# Llama nuestro método de clase -i.get_especie() #=> "H. sapiens" - -# Cambia los atributos compartidos -Humano.especie = "H. neanderthalensis" -i.get_especie() #=> "H. neanderthalensis" -j.get_especie() #=> "H. neanderthalensis" - -# Llama al método estático -Humano.roncar() #=> "*roncar*" - - -#################################################### -## 6. Módulos -#################################################### - -# Puedes importar módulos -import math -print(math.sqrt(16)) #=> 4.0 - -# Puedes obtener funciones específicas desde un módulo -from math import ceil, floor -print(ceil(3.7)) #=> 4.0 -print(floor(3.7))#=> 3.0 - -# Puedes importar todas las funciones de un módulo -# Precaución: Esto no es recomendable -from math import * - -# Puedes acortar los nombres de los módulos -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Los módulos de Python son sólo archivos ordinarios de Python. -# Puedes escribir tus propios módulos e importarlos. El nombre del módulo -# es el mismo del nombre del archivo. - -# Puedes encontrar que funciones y atributos definen un módulo. -import math -dir(math) - - -#################################################### -## 7. Avanzado -#################################################### - -# Los generadores te ayudan a hacer un código perezoso (lazy) -def duplicar_numeros(iterable): - for i in iterable: - yield i + i - -# Un generador crea valores sobre la marcha. -# En vez de generar y retornar todos los valores de una vez, crea uno en cada iteración. -# Esto significa que valores más grandes que 15 no serán procesados en 'duplicar_numeros'. -# Fíjate que 'range' es un generador. Crear una lista 1-900000000 tomaría mucho tiempo en crearse. -_rango = range(1, 900000000) -# Duplicará todos los números hasta que un resultado >= se encuentre. -for i in duplicar_numeros(_rango): - print(i) - if i >= 30: - break - - -# Decoradores -# en este ejemplo 'pedir' envuelve a 'decir' -# Pedir llamará a 'decir'. Si decir_por_favor es True entonces cambiará el mensaje a retornar -from functools import wraps - - -def pedir(_decir): - @wraps(_decir) - def wrapper(*args, **kwargs): - mensaje, decir_por_favor = _decir(*args, **kwargs) - if decir_por_favor: - return "{} {}".format(mensaje, "¡Por favor! Soy pobre :(") - return mensaje - - return wrapper - - -@pedir -def say(decir_por_favor=False): - mensaje = "¿Puedes comprarme una cerveza?" - return mensaje, decir_por_favor - - -print(decir()) # ¿Puedes comprarme una cerveza? -print(decir(decir_por_favor=True)) # ¿Puedes comprarme una cerveza? ¡Por favor! Soy pobre :() -``` - -## ¿Listo para más? - -### Gratis y en línea - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/3/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) - -### Encuadernados - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown new file mode 100644 index 00000000..7112cd90 --- /dev/null +++ b/fr-fr/python-fr.html.markdown @@ -0,0 +1,732 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] +translators: + - ["Gnomino", "https://github.com/Gnomino"] + - ["Julien M'Poy", "http://github.com/groovytron"] +filename: learnpython3-fr.py +lang: fr-fr +--- + +Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des +langages les plus populaires. Je suis tombé amoureux de Python pour la clarté de sa syntaxe. +C'est tout simplement du pseudo-code exécutable. + +L'auteur original apprécierait les retours (en anglais): vous pouvez le contacter sur Twitter à [@louiedinh](http://twitter.com/louiedinh) ou par mail à l'adresse louiedinh [at] [google's email service] + +Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil [ici](http://learnxinyminutes.com/docs/fr-fr/python-fr/) pour apprendre le vieux Python 2.7 + +```python + +# Un commentaire d'une ligne commence par un dièse + +""" Les chaînes de caractères peuvent être écrites + avec 3 guillemets doubles ("), et sont souvent + utilisées comme des commentaires. +""" + +#################################################### +## 1. Types de données primaires et opérateurs +#################################################### + +# On a des nombres +3 # => 3 + +# Les calculs sont ce à quoi on s'attend +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Sauf pour la division qui retourne un float (nombre à virgule flottante) +35 / 5 # => 7.0 + +# Résultats de divisions entières tronqués pour les nombres positifs et négatifs +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Quand on utilise un float, le résultat est un float +3 * 2.0 # => 6.0 + +# Modulo (reste de la division) +7 % 3 # => 1 + +# Exponentiation (x**y, x élevé à la puissance y) +2**4 # => 16 + +# Forcer la priorité de calcul avec des parenthèses +(1 + 3) * 2 # => 8 + +# Les valeurs booléennes sont primitives +True +False + +# Négation avec not +not True # => False +not False # => True + +# Opérateurs booléens +# On note que "and" et "or" sont sensibles à la casse +True and False #=> False +False or True #=> True + +# Utilisation des opérations booléennes avec des entiers : +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# On vérifie une égalité avec == +1 == 1 # => True +2 == 1 # => False + +# On vérifie une inégalité avec != +1 != 1 # => False +2 != 1 # => True + +# Autres opérateurs de comparaison +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# On peut enchaîner les comparaisons +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) is vérifie si deux variables pointent sur le même objet, mais == vérifie +# si les objets ont la même valeur. +a = [1, 2, 3, 4] # a pointe sur une nouvelle liste, [1, 2, 3, 4] +b = a # b pointe sur a +b is a # => True, a et b pointent sur le même objet +b == a # => True, les objets a et b sont égaux +b = [1, 2, 3, 4] # b pointe sur une nouvelle liste, [1, 2, 3, 4] +b is a # => False, a et b ne pointent pas sur le même objet +b == a # => True, les objets a et b ne pointent pas sur le même objet + +# Les chaînes (ou strings) sont créées avec " ou ' +"Ceci est une chaine" +'Ceci est une chaine aussi.' + +# On peut additionner des chaînes aussi ! Mais essayez d'éviter de le faire. +"Hello " + "world!" # => "Hello world!" +# On peut aussi le faire sans utiliser '+' +"Hello " "world!" # => "Hello world!" + +# On peut traîter une chaîne comme une liste de caractères +"This is a string"[0] # => 'T' + +# .format peut être utilisé pour formatter des chaînes, comme ceci: +"{} peuvent etre {}".format("Les chaînes", "interpolées") + +# On peut aussi réutiliser le même argument pour gagner du temps. +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# On peut aussi utiliser des mots clés pour éviter de devoir compter. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" + +# Il est également possible d'utiliser les f-strings depuis Python 3.6 (https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals) +name = "Fred" +f"Il a dit que son nom est {name}." #=> "Il a dit que son nom est Fred." + +# Si votre code doit aussi être compatible avec Python 2.5 et moins, +# vous pouvez encore utiliser l'ancienne syntaxe : +"Les %s peuvent être %s avec la %s méthode" % ("chaînes", "interpolées", "vieille") + + +# None est un objet +None # => None + +# N'utilisez pas "==" pour comparer des objets à None +# Utilisez plutôt "is". Cela permet de vérifier l'égalité de l'identité des objets. +"etc" is None # => False +None is None # => True + +# None, 0, and les strings/lists/dicts (chaînes/listes/dictionnaires) valent False lorsqu'ils sont convertis en booléens. +# Toutes les autres valeurs valent True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Variables et Collections +#################################################### + +# Python a une fonction print pour afficher du texte +print("I'm Python. Nice to meet you!") + +# Par défaut, la fonction print affiche aussi une nouvelle ligne à la fin. +# Utilisez l'argument optionnel end pour changer ce caractère de fin. +print("Hello, World", end="!") # => Hello, World! + +# Pas besoin de déclarer des variables avant de les définir. +# La convention est de nommer ses variables avec des minuscules_et_underscores +some_var = 5 +some_var # => 5 + +# Tenter d'accéder à une variable non définie lève une exception. +# Voir Structures de contrôle pour en apprendre plus sur le traitement des exceptions. +une_variable_inconnue # Lève une NameError + +# Les listes permettent de stocker des séquences +li = [] +# On peut initialiser une liste pré-remplie +other_li = [4, 5, 6] + +# On ajoute des objets à la fin d'une liste avec .append +li.append(1) # li vaut maintenant [1] +li.append(2) # li vaut maintenant [1, 2] +li.append(4) # li vaut maintenant [1, 2, 4] +li.append(3) # li vaut maintenant [1, 2, 4, 3] +# On enlève le dernier élément avec .pop +li.pop() # => 3 et li vaut maintenant [1, 2, 4] +# Et on le remet +li.append(3) # li vaut de nouveau [1, 2, 4, 3] + +# Accès à un élément d'une liste : +li[0] # => 1 +# Accès au dernier élément : +li[-1] # => 3 + +# Accéder à un élément en dehors des limites lève une IndexError +li[4] # Lève une IndexError + +# On peut accéder à une intervalle avec la syntaxe "slice" +# (c'est un rang du type "fermé/ouvert") +li[1:3] # => [2, 4] +# Omettre les deux premiers éléments +li[2:] # => [4, 3] +# Prendre les trois premiers +li[:3] # => [1, 2, 4] +# Sélectionner un élément sur deux +li[::2] # =>[1, 4] +# Avoir une copie de la liste à l'envers +li[::-1] # => [3, 4, 2, 1] +# Pour des "slices" plus élaborées : +# li[debut:fin:pas] + +# Faire une copie d'une profondeur de un avec les "slices" +li2 = li[:] # => li2 = [1, 2, 4, 3] mais (li2 is li) vaut False. + +# Enlever des éléments arbitrairement d'une liste +del li[2] # li is now [1, 2, 3] + +# On peut additionner des listes +# Note: les valeurs de li et other_li ne sont pas modifiées. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concaténer des listes avec "extend()" +li.extend(other_li) # Maintenant li contient [1, 2, 3, 4, 5, 6] + +# Vérifier la présence d'un objet dans une liste avec "in" +1 in li # => True + +# Examiner la longueur avec "len()" +len(li) # => 6 + + +# Les tuples sont comme des listes mais sont immuables. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Lève une TypeError + +# Note : un tuple de taille un doit avoir une virgule après le dernier élément, +# mais ce n'est pas le cas des tuples d'autres tailles, même zéro. +type((1)) # => +type((1,)) # => +type(()) # => + +# On peut utiliser la plupart des opérations des listes sur des tuples. +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Vous pouvez décomposer des tuples (ou des listes) dans des variables +a, b, c = (1, 2, 3) # a vaut 1, b vaut 2 et c vaut 3 +# Les tuples sont créés par défaut sans parenthèses +d, e, f = 4, 5, 6 +# Voyez comme il est facile d'intervertir deux valeurs : +e, d = d, e # d vaut maintenant 5 et e vaut maintenant 4 + + +# Créer un dictionnaire : +empty_dict = {} +# Un dictionnaire pré-rempli : +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Note : les clés des dictionnaires doivent être de types immuables. +# Elles doivent être convertibles en une valeur constante pour une recherche rapide. +# Les types immuables incluent les ints, floats, strings et tuples. +invalid_dict = {[1,2,3]: "123"} # => Lève une TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Par contre, les valeurs peuvent être de tout type. + +# On trouve une valeur avec [] +filled_dict["one"] # => 1 + +# On obtient toutes les clés sous forme d'un itérable avec "keys()" Il faut l'entourer +# de list() pour avoir une liste Note: l'ordre n'est pas garanti. +list(filled_dict.keys()) # => ["three", "two", "one"] + + +# On obtient toutes les valeurs sous forme d'un itérable avec "values()". +# Là aussi, il faut utiliser list() pour avoir une liste. +# Note : l'ordre n'est toujours pas garanti. +list(filled_dict.values()) # => [3, 2, 1] + + +# On vérifie la présence d'une clé dans un dictionnaire avec "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# L'accès à une clé non-existente lève une KeyError +filled_dict["four"] # KeyError + +# On utilise "get()" pour éviter la KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# La méthode get accepte une valeur de retour par défaut en cas de valeur non-existante. +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" insère une valeur dans un dictionnaire si la clé n'est pas présente. +filled_dict.setdefault("five", 5) # filled_dict["five"] devient 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] est toujours 5 + +# Ajouter à un dictionnaire +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 # une autre méthode + +# Enlever des clés d'un dictionnaire avec del +del filled_dict["one"] # Enlever la clé "one" de filled_dict. + + +# Les sets stockent des ensembles +empty_set = set() +# Initialiser un set avec des valeurs. Oui, ça ressemble aux dictionnaires, désolé. +some_set = {1, 1, 2, 2, 3, 4} # some_set est maintenant {1, 2, 3, 4} + +# Comme les clés d'un dictionnaire, les éléments d'un set doivent être immuables. +invalid_set = {[1], 1} # => Lève une TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# On peut changer un set : +filled_set = some_set + +# Ajouter un objet au set : +filled_set.add(5) # filled_set vaut maintenant {1, 2, 3, 4, 5} + +# Chercher les intersections de deux sets avec & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# On fait l'union de sets avec | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# On fait la différence de deux sets avec - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# On vérifie la présence d'un objet dans un set avec in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Structures de contrôle et Itérables +#################################################### + +# On crée juste une variable +some_var = 5 + +# Voici une condition "si". L'indentation est significative en Python! +# Affiche: "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # La clause elif ("sinon si") est optionelle + print("some_var is smaller than 10.") +else: # La clause else ("sinon") l'est aussi. + print("some_var is indeed 10.") + + +""" +Les boucles "for" itèrent sur une liste +Affiche: + chien est un mammifère + chat est un mammifère + souris est un mammifère +""" +for animal in ["chien", "chat", "souris"]: + # On peut utiliser format() pour interpoler des chaînes formattées + print("{} est un mammifère".format(animal)) + +""" +"range(nombre)" retourne un itérable de nombres +de zéro au nombre donné +Affiche: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(debut, fin)" retourne un itérable de nombre +de debut à fin. +Affiche: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(debut, fin, pas)" retourne un itérable de nombres +de début à fin en incrémentant de pas. +Si le pas n'est pas indiqué, la valeur par défaut est 1. +Affiche: + 4 + 6 + 8 +""" +for i in range(4, 8, 2): + print(i) +""" + +Les boucles "while" bouclent jusqu'à ce que la condition devienne fausse. +Affiche: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Raccourci pour x = x + 1 + +# On gère les exceptions avec un bloc try/except +try: + # On utilise "raise" pour lever une erreur + raise IndexError("Ceci est une erreur d'index") +except IndexError as e: + pass # Pass signifie simplement "ne rien faire". Généralement, on gère l'erreur ici. +except (TypeError, NameError): + pass # Si besoin, on peut aussi gérer plusieurs erreurs en même temps. +else: # Clause optionelle des blocs try/except. Doit être après tous les except. + print("Tout va bien!") # Uniquement si aucune exception n'est levée. +finally: # Éxécuté dans toutes les circonstances. + print("On nettoie les ressources ici") + +# Au lieu de try/finally pour nettoyer les ressources, on peut utiliser with +with open("myfile.txt") as f: + for line in f: + print(line) + +# Python offre une abstraction fondamentale : l'Iterable. +# Un itérable est un objet pouvant être traîté comme une séquence. +# L'objet retourné par la fonction range() est un itérable. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). C'est un objet qui implémente l'interface Iterable + +# On peut boucler dessus +for i in our_iterable: + print(i) # Affiche one, two, three + +# Cependant, on ne peut pas accéder aux éléments par leur adresse. +our_iterable[1] # Lève une TypeError + +# Un itérable est un objet qui sait créer un itérateur. +our_iterator = iter(our_iterable) + +# Notre itérateur est un objet qui se rappelle de notre position quand on le traverse. +# On passe à l'élément suivant avec "next()". +next(our_iterator) #=> "one" + +# Il garde son état quand on itère. +next(our_iterator) #=> "two" +next(our_iterator) #=> "three" + +# Après que l'itérateur a retourné toutes ses données, il lève une exception StopIterator +next(our_iterator) # Lève une StopIteration + +# On peut mettre tous les éléments d'un itérateur dans une liste avec list() +list(filled_dict.keys()) #=> Returns ["one", "two", "three"] + + +#################################################### +## 4. Fonctions +#################################################### + +# On utilise "def" pour créer des fonctions +def add(x, y): + print("x est {} et y est {}".format(x, y)) + return x + y # On retourne une valeur avec return + +# Appel d'une fonction avec des paramètres : +add(5, 6) # => affiche "x est 5 et y est 6" et retourne 11 + +# Une autre manière d'appeler une fonction : avec des arguments +add(y=6, x=5) # Les arguments peuvent être dans n'importe quel ordre. + +# Définir une fonction qui prend un nombre variable d'arguments +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# On peut aussi définir une fonction qui prend un nombre variable de paramètres. +def keyword_args(**kwargs): + return kwargs + +# Appelons la pour voir ce qu'il se passe : +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# On peut aussi faire les deux à la fois : +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) affiche: + (1, 2) + {"a": 3, "b": 4} +""" + +# En appelant des fonctions, on peut aussi faire l'inverse : +# utiliser * pour étendre un tuple de paramètres +# et ** pour étendre un dictionnaire d'arguments. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # équivalent à foo(1, 2, 3, 4) +all_the_args(**kwargs) # équivalent à foo(a=3, b=4) +all_the_args(*args, **kwargs) # équivalent à foo(1, 2, 3, 4, a=3, b=4) + +# Retourne plusieurs valeurs (avec un tuple) +def swap(x, y): + return y, x # Retourne plusieurs valeurs avec un tuple sans parenthèses. + # (Note: on peut aussi utiliser des parenthèses) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Là aussi, rien ne nous empêche d'ajouter des parenthèses + +# Portée des fonctions : +x = 5 + +def setX(num): + # La variable locale x n'est pas la même que la variable globale x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # la variable globale x est maintenant 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python a des fonctions de première classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Mais aussi des fonctions anonymes +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# TODO - Fix for iterables +# Il y a aussi des fonctions de base +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# On peut utiliser les compréhensions de listes pour de jolies maps et filtres. +# Une compréhension de liste stocke la sortie comme une liste qui peut elle même être une liste imbriquée. +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Classes +#################################################### + + +# On utilise l'opérateur "class" pour définir une classe +class Human: + + # Un attribut de la classe. Il est partagé par toutes les instances de la classe. + species = "H. sapiens" + + # L'initialiseur de base. Il est appelé quand la classe est instanciée. + # Note : les doubles underscores au début et à la fin sont utilisés pour + # les fonctions et attributs utilisés par Python mais contrôlés par l'utilisateur. + # Les méthodes (ou objets ou attributs) comme: __init__, __str__, + # __repr__ etc. sont appelés méthodes magiques. + # Vous ne devriez pas inventer de noms de ce style. + def __init__(self, name): + # Assigner l'argument à l'attribut de l'instance + self.name = name + + # Une méthode de l'instance. Toutes prennent "self" comme premier argument. + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Une méthode de classe est partagée avec entre les instances + # Ils sont appelés avec la classe comme premier argument + @classmethod + def get_species(cls): + return cls.species + + # Une méthode statique est appelée sans référence à une instance ni à une classe. + @staticmethod + def grunt(): + return "*grunt*" + + +# Instantier une classe +i = Human(name="Ian") +print(i.say("hi")) # affiche "Ian: hi" + +j = Human("Joel") +print(j.say("hello")) # affiche "Joel: hello" + +# Appeller notre méthode de classe +i.get_species() # => "H. sapiens" + +# Changer les attributs partagés +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Appeller la méthode statique +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Modules +#################################################### + +# On peut importer des modules +import math +print(math.sqrt(16)) # => 4.0 + +# On peut importer des fonctions spécifiques d'un module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# On peut importer toutes les fonctions d'un module +# Attention: ce n'est pas recommandé. +from math import * + +# On peut raccourcir un nom de module +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Les modules Python sont juste des fichiers Python. +# Vous pouvez écrire les vôtres et les importer. Le nom du module +# est le nom du fichier. + +# On peut voir quels fonctions et objets un module définit +import math +dir(math) + + +#################################################### +## 7. Avancé +#################################################### + +# Les générateurs aident à faire du code paresseux (lazy) +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Un générateur crée des valeurs à la volée. +# Au lieu de générer et retourner toutes les valeurs en une fois, il en crée une à chaque +# itération. Cela signifie que les valeurs supérieures à 30 ne seront pas traîtées par +# double_numbers. +# Note : range est un générateur aussi. +# Créer une liste 1-900000000 prendrait beaucoup de temps +# On met un underscore à la fin d'un nom de variable normalement réservé par Python. +range_ = range(1, 900000000) +# Double tous les nombres jusqu'à ce qu'un nombre >=30 soit trouvé +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Decorateurs +# Dans cet exemple, beg enveloppe say +# Beg appellera say. Si say_please vaut True le message retourné sera changé +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # affiche Can you buy me a beer? +print(say(say_please=True)) # affiche Can you buy me a beer? Please! I am poor :( +``` + +## Prêt pour encore plus ? + +### En ligne et gratuit (en anglais) + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### En ligne et gratuit (en français) + +* [Le petit guide des batteries à découvrir](https://he-arc.github.io/livre-python/) + +### Livres (en anglais) + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown deleted file mode 100644 index 7112cd90..00000000 --- a/fr-fr/python3-fr.html.markdown +++ /dev/null @@ -1,732 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] -translators: - - ["Gnomino", "https://github.com/Gnomino"] - - ["Julien M'Poy", "http://github.com/groovytron"] -filename: learnpython3-fr.py -lang: fr-fr ---- - -Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des -langages les plus populaires. Je suis tombé amoureux de Python pour la clarté de sa syntaxe. -C'est tout simplement du pseudo-code exécutable. - -L'auteur original apprécierait les retours (en anglais): vous pouvez le contacter sur Twitter à [@louiedinh](http://twitter.com/louiedinh) ou par mail à l'adresse louiedinh [at] [google's email service] - -Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil [ici](http://learnxinyminutes.com/docs/fr-fr/python-fr/) pour apprendre le vieux Python 2.7 - -```python - -# Un commentaire d'une ligne commence par un dièse - -""" Les chaînes de caractères peuvent être écrites - avec 3 guillemets doubles ("), et sont souvent - utilisées comme des commentaires. -""" - -#################################################### -## 1. Types de données primaires et opérateurs -#################################################### - -# On a des nombres -3 # => 3 - -# Les calculs sont ce à quoi on s'attend -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 - -# Sauf pour la division qui retourne un float (nombre à virgule flottante) -35 / 5 # => 7.0 - -# Résultats de divisions entières tronqués pour les nombres positifs et négatifs -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # works on floats too --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Quand on utilise un float, le résultat est un float -3 * 2.0 # => 6.0 - -# Modulo (reste de la division) -7 % 3 # => 1 - -# Exponentiation (x**y, x élevé à la puissance y) -2**4 # => 16 - -# Forcer la priorité de calcul avec des parenthèses -(1 + 3) * 2 # => 8 - -# Les valeurs booléennes sont primitives -True -False - -# Négation avec not -not True # => False -not False # => True - -# Opérateurs booléens -# On note que "and" et "or" sont sensibles à la casse -True and False #=> False -False or True #=> True - -# Utilisation des opérations booléennes avec des entiers : -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True - -# On vérifie une égalité avec == -1 == 1 # => True -2 == 1 # => False - -# On vérifie une inégalité avec != -1 != 1 # => False -2 != 1 # => True - -# Autres opérateurs de comparaison -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# On peut enchaîner les comparaisons -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# (is vs. ==) is vérifie si deux variables pointent sur le même objet, mais == vérifie -# si les objets ont la même valeur. -a = [1, 2, 3, 4] # a pointe sur une nouvelle liste, [1, 2, 3, 4] -b = a # b pointe sur a -b is a # => True, a et b pointent sur le même objet -b == a # => True, les objets a et b sont égaux -b = [1, 2, 3, 4] # b pointe sur une nouvelle liste, [1, 2, 3, 4] -b is a # => False, a et b ne pointent pas sur le même objet -b == a # => True, les objets a et b ne pointent pas sur le même objet - -# Les chaînes (ou strings) sont créées avec " ou ' -"Ceci est une chaine" -'Ceci est une chaine aussi.' - -# On peut additionner des chaînes aussi ! Mais essayez d'éviter de le faire. -"Hello " + "world!" # => "Hello world!" -# On peut aussi le faire sans utiliser '+' -"Hello " "world!" # => "Hello world!" - -# On peut traîter une chaîne comme une liste de caractères -"This is a string"[0] # => 'T' - -# .format peut être utilisé pour formatter des chaînes, comme ceci: -"{} peuvent etre {}".format("Les chaînes", "interpolées") - -# On peut aussi réutiliser le même argument pour gagner du temps. -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# On peut aussi utiliser des mots clés pour éviter de devoir compter. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" - -# Il est également possible d'utiliser les f-strings depuis Python 3.6 (https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals) -name = "Fred" -f"Il a dit que son nom est {name}." #=> "Il a dit que son nom est Fred." - -# Si votre code doit aussi être compatible avec Python 2.5 et moins, -# vous pouvez encore utiliser l'ancienne syntaxe : -"Les %s peuvent être %s avec la %s méthode" % ("chaînes", "interpolées", "vieille") - - -# None est un objet -None # => None - -# N'utilisez pas "==" pour comparer des objets à None -# Utilisez plutôt "is". Cela permet de vérifier l'égalité de l'identité des objets. -"etc" is None # => False -None is None # => True - -# None, 0, and les strings/lists/dicts (chaînes/listes/dictionnaires) valent False lorsqu'ils sont convertis en booléens. -# Toutes les autres valeurs valent True -bool(0) # => False -bool("") # => False -bool([]) #=> False -bool({}) #=> False - - -#################################################### -## 2. Variables et Collections -#################################################### - -# Python a une fonction print pour afficher du texte -print("I'm Python. Nice to meet you!") - -# Par défaut, la fonction print affiche aussi une nouvelle ligne à la fin. -# Utilisez l'argument optionnel end pour changer ce caractère de fin. -print("Hello, World", end="!") # => Hello, World! - -# Pas besoin de déclarer des variables avant de les définir. -# La convention est de nommer ses variables avec des minuscules_et_underscores -some_var = 5 -some_var # => 5 - -# Tenter d'accéder à une variable non définie lève une exception. -# Voir Structures de contrôle pour en apprendre plus sur le traitement des exceptions. -une_variable_inconnue # Lève une NameError - -# Les listes permettent de stocker des séquences -li = [] -# On peut initialiser une liste pré-remplie -other_li = [4, 5, 6] - -# On ajoute des objets à la fin d'une liste avec .append -li.append(1) # li vaut maintenant [1] -li.append(2) # li vaut maintenant [1, 2] -li.append(4) # li vaut maintenant [1, 2, 4] -li.append(3) # li vaut maintenant [1, 2, 4, 3] -# On enlève le dernier élément avec .pop -li.pop() # => 3 et li vaut maintenant [1, 2, 4] -# Et on le remet -li.append(3) # li vaut de nouveau [1, 2, 4, 3] - -# Accès à un élément d'une liste : -li[0] # => 1 -# Accès au dernier élément : -li[-1] # => 3 - -# Accéder à un élément en dehors des limites lève une IndexError -li[4] # Lève une IndexError - -# On peut accéder à une intervalle avec la syntaxe "slice" -# (c'est un rang du type "fermé/ouvert") -li[1:3] # => [2, 4] -# Omettre les deux premiers éléments -li[2:] # => [4, 3] -# Prendre les trois premiers -li[:3] # => [1, 2, 4] -# Sélectionner un élément sur deux -li[::2] # =>[1, 4] -# Avoir une copie de la liste à l'envers -li[::-1] # => [3, 4, 2, 1] -# Pour des "slices" plus élaborées : -# li[debut:fin:pas] - -# Faire une copie d'une profondeur de un avec les "slices" -li2 = li[:] # => li2 = [1, 2, 4, 3] mais (li2 is li) vaut False. - -# Enlever des éléments arbitrairement d'une liste -del li[2] # li is now [1, 2, 3] - -# On peut additionner des listes -# Note: les valeurs de li et other_li ne sont pas modifiées. -li + other_li # => [1, 2, 3, 4, 5, 6] - -# Concaténer des listes avec "extend()" -li.extend(other_li) # Maintenant li contient [1, 2, 3, 4, 5, 6] - -# Vérifier la présence d'un objet dans une liste avec "in" -1 in li # => True - -# Examiner la longueur avec "len()" -len(li) # => 6 - - -# Les tuples sont comme des listes mais sont immuables. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Lève une TypeError - -# Note : un tuple de taille un doit avoir une virgule après le dernier élément, -# mais ce n'est pas le cas des tuples d'autres tailles, même zéro. -type((1)) # => -type((1,)) # => -type(()) # => - -# On peut utiliser la plupart des opérations des listes sur des tuples. -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Vous pouvez décomposer des tuples (ou des listes) dans des variables -a, b, c = (1, 2, 3) # a vaut 1, b vaut 2 et c vaut 3 -# Les tuples sont créés par défaut sans parenthèses -d, e, f = 4, 5, 6 -# Voyez comme il est facile d'intervertir deux valeurs : -e, d = d, e # d vaut maintenant 5 et e vaut maintenant 4 - - -# Créer un dictionnaire : -empty_dict = {} -# Un dictionnaire pré-rempli : -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Note : les clés des dictionnaires doivent être de types immuables. -# Elles doivent être convertibles en une valeur constante pour une recherche rapide. -# Les types immuables incluent les ints, floats, strings et tuples. -invalid_dict = {[1,2,3]: "123"} # => Lève une TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # Par contre, les valeurs peuvent être de tout type. - -# On trouve une valeur avec [] -filled_dict["one"] # => 1 - -# On obtient toutes les clés sous forme d'un itérable avec "keys()" Il faut l'entourer -# de list() pour avoir une liste Note: l'ordre n'est pas garanti. -list(filled_dict.keys()) # => ["three", "two", "one"] - - -# On obtient toutes les valeurs sous forme d'un itérable avec "values()". -# Là aussi, il faut utiliser list() pour avoir une liste. -# Note : l'ordre n'est toujours pas garanti. -list(filled_dict.values()) # => [3, 2, 1] - - -# On vérifie la présence d'une clé dans un dictionnaire avec "in" -"one" in filled_dict # => True -1 in filled_dict # => False - -# L'accès à une clé non-existente lève une KeyError -filled_dict["four"] # KeyError - -# On utilise "get()" pour éviter la KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# La méthode get accepte une valeur de retour par défaut en cas de valeur non-existante. -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# "setdefault()" insère une valeur dans un dictionnaire si la clé n'est pas présente. -filled_dict.setdefault("five", 5) # filled_dict["five"] devient 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] est toujours 5 - -# Ajouter à un dictionnaire -filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} -#filled_dict["four"] = 4 # une autre méthode - -# Enlever des clés d'un dictionnaire avec del -del filled_dict["one"] # Enlever la clé "one" de filled_dict. - - -# Les sets stockent des ensembles -empty_set = set() -# Initialiser un set avec des valeurs. Oui, ça ressemble aux dictionnaires, désolé. -some_set = {1, 1, 2, 2, 3, 4} # some_set est maintenant {1, 2, 3, 4} - -# Comme les clés d'un dictionnaire, les éléments d'un set doivent être immuables. -invalid_set = {[1], 1} # => Lève une TypeError: unhashable type: 'list' -valid_set = {(1,), 1} - -# On peut changer un set : -filled_set = some_set - -# Ajouter un objet au set : -filled_set.add(5) # filled_set vaut maintenant {1, 2, 3, 4, 5} - -# Chercher les intersections de deux sets avec & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# On fait l'union de sets avec | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# On fait la différence de deux sets avec - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# On vérifie la présence d'un objet dans un set avec in -2 in filled_set # => True -10 in filled_set # => False - - - -#################################################### -## 3. Structures de contrôle et Itérables -#################################################### - -# On crée juste une variable -some_var = 5 - -# Voici une condition "si". L'indentation est significative en Python! -# Affiche: "some_var is smaller than 10" -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # La clause elif ("sinon si") est optionelle - print("some_var is smaller than 10.") -else: # La clause else ("sinon") l'est aussi. - print("some_var is indeed 10.") - - -""" -Les boucles "for" itèrent sur une liste -Affiche: - chien est un mammifère - chat est un mammifère - souris est un mammifère -""" -for animal in ["chien", "chat", "souris"]: - # On peut utiliser format() pour interpoler des chaînes formattées - print("{} est un mammifère".format(animal)) - -""" -"range(nombre)" retourne un itérable de nombres -de zéro au nombre donné -Affiche: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(debut, fin)" retourne un itérable de nombre -de debut à fin. -Affiche: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(debut, fin, pas)" retourne un itérable de nombres -de début à fin en incrémentant de pas. -Si le pas n'est pas indiqué, la valeur par défaut est 1. -Affiche: - 4 - 6 - 8 -""" -for i in range(4, 8, 2): - print(i) -""" - -Les boucles "while" bouclent jusqu'à ce que la condition devienne fausse. -Affiche: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Raccourci pour x = x + 1 - -# On gère les exceptions avec un bloc try/except -try: - # On utilise "raise" pour lever une erreur - raise IndexError("Ceci est une erreur d'index") -except IndexError as e: - pass # Pass signifie simplement "ne rien faire". Généralement, on gère l'erreur ici. -except (TypeError, NameError): - pass # Si besoin, on peut aussi gérer plusieurs erreurs en même temps. -else: # Clause optionelle des blocs try/except. Doit être après tous les except. - print("Tout va bien!") # Uniquement si aucune exception n'est levée. -finally: # Éxécuté dans toutes les circonstances. - print("On nettoie les ressources ici") - -# Au lieu de try/finally pour nettoyer les ressources, on peut utiliser with -with open("myfile.txt") as f: - for line in f: - print(line) - -# Python offre une abstraction fondamentale : l'Iterable. -# Un itérable est un objet pouvant être traîté comme une séquence. -# L'objet retourné par la fonction range() est un itérable. - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) #=> range(1,10). C'est un objet qui implémente l'interface Iterable - -# On peut boucler dessus -for i in our_iterable: - print(i) # Affiche one, two, three - -# Cependant, on ne peut pas accéder aux éléments par leur adresse. -our_iterable[1] # Lève une TypeError - -# Un itérable est un objet qui sait créer un itérateur. -our_iterator = iter(our_iterable) - -# Notre itérateur est un objet qui se rappelle de notre position quand on le traverse. -# On passe à l'élément suivant avec "next()". -next(our_iterator) #=> "one" - -# Il garde son état quand on itère. -next(our_iterator) #=> "two" -next(our_iterator) #=> "three" - -# Après que l'itérateur a retourné toutes ses données, il lève une exception StopIterator -next(our_iterator) # Lève une StopIteration - -# On peut mettre tous les éléments d'un itérateur dans une liste avec list() -list(filled_dict.keys()) #=> Returns ["one", "two", "three"] - - -#################################################### -## 4. Fonctions -#################################################### - -# On utilise "def" pour créer des fonctions -def add(x, y): - print("x est {} et y est {}".format(x, y)) - return x + y # On retourne une valeur avec return - -# Appel d'une fonction avec des paramètres : -add(5, 6) # => affiche "x est 5 et y est 6" et retourne 11 - -# Une autre manière d'appeler une fonction : avec des arguments -add(y=6, x=5) # Les arguments peuvent être dans n'importe quel ordre. - -# Définir une fonction qui prend un nombre variable d'arguments -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# On peut aussi définir une fonction qui prend un nombre variable de paramètres. -def keyword_args(**kwargs): - return kwargs - -# Appelons la pour voir ce qu'il se passe : -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# On peut aussi faire les deux à la fois : -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) affiche: - (1, 2) - {"a": 3, "b": 4} -""" - -# En appelant des fonctions, on peut aussi faire l'inverse : -# utiliser * pour étendre un tuple de paramètres -# et ** pour étendre un dictionnaire d'arguments. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # équivalent à foo(1, 2, 3, 4) -all_the_args(**kwargs) # équivalent à foo(a=3, b=4) -all_the_args(*args, **kwargs) # équivalent à foo(1, 2, 3, 4, a=3, b=4) - -# Retourne plusieurs valeurs (avec un tuple) -def swap(x, y): - return y, x # Retourne plusieurs valeurs avec un tuple sans parenthèses. - # (Note: on peut aussi utiliser des parenthèses) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # Là aussi, rien ne nous empêche d'ajouter des parenthèses - -# Portée des fonctions : -x = 5 - -def setX(num): - # La variable locale x n'est pas la même que la variable globale x - x = num # => 43 - print (x) # => 43 - -def setGlobalX(num): - global x - print (x) # => 5 - x = num # la variable globale x est maintenant 6 - print (x) # => 6 - -setX(43) -setGlobalX(6) - - -# Python a des fonctions de première classe -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Mais aussi des fonctions anonymes -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# TODO - Fix for iterables -# Il y a aussi des fonctions de base -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] - -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# On peut utiliser les compréhensions de listes pour de jolies maps et filtres. -# Une compréhension de liste stocke la sortie comme une liste qui peut elle même être une liste imbriquée. -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -#################################################### -## 5. Classes -#################################################### - - -# On utilise l'opérateur "class" pour définir une classe -class Human: - - # Un attribut de la classe. Il est partagé par toutes les instances de la classe. - species = "H. sapiens" - - # L'initialiseur de base. Il est appelé quand la classe est instanciée. - # Note : les doubles underscores au début et à la fin sont utilisés pour - # les fonctions et attributs utilisés par Python mais contrôlés par l'utilisateur. - # Les méthodes (ou objets ou attributs) comme: __init__, __str__, - # __repr__ etc. sont appelés méthodes magiques. - # Vous ne devriez pas inventer de noms de ce style. - def __init__(self, name): - # Assigner l'argument à l'attribut de l'instance - self.name = name - - # Une méthode de l'instance. Toutes prennent "self" comme premier argument. - def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) - - # Une méthode de classe est partagée avec entre les instances - # Ils sont appelés avec la classe comme premier argument - @classmethod - def get_species(cls): - return cls.species - - # Une méthode statique est appelée sans référence à une instance ni à une classe. - @staticmethod - def grunt(): - return "*grunt*" - - -# Instantier une classe -i = Human(name="Ian") -print(i.say("hi")) # affiche "Ian: hi" - -j = Human("Joel") -print(j.say("hello")) # affiche "Joel: hello" - -# Appeller notre méthode de classe -i.get_species() # => "H. sapiens" - -# Changer les attributs partagés -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# Appeller la méthode statique -Human.grunt() # => "*grunt*" - - -#################################################### -## 6. Modules -#################################################### - -# On peut importer des modules -import math -print(math.sqrt(16)) # => 4.0 - -# On peut importer des fonctions spécifiques d'un module -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# On peut importer toutes les fonctions d'un module -# Attention: ce n'est pas recommandé. -from math import * - -# On peut raccourcir un nom de module -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Les modules Python sont juste des fichiers Python. -# Vous pouvez écrire les vôtres et les importer. Le nom du module -# est le nom du fichier. - -# On peut voir quels fonctions et objets un module définit -import math -dir(math) - - -#################################################### -## 7. Avancé -#################################################### - -# Les générateurs aident à faire du code paresseux (lazy) -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Un générateur crée des valeurs à la volée. -# Au lieu de générer et retourner toutes les valeurs en une fois, il en crée une à chaque -# itération. Cela signifie que les valeurs supérieures à 30 ne seront pas traîtées par -# double_numbers. -# Note : range est un générateur aussi. -# Créer une liste 1-900000000 prendrait beaucoup de temps -# On met un underscore à la fin d'un nom de variable normalement réservé par Python. -range_ = range(1, 900000000) -# Double tous les nombres jusqu'à ce qu'un nombre >=30 soit trouvé -for i in double_numbers(range_): - print(i) - if i >= 30: - break - - -# Decorateurs -# Dans cet exemple, beg enveloppe say -# Beg appellera say. Si say_please vaut True le message retourné sera changé -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # affiche Can you buy me a beer? -print(say(say_please=True)) # affiche Can you buy me a beer? Please! I am poor :( -``` - -## Prêt pour encore plus ? - -### En ligne et gratuit (en anglais) - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) - -### En ligne et gratuit (en français) - -* [Le petit guide des batteries à découvrir](https://he-arc.github.io/livre-python/) - -### Livres (en anglais) - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/it-it/python-it.html.markdown b/it-it/python-it.html.markdown new file mode 100644 index 00000000..04f78cff --- /dev/null +++ b/it-it/python-it.html.markdown @@ -0,0 +1,1016 @@ +--- +language: python3 +filename: learnpython3-it.py +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] +translators: + - ["Draio", "http://github.com/Draio/"] + - ["Ale46", "http://github.com/Ale46/"] + - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] +lang: it-it +--- + +Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente pseudocodice eseguibile. + +Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service] + +Nota: Questo articolo è riferito a Python 3 in modo specifico. Se volete avete la necessità di utilizzare Python 2.7 potete consultarla [qui](https://learnxinyminutes.com/docs/it-it/python-it/) + +```python + +# I commenti su una sola linea iniziano con un cancelletto + + +""" Più stringhe possono essere scritte + usando tre ", e sono spesso usate + come documentazione +""" + +#################################################### +## 1. Tipi di dati primitivi ed Operatori +#################################################### + +# Ci sono i numeri +3 # => 3 + +# La matematica è quello che vi aspettereste +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# Risultato della divisione intera troncata sia in positivo che in negativo +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Il risultato di una divisione è sempre un numero decimale (float) +10.0 / 3 # => 3.3333333333333335 + +# Operazione Modulo +7 % 3 # => 1 + +# Elevamento a potenza (x alla y-esima potenza) +2**3 # => 8 + +# Forzare le precedenze con le parentesi +(1 + 3) * 2 # => 8 + +# I valori booleani sono primitive del linguaggio (nota la maiuscola) +True +False + +# nega con not +not True # => False +not False # => True + +# Operatori Booleani +# Nota "and" e "or" sono case-sensitive +True and False # => False +False or True # => True + +# Note sull'uso di operatori Bool con interi +# False è 0 e True è 1 +# Non confonderti tra bool(ints) e le operazioni bitwise and/or (&,|) +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True +-5 != False != True #=> True + +# Uguaglianza è == +1 == 1 # => True +2 == 1 # => False + +# Disuguaglianza è != +1 != 1 # => False +2 != 1 # => True + +# Altri confronti +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# I confronti possono essere concatenati! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# ('is' vs. '==') +# 'is' controlla se due variabili si riferiscono allo stesso oggetto +# '==' controlla se gli oggetti puntati hanno lo stesso valore. +a = [1, 2, 3, 4] # a punta ad una nuova lista [1, 2, 3, 4] +b = a # b punta a ciò a cui punta a +b is a # => True, a e b puntano allo stesso oggeto +b == a # => True, gli oggetti di a e b sono uguali +b = [1, 2, 3, 4] # b punta ad una nuova lista [1, 2, 3, 4] +b is a # => False, a e b non puntano allo stesso oggetto +b == a # => True, gli oggetti di a e b sono uguali + +# Le stringhe sono create con " o ' +"Questa è una stringa." +'Anche questa è una stringa.' + +# Anche le stringhe possono essere sommate! Ma cerca di non farlo. +"Hello " + "world!" # => "Hello world!" +# Le stringhe (ma non le variabili contenenti stringhe) possono essere +# sommate anche senza '+' +"Hello " "world!" # => "Hello world!" + +# Una stringa può essere considerata come una lista di caratteri +"Questa è una stringa"[0] # => 'Q' + +# Puoi conoscere la lunghezza di una stringa +len("Questa è una stringa") # => 20 + +# .format può essere usato per formattare le stringhe, in questo modo: +"{} possono essere {}".format("Le stringhe", "interpolate") # => "Le stringhe possono essere interpolate" + +# Puoi ripetere gli argomenti di formattazione per risparmiare un po' di codice +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# Puoi usare dei nomi se non vuoi contare gli argomenti +"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="le lasagne") # => "Bob vuole mangiare le lasagne" + +# Se il tuo codice Python 3 necessita di eseguire codice Python 2.x puoi ancora +# utilizzare il vecchio stile di formattazione: +"%s possono essere %s nel %s modo" % ("Le stringhe", "interpolate", "vecchio") # => "Le stringhe possono essere interpolate nel vecchio modo" + +# None è un oggetto +None # => None + +# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None +# Usa "is" invece +"etc" is None # => False +None is None # => True + +# None, 0, e stringhe/liste/dizionari/tuple vuoti vengono considerati +# falsi (False). Tutti gli altri valori sono considerati veri (True). +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +## 2. Variabili e Collections +#################################################### + +# Python ha una funzione per scrivere (sul tuo schermo) +print("Sono Python. Piacere di conoscerti!") # => Sono Python. Piacere di conoscerti! + +# Di default la funzione print() scrive e va a capo aggiungendo un carattere +# newline alla fine della stringa. È possibile utilizzare l'argomento opzionale +# end per cambiare quest'ultimo carattere aggiunto. +print("Hello, World", end="!") # => Hello, World! + +# Un modo semplice per ricevere dati in input dalla riga di comando +variabile_stringa_input = input("Inserisci del testo: ") # Restituisce i dati letti come stringa +# Nota: Nelle precedenti vesioni di Python, il metodo input() +# era chiamato raw_input() + +# Non c'è bisogno di dichiarare una variabile per assegnarle un valore +# Come convenzione, per i nomi delle variabili, si utilizzano i caratteri +# minuscoli separati, se necessario, da underscore +some_var = 5 +some_var # => 5 + +# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione. +# Dai un'occhiata al Control Flow per imparare di più su come gestire +# le eccezioni. +some_unknown_var # Genera un errore di nome + +# if può essere usato come un'espressione +# È l'equivalente dell'operatore ternario in C +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Le liste immagazzinano sequenze +li = [] +# Puoi partire con una lista pre-riempita +other_li = [4, 5, 6] + +# Aggiungere alla fine di una lista con append +li.append(1) # li ora è [1] +li.append(2) # li ora è [1, 2] +li.append(4) # li ora è [1, 2, 4] +li.append(3) # li ora è [1, 2, 4, 3] +# Rimuovi dalla fine della lista con pop +li.pop() # => 3 e li ora è [1, 2, 4] +# Rimettiamolo a posto +li.append(3) # li ora è [1, 2, 4, 3] di nuovo. + +# Accedi ad una lista come faresti con un array +li[0] # => 1 +# Guarda l'ultimo elemento +li[-1] # => 3 + +# Guardare al di fuori dei limiti genera un IndexError +li[4] # Genera IndexError + +# Puoi guardare gli intervalli con la sintassi slice (a fetta). +# (E' un intervallo chiuso/aperto per voi tipi matematici.) +li[1:3] # => [2, 4] +# Ometti l'inizio +li[2:] # => [4, 3] +# Ometti la fine +li[:3] # => [1, 2, 4] +# Seleziona ogni seconda voce +li[::2] # =>[1, 4] +# Copia al contrario della lista +li[::-1] # => [3, 4, 2, 1] +# Usa combinazioni per fare slices avanzate +# li[inizio:fine:passo] + +# Crea una copia (one layer deep copy) usando la sintassi slices +li2 = li[:] # => li2 = [1, 2, 4, 3] ma (li2 is li) risulterà falso. + +# Rimuovi arbitrariamente elementi da una lista con "del" +del li[2] # li è ora [1, 2, 3] + +# Rimuove la prima occorrenza di un elemento +li.remove(2) # Ora li è [1, 3, 4, 5, 6] +li.remove(2) # Emette un ValueError, poichè 2 non è contenuto nella lista + +# Inserisce un elemento all'indice specificato +li.insert(1, 2) # li è di nuovo [1, 2, 3, 4, 5, 6] + + Ritorna l'indice della prima occorrenza dell'elemento fornito +li.index(2) # => 1 +li.index(7) # Emette un ValueError, poichè 7 non è contenuto nella lista + +# Puoi sommare le liste +# Nota: i valori per li e per other_li non vengono modificati. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concatena le liste con "extend()" +li.extend(other_li) # Adesso li è [1, 2, 3, 4, 5, 6] + +# Controlla l'esistenza di un valore in una lista con "in" +1 in li # => True + +# Esamina la lunghezza con "len()" +len(li) # => 6 + + +# Le tuple sono come le liste ma immutabili. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Genera un TypeError + +# Note that a tuple of length one has to have a comma after the last element but +# tuples of other lengths, even zero, do not. +type((1)) # => +type((1,)) # => +type(()) # => + +# Puoi fare tutte queste cose da lista anche sulle tuple +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Puoi scompattare le tuple (o liste) in variabili +a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 e c è ora 3 +d, e, f = 4, 5, 6 # puoi anche omettere le parentesi +# Le tuple sono create di default se non usi le parentesi +g = 4, 5, 6 # => (4, 5, 6) +# Guarda come è facile scambiare due valori +e, d = d, e # d è ora 5 ed e è ora 4 + +# I dizionari memorizzano insiemi di dati indicizzati da nomi arbitrari (chiavi) +empty_dict= {} +# Questo è un dizionario pre-caricato +filled_dict = {"uno": 1, "due": 2, "tre": 3} + +# Nota: le chiavi dei dizionari devono essere di tipo immutabile. Questo per +# assicurare che le chiavi possano essere convertite in calori hash costanti +# per un risposta più veloce. +invalid_dict = {[1,2,3]: "123"} # => Emette un TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # I valori, invece, possono essere di qualunque tipo + +# Accedi ai valori indicando la chiave tra [] +filled_dict["uno"] # => 1 + +# Puoi ottenere tutte le chiavi di un dizionario con "keys()" +# (come oggetto iterabile). Per averle in formato lista è necessario +# utilizzare list(). +# Nota - Nei dizionari l'ordine delle chiavi non è garantito. +# Il tuo risultato potrebbe non essere uguale a questo. +list(filled_dict.keys()) # => ["tre", "due", "uno"] + + +# Puoi ottenere tutti i valori di un dizionario con "values()" +# (come oggetto iterabile). +# Anche in questo caso, er averle in formato lista, è necessario utilizzare list() +# Anche in questo caso, come per le chiavi, l'ordine non è garantito +list(filled_dict.values()) # => [3, 2, 1] + +# Controlla l'esistenza delle chiavi in un dizionario con "in" +"uno" in filled_dict # => True +1 in filled_dict # => False + +# Cercando una chiave non esistente genera un KeyError +filled_dict["quattro"] # KeyError + +# Usa il metodo "get()" per evitare KeyError +filled_dict.get("uno") # => 1 +filled_dict.get("quattro") # => None +# Il metodo get supporta un argomento di default quando il valore è mancante +filled_dict.get("uno", 4) # => 1 +filled_dict.get("quattro", 4) # => 4 + + +# "setdefault()" inserisce un valore per una chiave in un dizionario +# solo se la chiave data non è già presente +filled_dict.setdefault("cinque", 5) # filled_dict["cinque"] viene impostato a 5 +filled_dict.setdefault("cinque", 6) # filled_dict["cinque"] rimane 5 + +# Aggiungere una coppia chiave->valore a un dizionario +filled_dict.update({"quattro":4}) # => {"uno": 1, "due": 2, "tre": 3, "quattro": 4} +filled_dict["quattro"] = 4 # un altro modo pe aggiungere a un dizionario + +# Rimuovi una chiave da un dizionario con del +del filled_dict["uno"] # Rimuove la chiave "uno" dal dizionario + +# Da Python 3.5 puoi anche usare ulteriori opzioni di spacchettamento +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + +# I set sono come le liste ma non possono contenere doppioni +empty_set = set() +# Inizializza un "set()" con un dei valori. Sì, sembra un dizionario. +some_set = {1, 1, 2, 2, 3, 4} # set_nuovo è {1, 2, 3, 4} + +# Come le chiavi di un dizionario, gli elementi di un set devono essere +# di tipo immutabile +invalid_set = {[1], 1} # => Genera un "TypeError: unhashable type: 'list'"" +valid_set = {(1,), 1} + +# Aggiungere uno o più elementi ad un set +some_set.add(5) # some_set ora è {1, 2, 3, 4, 5} + +# Fai intersezioni su un set con & +other_set = {3, 4, 5, 6} +some_set & other_set # => {3, 4, 5} + +# Fai unioni su set con | +some_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Fai differenze su set con - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Effettua la differenza simmetrica con ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Controlla se il set a sinistra contiene quello a destra +{1, 2} >= {1, 2, 3} # => False + +# Controlla se il set a sinistra è un sottoinsieme di quello a destra +{1, 2} <= {1, 2, 3} # => True + +# Controlla l'esistenza in un set con in +2 in some_set # => True +10 in some_set # => False + + + +#################################################### +## 3. Control Flow e oggetti Iterabili +#################################################### + +# Dichiariamo una variabile +some_var = 5 + +# Questo è un controllo if. L'indentazione è molto importante in python! +# Come convenzione si utilizzano quattro spazi, non la tabulazione. +# Il seguente codice stampa "some_var è minore di 10" +if some_var > 10: + print("some_var è maggiore di 10") +elif some_var < 10: # La clausolo elif è opzionale + print("some_var è minore di 10") +else: # Anche else è opzionale + print("some_var è 10.") + +""" +I cicli for iterano sulle liste, cioè ripetono un codice per ogni elemento +di una lista. +Il seguente codice scriverà: + cane è un mammifero + gatto è un mammifero + topo è un mammifero +""" +for animale in ["cane", "gatto", "topo"]: + # Puoi usare format() per interpolare le stringhe formattate. + print("{} è un mammifero".format(animale)) + +""" +"range(numero)" restituisce una lista di numeri da zero al numero dato +Il seguente codice scriverà: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(lower, upper)" restituisce una lista di numeri dal più piccolo (lower) +al più grande (upper). +Il seguente codice scriverà: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(lower, upper, step)" rrestituisce una lista di numeri dal più piccolo +(lower) al più grande (upper), incrementando del valore step. +Se step non è indicato, avrà come valore di default 1. +Il seguente codice scriverà: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +I cicli while vengono eseguiti finchè una condizione viene a mancare +Il seguente codice scriverà: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Forma compatta per x = x + 1 + +# Gestione delle eccezioni con un blocco try/except +try: + # Usa "raise" per generare un errore + raise IndexError("Questo è un IndexError") +except IndexError as e: + pass # Pass è solo una non-operazione. Solitamente vorrai rimediare all'errore. +except (TypeError, NameError): + pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario. +else: # Clausola opzionale al blocco try/except. Deve essere dopo tutti i blocchi except + print("Tutto ok!") # Viene eseguita solo se il codice dentro try non genera eccezioni +finally: # Eseguito sempre + print("Possiamo liberare risorse qui") + +# Se ti serve solo un try/finally, per liberare risorse, puoi usare il metodo with +with open("myfile.txt") as f: + for line in f: + print(line) + +# In Python qualunque oggetto in grado di essere trattato come una +# sequenza è definito un oggetto Iterable (itarabile). +# L'oggetto restituito da una funzione range è un iterabile. + +filled_dict = {"uno": 1, "due": 2, "tre": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['uno', 'due', 'tre']). +# Questo è un oggetto che implementa la nostra interfaccia Iterable. + +# È possibile utilizzarlo con i loop: +for i in our_iterable: + print(i) # Scrive uno, due, tre + +# Tuttavia non possiamo recuperarne i valori tramite indice. +our_iterable[1] # Genera un TypeError + +# Un oggetto iterabile è in grado di generare un iteratore +our_iterator = iter(our_iterable) + +# L'iteratore è un oggetto che ricorda il suo stato mentro lo si "attraversa" +# Possiamo accedere al successivo elemento con "next()". +next(our_iterator) # => "uno" + +# Mantiene il suo stato mentro eseguiamo l'iterazione +next(our_iterator) # => "due" +next(our_iterator) # => "tre" + +# Dopo che un iteratore ha restituito tutti i suoi dati, genera +# un'eccezione StopIteration +next(our_iterator) # Raises StopIteration + +# Puoi prendere tutti gli elementi di un iteratore utilizzando list(). +list(filled_dict.keys()) # => Returns ["one", "two", "three"] + + + +#################################################### +## 4. Funzioni +#################################################### + +# Usa "def" per creare nuove funzioni +def aggiungi(x, y): + print("x è {} e y è {}".format(x, y)) // Scrive i valori formattati in una stringa + return x + y # Restituisce la somma dei valori con il metodo return + +# Chiamare funzioni con parametri +aggiungi(5, 6) # => scrive "x è 5 e y è 6" e restituisce 11 + +# Un altro modo per chiamare funzioni è con parole chiave come argomenti +aggiungi(y=6, x=5) # In questo modo non è necessario rispettare l'ordine degli argomenti + +# Puoi definire funzioni che accettano un numero non definito di argomenti +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Puoi definire funzioni che accettano un numero variabile di parole chiave +# come argomento, che saranno interpretati come un dizionario usando ** +def keyword_args(**kwargs): + return kwargs + +# Chiamiamola per vedere cosa succede +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# Puoi farle entrambi in una volta, se ti va +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) stampa: + (1, 2) + {"a": 3, "b": 4} +""" + +# Quando chiami funzioni, puoi fare l'opposto di args/kwargs! +# Usa * per sviluppare gli argomenti posizionale ed usa ** per +# espandere gli argomenti parola chiave +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalente a foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalente a foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) + + +# Restituire valori multipli (with tuple assignments) +def swap(x, y): + return y, x # Restituisce valori multipli come tupla senza parentesi + # (Nota: le parentesi sono state escluse ma possono essere messe) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Le parentesi sono state escluse ma possono essere incluse. + +# Funzioni - Visibilità delle variabili (variable scope) +x = 5 + +def set_x(num): + # La variabile locale x non è la variabile globale x + x = num # => 43 + print(x) # => 43 + +def set_global_x(num): + global x + print(x) # => 5 + x = num # la variabile globable x è ora 6 + print(x) # => 6 + +set_x(43) +set_global_x(6) + + +# Python ha "first class functions" +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Ci sono anche funzioni anonime +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# È possibile creare "mappe" e "filtri" +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# Possiamo usare le "list comprehensions" per mappe e filtri +# Le "list comprehensions" memorizzano l'output come una lista che può essere +# di per sé una lista annidata +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# Puoi fare anche la comprensione di set e dizionari +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Modules +#################################################### + +# Puoi importare moduli +import math +print(math.sqrt(16)) # => 4.0 + +# Puoi ottenere specifiche funzione da un modulo +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Puoi importare tutte le funzioni da un modulo +# Attenzione: questo non è raccomandato +from math import * + +# Puoi abbreviare i nomi dei moduli +import math as m +math.sqrt(16) == m.sqrt(16) # => True + + +# I moduli di Python sono normali file python. Ne puoi +# scrivere di tuoi ed importarli. Il nome del modulo +# è lo stesso del nome del file. + +# Potete scoprire quali funzioni e attributi +# sono definiti in un modulo +import math +dir(math) + +# Se nella cartella corrente hai uno script chiamato math.py, +# Python caricherà quello invece del modulo math. +# Questo succede perchè la cartella corrente ha priorità +# sulle librerie standard di Python + +# Se hai uno script Python chiamato math.py nella stessa +# cartella del tua script, Python caricherà quello al posto del +# comune modulo math. +# Questo accade perché la cartella locale ha la priorità +# sulle librerie built-in di Python. + + +#################################################### +## 6. Classes +#################################################### + +# Usiamo l'istruzione "class" per creare una classe +class Human: + + # Un attributo della classe. E' condiviso tra tutte le istanze delle classe + species = "H. sapiens" + + # Si noti che i doppi underscore iniziali e finali denotano gli oggetti o + # attributi utilizzati da Python ma che vivono nel namespace controllato + # dall'utente + # Metodi, oggetti o attributi come: __init__, __str__, __repr__, etc. sono + # chiamati metodi speciali (o talvolta chiamati "dunder methods"). + # Non dovresti inventare tali nomi da solo. + + def __init__(self, name): + # Assegna l'argomento all'attributo name dell'istanza + self.name = name + + # Inizializza una proprietà + self._age = 0 + + # Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento + def say(self, msg): + print("{name}: {message}".format(name=self.name, message=msg)) + + # Un altro metodo dell'istanza + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # Un metodo della classe è condiviso fra tutte le istanze + # Sono chiamati con la classe chiamante come primo argomento + @classmethod + def get_species(cls): + return cls.species + + # Un metodo statico è chiamato senza classe o istanza di riferimento + @staticmethod + def grunt(): + return "*grunt*" + + # Una property è come un metodo getter. + # Trasforma il metodo age() in un attributo in sola lettura, che ha + # lo stesso nome + # In Python non c'è bisogno di scrivere futili getter e setter. + @property + def age(self): + return self._age + + # Questo metodo permette di modificare una property + @age.setter + def age(self, age): + self._age = age + + # Questo metodo permette di cancellare una property + @age.deleter + def age(self): + del self._age + +# Quando l'interprete Python legge un sorgente esegue tutto il suo codice. +# Questo controllo su __name__ assicura che questo blocco di codice venga +# eseguito solo quando questo modulo è il programma principale. + +if __name__ == '__main__': + # Crea un'istanza della classe + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i e j sono istanze del tipo Human, o in altre parole sono oggetti Human + + # Chiama un metodo della classe + i.say(i.get_species()) # "Ian: H. sapiens" + # Cambia l'attributo condiviso + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Chiama un metodo statico + print(Human.grunt()) # => "*grunt*" + + # Non è possibile chiamare il metodo statico con l'istanza dell'oggetto + # poiché i.grunt() metterà automaticamente "self" (l'oggetto i) + # come argomento + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # Aggiorna la property (age) di questa istanza + i.age = 42 + # Leggi la property + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # Cancella la property + del i.age + i.age # => questo genererà un AttributeError + + +#################################################### +## 6.1 Ereditarietà (Inheritance) +#################################################### + +# L'ereditarietà consente di definire nuove classi figlio che ereditano metodi e +# variabili dalla loro classe genitore. + +# Usando la classe Human definita sopra come classe base o genitore, possiamo +# definire una classe figlia, Superhero, che erediterà le variabili di classe +# come "species", "name" e "age", così come i metodi, come "sing" e "grunt", +# dalla classe Human, ma potrà anche avere le sue proprietà uniche. + +# Per importare le funzioni da altri file usa il seguente formato +# from "nomefile-senza-estensione" import "funzione-o-classe" + +from human import Human + +# Specificare le classi genitore come parametri della definizione della classe +class Superhero(Human): + + # Se la classe figlio deve ereditare tutte le definizioni del genitore + # senza alcuna modifica, puoi semplicemente usare la parola chiave "pass" + # (e nient'altro) + + #Le classi figlio possono sovrascrivere gli attributi dei loro genitori + species = 'Superhuman' + + # Le classi figlie ereditano automaticamente il costruttore della classe + # genitore, inclusi i suoi argomenti, ma possono anche definire ulteriori + # argomenti o definizioni e sovrascrivere i suoi metodi (compreso il + # costruttore della classe). + # Questo costruttore eredita l'argomento "nome" dalla classe "Human" e + # aggiunge gli argomenti "superpowers" e "movie": + + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # aggiungi ulteriori attributi della classe + self.fictional = True + self.movie = movie + self.superpowers = superpowers + + # La funzione "super" ti consente di accedere ai metodi della classe + # genitore che sono stati sovrascritti dalla classe figlia, + # in questo caso il metodo __init__. + # Il seguente codice esegue il costruttore della classe genitore: + super().__init__(name) + + # Sovrascrivere il metodo "sing" + def sing(self): + return 'Dun, dun, DUN!' + + # Aggiungi un ulteriore metodo dell'istanza + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # Controllo del tipo di istanza + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') + + # Ottieni il "Method Resolution search Order" usato sia da getattr () + # che da super (). Questo attributo è dinamico e può essere aggiornato + print(Superhero.__mro__) # => (, + # => , ) + + # Esegui il metodo principale ma utilizza il proprio attributo di classe + print(sup.get_species()) # => Superhuman + + # Esegui un metodo che è stato sovrascritto + print(sup.sing()) # => Dun, dun, DUN! + + # Esegui un metodo di Human + sup.say('Spoon') # => Tick: Spoon + + # Esegui un metodo che esiste solo in Superhero + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # Attributo di classe ereditato + sup.age = 31 + print(sup.age) # => 31 + + # Attributo che esiste solo in Superhero + print('Am I Oscar eligible? ' + str(sup.movie)) + +#################################################### +## 6.2 Ereditarietà multipla +#################################################### + +# Un'altra definizione di classe +# bat.py +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # Questa classe ha anche un metodo "say" + def say(self, msg): + msg = '... ... ...' + return msg + + # E anche un suo metodo personale + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + +# Definizione di classe che eredita da Superhero e Bat +# superhero.py +from superhero import Superhero +from bat import Bat + +# Definisci Batman come classe figlia che eredita sia da Superhero che da Bat +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # In genere per ereditare gli attributi devi chiamare super: + # super(Batman, self).__init__(*args, **kwargs) + # Ma qui abbiamo a che fare con l'ereditarietà multipla, e super() + # funziona solo con la successiva classe nell'elenco MRO. + # Quindi, invece, chiamiamo esplicitamente __init__ per tutti gli + # antenati. L'uso di *args e **kwargs consente di passare in modo + # pulito gli argomenti, con ciascun genitore che "sbuccia un + # livello della cipolla". + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # sovrascrivere il valore per l'attributo name + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # Ottieni il "Method Resolution search Order" utilizzato da getattr() e super(). + # Questo attributo è dinamico e può essere aggiornato + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + # Esegui il metodo del genitore ma utilizza il proprio attributo di classe + print(sup.get_species()) # => Superhuman + + # Esegui un metodo che è stato sovrascritto + print(sup.sing()) # => nan nan nan nan nan batman! + + # Esegui un metodo da Human, perché l'ordine di ereditarietà è importante + sup.say('I agree') # => Sad Affleck: I agree + + # Esegui un metodo che esiste solo nel 2o antenato + print(sup.sonar()) # => ))) ... ((( + + # Attributo di classe ereditato + sup.age = 100 + print(sup.age) # => 100 + + # Attributo ereditato dal secondo antenato il cui valore predefinito + # è stato ignorato. + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False + + + +#################################################### +## 7. Advanced +#################################################### + +# I generatori ti aiutano a creare codice pigro (lazy code). +# Codice che darà un risultato solo quando sarà "valutato" +def double_numbers(iterable): + for i in iterable: + yield i + i + +# I generatori sono efficienti in termini di memoria perché caricano +# solo i dati necessari per elaborare il valore successivo nell'iterabile. +# Ciò consente loro di eseguire operazioni su intervalli di valori +# altrimenti proibitivi. +# NOTA: `range` sostituisce` xrange` in Python 3. +for i in double_numbers(range(1, 900000000)): # `range` is a generator. + print(i) + if i >= 30: + break + +# Proprio come è possibile creare una "list comprehension", è possibile +# creare anche delle "generator comprehensions". +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# Puoi anche trasmettere una "generator comprehensions" direttamente +# ad un elenco. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# Decoratori +# In questo esempio "beg" avvolge/wrappa "say". +# Se say_please è True, cambierà il messaggio restituito. +from functools import wraps + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Per favore! Sono povero :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Puoi comprarmi una birra?" + return msg, say_please + + +print(say()) # Puoi comprarmi una birra? +print(say(say_please=True)) # Puoi comprarmi una birra? Per favore! Sono povero :( +``` + +## Pronto per qualcosa di più? + +### Gratis Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/it-it/python3-it.html.markdown b/it-it/python3-it.html.markdown deleted file mode 100644 index 04f78cff..00000000 --- a/it-it/python3-it.html.markdown +++ /dev/null @@ -1,1016 +0,0 @@ ---- -language: python3 -filename: learnpython3-it.py -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["evuez", "http://github.com/evuez"] - - ["Rommel Martinez", "https://ebzzry.io"] -translators: - - ["Draio", "http://github.com/Draio/"] - - ["Ale46", "http://github.com/Ale46/"] - - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] -lang: it-it ---- - -Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente pseudocodice eseguibile. - -Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service] - -Nota: Questo articolo è riferito a Python 3 in modo specifico. Se volete avete la necessità di utilizzare Python 2.7 potete consultarla [qui](https://learnxinyminutes.com/docs/it-it/python-it/) - -```python - -# I commenti su una sola linea iniziano con un cancelletto - - -""" Più stringhe possono essere scritte - usando tre ", e sono spesso usate - come documentazione -""" - -#################################################### -## 1. Tipi di dati primitivi ed Operatori -#################################################### - -# Ci sono i numeri -3 # => 3 - -# La matematica è quello che vi aspettereste -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 - -# Risultato della divisione intera troncata sia in positivo che in negativo -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # works on floats too --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Il risultato di una divisione è sempre un numero decimale (float) -10.0 / 3 # => 3.3333333333333335 - -# Operazione Modulo -7 % 3 # => 1 - -# Elevamento a potenza (x alla y-esima potenza) -2**3 # => 8 - -# Forzare le precedenze con le parentesi -(1 + 3) * 2 # => 8 - -# I valori booleani sono primitive del linguaggio (nota la maiuscola) -True -False - -# nega con not -not True # => False -not False # => True - -# Operatori Booleani -# Nota "and" e "or" sono case-sensitive -True and False # => False -False or True # => True - -# Note sull'uso di operatori Bool con interi -# False è 0 e True è 1 -# Non confonderti tra bool(ints) e le operazioni bitwise and/or (&,|) -0 and 2 # => 0 --5 or 0 # => -5 -0 == False # => True -2 == True # => False -1 == True # => True --5 != False != True #=> True - -# Uguaglianza è == -1 == 1 # => True -2 == 1 # => False - -# Disuguaglianza è != -1 != 1 # => False -2 != 1 # => True - -# Altri confronti -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# I confronti possono essere concatenati! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# ('is' vs. '==') -# 'is' controlla se due variabili si riferiscono allo stesso oggetto -# '==' controlla se gli oggetti puntati hanno lo stesso valore. -a = [1, 2, 3, 4] # a punta ad una nuova lista [1, 2, 3, 4] -b = a # b punta a ciò a cui punta a -b is a # => True, a e b puntano allo stesso oggeto -b == a # => True, gli oggetti di a e b sono uguali -b = [1, 2, 3, 4] # b punta ad una nuova lista [1, 2, 3, 4] -b is a # => False, a e b non puntano allo stesso oggetto -b == a # => True, gli oggetti di a e b sono uguali - -# Le stringhe sono create con " o ' -"Questa è una stringa." -'Anche questa è una stringa.' - -# Anche le stringhe possono essere sommate! Ma cerca di non farlo. -"Hello " + "world!" # => "Hello world!" -# Le stringhe (ma non le variabili contenenti stringhe) possono essere -# sommate anche senza '+' -"Hello " "world!" # => "Hello world!" - -# Una stringa può essere considerata come una lista di caratteri -"Questa è una stringa"[0] # => 'Q' - -# Puoi conoscere la lunghezza di una stringa -len("Questa è una stringa") # => 20 - -# .format può essere usato per formattare le stringhe, in questo modo: -"{} possono essere {}".format("Le stringhe", "interpolate") # => "Le stringhe possono essere interpolate" - -# Puoi ripetere gli argomenti di formattazione per risparmiare un po' di codice -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# Puoi usare dei nomi se non vuoi contare gli argomenti -"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="le lasagne") # => "Bob vuole mangiare le lasagne" - -# Se il tuo codice Python 3 necessita di eseguire codice Python 2.x puoi ancora -# utilizzare il vecchio stile di formattazione: -"%s possono essere %s nel %s modo" % ("Le stringhe", "interpolate", "vecchio") # => "Le stringhe possono essere interpolate nel vecchio modo" - -# None è un oggetto -None # => None - -# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None -# Usa "is" invece -"etc" is None # => False -None is None # => True - -# None, 0, e stringhe/liste/dizionari/tuple vuoti vengono considerati -# falsi (False). Tutti gli altri valori sono considerati veri (True). -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False - -#################################################### -## 2. Variabili e Collections -#################################################### - -# Python ha una funzione per scrivere (sul tuo schermo) -print("Sono Python. Piacere di conoscerti!") # => Sono Python. Piacere di conoscerti! - -# Di default la funzione print() scrive e va a capo aggiungendo un carattere -# newline alla fine della stringa. È possibile utilizzare l'argomento opzionale -# end per cambiare quest'ultimo carattere aggiunto. -print("Hello, World", end="!") # => Hello, World! - -# Un modo semplice per ricevere dati in input dalla riga di comando -variabile_stringa_input = input("Inserisci del testo: ") # Restituisce i dati letti come stringa -# Nota: Nelle precedenti vesioni di Python, il metodo input() -# era chiamato raw_input() - -# Non c'è bisogno di dichiarare una variabile per assegnarle un valore -# Come convenzione, per i nomi delle variabili, si utilizzano i caratteri -# minuscoli separati, se necessario, da underscore -some_var = 5 -some_var # => 5 - -# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione. -# Dai un'occhiata al Control Flow per imparare di più su come gestire -# le eccezioni. -some_unknown_var # Genera un errore di nome - -# if può essere usato come un'espressione -# È l'equivalente dell'operatore ternario in C -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# Le liste immagazzinano sequenze -li = [] -# Puoi partire con una lista pre-riempita -other_li = [4, 5, 6] - -# Aggiungere alla fine di una lista con append -li.append(1) # li ora è [1] -li.append(2) # li ora è [1, 2] -li.append(4) # li ora è [1, 2, 4] -li.append(3) # li ora è [1, 2, 4, 3] -# Rimuovi dalla fine della lista con pop -li.pop() # => 3 e li ora è [1, 2, 4] -# Rimettiamolo a posto -li.append(3) # li ora è [1, 2, 4, 3] di nuovo. - -# Accedi ad una lista come faresti con un array -li[0] # => 1 -# Guarda l'ultimo elemento -li[-1] # => 3 - -# Guardare al di fuori dei limiti genera un IndexError -li[4] # Genera IndexError - -# Puoi guardare gli intervalli con la sintassi slice (a fetta). -# (E' un intervallo chiuso/aperto per voi tipi matematici.) -li[1:3] # => [2, 4] -# Ometti l'inizio -li[2:] # => [4, 3] -# Ometti la fine -li[:3] # => [1, 2, 4] -# Seleziona ogni seconda voce -li[::2] # =>[1, 4] -# Copia al contrario della lista -li[::-1] # => [3, 4, 2, 1] -# Usa combinazioni per fare slices avanzate -# li[inizio:fine:passo] - -# Crea una copia (one layer deep copy) usando la sintassi slices -li2 = li[:] # => li2 = [1, 2, 4, 3] ma (li2 is li) risulterà falso. - -# Rimuovi arbitrariamente elementi da una lista con "del" -del li[2] # li è ora [1, 2, 3] - -# Rimuove la prima occorrenza di un elemento -li.remove(2) # Ora li è [1, 3, 4, 5, 6] -li.remove(2) # Emette un ValueError, poichè 2 non è contenuto nella lista - -# Inserisce un elemento all'indice specificato -li.insert(1, 2) # li è di nuovo [1, 2, 3, 4, 5, 6] - - Ritorna l'indice della prima occorrenza dell'elemento fornito -li.index(2) # => 1 -li.index(7) # Emette un ValueError, poichè 7 non è contenuto nella lista - -# Puoi sommare le liste -# Nota: i valori per li e per other_li non vengono modificati. -li + other_li # => [1, 2, 3, 4, 5, 6] - -# Concatena le liste con "extend()" -li.extend(other_li) # Adesso li è [1, 2, 3, 4, 5, 6] - -# Controlla l'esistenza di un valore in una lista con "in" -1 in li # => True - -# Esamina la lunghezza con "len()" -len(li) # => 6 - - -# Le tuple sono come le liste ma immutabili. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Genera un TypeError - -# Note that a tuple of length one has to have a comma after the last element but -# tuples of other lengths, even zero, do not. -type((1)) # => -type((1,)) # => -type(()) # => - -# Puoi fare tutte queste cose da lista anche sulle tuple -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Puoi scompattare le tuple (o liste) in variabili -a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 e c è ora 3 -d, e, f = 4, 5, 6 # puoi anche omettere le parentesi -# Le tuple sono create di default se non usi le parentesi -g = 4, 5, 6 # => (4, 5, 6) -# Guarda come è facile scambiare due valori -e, d = d, e # d è ora 5 ed e è ora 4 - -# I dizionari memorizzano insiemi di dati indicizzati da nomi arbitrari (chiavi) -empty_dict= {} -# Questo è un dizionario pre-caricato -filled_dict = {"uno": 1, "due": 2, "tre": 3} - -# Nota: le chiavi dei dizionari devono essere di tipo immutabile. Questo per -# assicurare che le chiavi possano essere convertite in calori hash costanti -# per un risposta più veloce. -invalid_dict = {[1,2,3]: "123"} # => Emette un TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # I valori, invece, possono essere di qualunque tipo - -# Accedi ai valori indicando la chiave tra [] -filled_dict["uno"] # => 1 - -# Puoi ottenere tutte le chiavi di un dizionario con "keys()" -# (come oggetto iterabile). Per averle in formato lista è necessario -# utilizzare list(). -# Nota - Nei dizionari l'ordine delle chiavi non è garantito. -# Il tuo risultato potrebbe non essere uguale a questo. -list(filled_dict.keys()) # => ["tre", "due", "uno"] - - -# Puoi ottenere tutti i valori di un dizionario con "values()" -# (come oggetto iterabile). -# Anche in questo caso, er averle in formato lista, è necessario utilizzare list() -# Anche in questo caso, come per le chiavi, l'ordine non è garantito -list(filled_dict.values()) # => [3, 2, 1] - -# Controlla l'esistenza delle chiavi in un dizionario con "in" -"uno" in filled_dict # => True -1 in filled_dict # => False - -# Cercando una chiave non esistente genera un KeyError -filled_dict["quattro"] # KeyError - -# Usa il metodo "get()" per evitare KeyError -filled_dict.get("uno") # => 1 -filled_dict.get("quattro") # => None -# Il metodo get supporta un argomento di default quando il valore è mancante -filled_dict.get("uno", 4) # => 1 -filled_dict.get("quattro", 4) # => 4 - - -# "setdefault()" inserisce un valore per una chiave in un dizionario -# solo se la chiave data non è già presente -filled_dict.setdefault("cinque", 5) # filled_dict["cinque"] viene impostato a 5 -filled_dict.setdefault("cinque", 6) # filled_dict["cinque"] rimane 5 - -# Aggiungere una coppia chiave->valore a un dizionario -filled_dict.update({"quattro":4}) # => {"uno": 1, "due": 2, "tre": 3, "quattro": 4} -filled_dict["quattro"] = 4 # un altro modo pe aggiungere a un dizionario - -# Rimuovi una chiave da un dizionario con del -del filled_dict["uno"] # Rimuove la chiave "uno" dal dizionario - -# Da Python 3.5 puoi anche usare ulteriori opzioni di spacchettamento -{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} -{'a': 1, **{'a': 2}} # => {'a': 2} - -# I set sono come le liste ma non possono contenere doppioni -empty_set = set() -# Inizializza un "set()" con un dei valori. Sì, sembra un dizionario. -some_set = {1, 1, 2, 2, 3, 4} # set_nuovo è {1, 2, 3, 4} - -# Come le chiavi di un dizionario, gli elementi di un set devono essere -# di tipo immutabile -invalid_set = {[1], 1} # => Genera un "TypeError: unhashable type: 'list'"" -valid_set = {(1,), 1} - -# Aggiungere uno o più elementi ad un set -some_set.add(5) # some_set ora è {1, 2, 3, 4, 5} - -# Fai intersezioni su un set con & -other_set = {3, 4, 5, 6} -some_set & other_set # => {3, 4, 5} - -# Fai unioni su set con | -some_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Fai differenze su set con - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Effettua la differenza simmetrica con ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Controlla se il set a sinistra contiene quello a destra -{1, 2} >= {1, 2, 3} # => False - -# Controlla se il set a sinistra è un sottoinsieme di quello a destra -{1, 2} <= {1, 2, 3} # => True - -# Controlla l'esistenza in un set con in -2 in some_set # => True -10 in some_set # => False - - - -#################################################### -## 3. Control Flow e oggetti Iterabili -#################################################### - -# Dichiariamo una variabile -some_var = 5 - -# Questo è un controllo if. L'indentazione è molto importante in python! -# Come convenzione si utilizzano quattro spazi, non la tabulazione. -# Il seguente codice stampa "some_var è minore di 10" -if some_var > 10: - print("some_var è maggiore di 10") -elif some_var < 10: # La clausolo elif è opzionale - print("some_var è minore di 10") -else: # Anche else è opzionale - print("some_var è 10.") - -""" -I cicli for iterano sulle liste, cioè ripetono un codice per ogni elemento -di una lista. -Il seguente codice scriverà: - cane è un mammifero - gatto è un mammifero - topo è un mammifero -""" -for animale in ["cane", "gatto", "topo"]: - # Puoi usare format() per interpolare le stringhe formattate. - print("{} è un mammifero".format(animale)) - -""" -"range(numero)" restituisce una lista di numeri da zero al numero dato -Il seguente codice scriverà: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(lower, upper)" restituisce una lista di numeri dal più piccolo (lower) -al più grande (upper). -Il seguente codice scriverà: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(lower, upper, step)" rrestituisce una lista di numeri dal più piccolo -(lower) al più grande (upper), incrementando del valore step. -Se step non è indicato, avrà come valore di default 1. -Il seguente codice scriverà: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) -""" - -I cicli while vengono eseguiti finchè una condizione viene a mancare -Il seguente codice scriverà: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Forma compatta per x = x + 1 - -# Gestione delle eccezioni con un blocco try/except -try: - # Usa "raise" per generare un errore - raise IndexError("Questo è un IndexError") -except IndexError as e: - pass # Pass è solo una non-operazione. Solitamente vorrai rimediare all'errore. -except (TypeError, NameError): - pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario. -else: # Clausola opzionale al blocco try/except. Deve essere dopo tutti i blocchi except - print("Tutto ok!") # Viene eseguita solo se il codice dentro try non genera eccezioni -finally: # Eseguito sempre - print("Possiamo liberare risorse qui") - -# Se ti serve solo un try/finally, per liberare risorse, puoi usare il metodo with -with open("myfile.txt") as f: - for line in f: - print(line) - -# In Python qualunque oggetto in grado di essere trattato come una -# sequenza è definito un oggetto Iterable (itarabile). -# L'oggetto restituito da una funzione range è un iterabile. - -filled_dict = {"uno": 1, "due": 2, "tre": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['uno', 'due', 'tre']). -# Questo è un oggetto che implementa la nostra interfaccia Iterable. - -# È possibile utilizzarlo con i loop: -for i in our_iterable: - print(i) # Scrive uno, due, tre - -# Tuttavia non possiamo recuperarne i valori tramite indice. -our_iterable[1] # Genera un TypeError - -# Un oggetto iterabile è in grado di generare un iteratore -our_iterator = iter(our_iterable) - -# L'iteratore è un oggetto che ricorda il suo stato mentro lo si "attraversa" -# Possiamo accedere al successivo elemento con "next()". -next(our_iterator) # => "uno" - -# Mantiene il suo stato mentro eseguiamo l'iterazione -next(our_iterator) # => "due" -next(our_iterator) # => "tre" - -# Dopo che un iteratore ha restituito tutti i suoi dati, genera -# un'eccezione StopIteration -next(our_iterator) # Raises StopIteration - -# Puoi prendere tutti gli elementi di un iteratore utilizzando list(). -list(filled_dict.keys()) # => Returns ["one", "two", "three"] - - - -#################################################### -## 4. Funzioni -#################################################### - -# Usa "def" per creare nuove funzioni -def aggiungi(x, y): - print("x è {} e y è {}".format(x, y)) // Scrive i valori formattati in una stringa - return x + y # Restituisce la somma dei valori con il metodo return - -# Chiamare funzioni con parametri -aggiungi(5, 6) # => scrive "x è 5 e y è 6" e restituisce 11 - -# Un altro modo per chiamare funzioni è con parole chiave come argomenti -aggiungi(y=6, x=5) # In questo modo non è necessario rispettare l'ordine degli argomenti - -# Puoi definire funzioni che accettano un numero non definito di argomenti -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# Puoi definire funzioni che accettano un numero variabile di parole chiave -# come argomento, che saranno interpretati come un dizionario usando ** -def keyword_args(**kwargs): - return kwargs - -# Chiamiamola per vedere cosa succede -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# Puoi farle entrambi in una volta, se ti va -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) stampa: - (1, 2) - {"a": 3, "b": 4} -""" - -# Quando chiami funzioni, puoi fare l'opposto di args/kwargs! -# Usa * per sviluppare gli argomenti posizionale ed usa ** per -# espandere gli argomenti parola chiave -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalente a foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalente a foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) - - -# Restituire valori multipli (with tuple assignments) -def swap(x, y): - return y, x # Restituisce valori multipli come tupla senza parentesi - # (Nota: le parentesi sono state escluse ma possono essere messe) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # Le parentesi sono state escluse ma possono essere incluse. - -# Funzioni - Visibilità delle variabili (variable scope) -x = 5 - -def set_x(num): - # La variabile locale x non è la variabile globale x - x = num # => 43 - print(x) # => 43 - -def set_global_x(num): - global x - print(x) # => 5 - x = num # la variabile globable x è ora 6 - print(x) # => 6 - -set_x(43) -set_global_x(6) - - -# Python ha "first class functions" -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Ci sono anche funzioni anonime -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# È possibile creare "mappe" e "filtri" -list(map(add_10, [1, 2, 3])) # => [11, 12, 13] -list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] - -list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] - -# Possiamo usare le "list comprehensions" per mappe e filtri -# Le "list comprehensions" memorizzano l'output come una lista che può essere -# di per sé una lista annidata -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# Puoi fare anche la comprensione di set e dizionari -{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} -{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -## 5. Modules -#################################################### - -# Puoi importare moduli -import math -print(math.sqrt(16)) # => 4.0 - -# Puoi ottenere specifiche funzione da un modulo -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Puoi importare tutte le funzioni da un modulo -# Attenzione: questo non è raccomandato -from math import * - -# Puoi abbreviare i nomi dei moduli -import math as m -math.sqrt(16) == m.sqrt(16) # => True - - -# I moduli di Python sono normali file python. Ne puoi -# scrivere di tuoi ed importarli. Il nome del modulo -# è lo stesso del nome del file. - -# Potete scoprire quali funzioni e attributi -# sono definiti in un modulo -import math -dir(math) - -# Se nella cartella corrente hai uno script chiamato math.py, -# Python caricherà quello invece del modulo math. -# Questo succede perchè la cartella corrente ha priorità -# sulle librerie standard di Python - -# Se hai uno script Python chiamato math.py nella stessa -# cartella del tua script, Python caricherà quello al posto del -# comune modulo math. -# Questo accade perché la cartella locale ha la priorità -# sulle librerie built-in di Python. - - -#################################################### -## 6. Classes -#################################################### - -# Usiamo l'istruzione "class" per creare una classe -class Human: - - # Un attributo della classe. E' condiviso tra tutte le istanze delle classe - species = "H. sapiens" - - # Si noti che i doppi underscore iniziali e finali denotano gli oggetti o - # attributi utilizzati da Python ma che vivono nel namespace controllato - # dall'utente - # Metodi, oggetti o attributi come: __init__, __str__, __repr__, etc. sono - # chiamati metodi speciali (o talvolta chiamati "dunder methods"). - # Non dovresti inventare tali nomi da solo. - - def __init__(self, name): - # Assegna l'argomento all'attributo name dell'istanza - self.name = name - - # Inizializza una proprietà - self._age = 0 - - # Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento - def say(self, msg): - print("{name}: {message}".format(name=self.name, message=msg)) - - # Un altro metodo dell'istanza - def sing(self): - return 'yo... yo... microphone check... one two... one two...' - - # Un metodo della classe è condiviso fra tutte le istanze - # Sono chiamati con la classe chiamante come primo argomento - @classmethod - def get_species(cls): - return cls.species - - # Un metodo statico è chiamato senza classe o istanza di riferimento - @staticmethod - def grunt(): - return "*grunt*" - - # Una property è come un metodo getter. - # Trasforma il metodo age() in un attributo in sola lettura, che ha - # lo stesso nome - # In Python non c'è bisogno di scrivere futili getter e setter. - @property - def age(self): - return self._age - - # Questo metodo permette di modificare una property - @age.setter - def age(self, age): - self._age = age - - # Questo metodo permette di cancellare una property - @age.deleter - def age(self): - del self._age - -# Quando l'interprete Python legge un sorgente esegue tutto il suo codice. -# Questo controllo su __name__ assicura che questo blocco di codice venga -# eseguito solo quando questo modulo è il programma principale. - -if __name__ == '__main__': - # Crea un'istanza della classe - i = Human(name="Ian") - i.say("hi") # "Ian: hi" - j = Human("Joel") - j.say("hello") # "Joel: hello" - # i e j sono istanze del tipo Human, o in altre parole sono oggetti Human - - # Chiama un metodo della classe - i.say(i.get_species()) # "Ian: H. sapiens" - # Cambia l'attributo condiviso - Human.species = "H. neanderthalensis" - i.say(i.get_species()) # => "Ian: H. neanderthalensis" - j.say(j.get_species()) # => "Joel: H. neanderthalensis" - - # Chiama un metodo statico - print(Human.grunt()) # => "*grunt*" - - # Non è possibile chiamare il metodo statico con l'istanza dell'oggetto - # poiché i.grunt() metterà automaticamente "self" (l'oggetto i) - # come argomento - print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given - - # Aggiorna la property (age) di questa istanza - i.age = 42 - # Leggi la property - i.say(i.age) # => "Ian: 42" - j.say(j.age) # => "Joel: 0" - # Cancella la property - del i.age - i.age # => questo genererà un AttributeError - - -#################################################### -## 6.1 Ereditarietà (Inheritance) -#################################################### - -# L'ereditarietà consente di definire nuove classi figlio che ereditano metodi e -# variabili dalla loro classe genitore. - -# Usando la classe Human definita sopra come classe base o genitore, possiamo -# definire una classe figlia, Superhero, che erediterà le variabili di classe -# come "species", "name" e "age", così come i metodi, come "sing" e "grunt", -# dalla classe Human, ma potrà anche avere le sue proprietà uniche. - -# Per importare le funzioni da altri file usa il seguente formato -# from "nomefile-senza-estensione" import "funzione-o-classe" - -from human import Human - -# Specificare le classi genitore come parametri della definizione della classe -class Superhero(Human): - - # Se la classe figlio deve ereditare tutte le definizioni del genitore - # senza alcuna modifica, puoi semplicemente usare la parola chiave "pass" - # (e nient'altro) - - #Le classi figlio possono sovrascrivere gli attributi dei loro genitori - species = 'Superhuman' - - # Le classi figlie ereditano automaticamente il costruttore della classe - # genitore, inclusi i suoi argomenti, ma possono anche definire ulteriori - # argomenti o definizioni e sovrascrivere i suoi metodi (compreso il - # costruttore della classe). - # Questo costruttore eredita l'argomento "nome" dalla classe "Human" e - # aggiunge gli argomenti "superpowers" e "movie": - - def __init__(self, name, movie=False, - superpowers=["super strength", "bulletproofing"]): - - # aggiungi ulteriori attributi della classe - self.fictional = True - self.movie = movie - self.superpowers = superpowers - - # La funzione "super" ti consente di accedere ai metodi della classe - # genitore che sono stati sovrascritti dalla classe figlia, - # in questo caso il metodo __init__. - # Il seguente codice esegue il costruttore della classe genitore: - super().__init__(name) - - # Sovrascrivere il metodo "sing" - def sing(self): - return 'Dun, dun, DUN!' - - # Aggiungi un ulteriore metodo dell'istanza - def boast(self): - for power in self.superpowers: - print("I wield the power of {pow}!".format(pow=power)) - - -if __name__ == '__main__': - sup = Superhero(name="Tick") - - # Controllo del tipo di istanza - if isinstance(sup, Human): - print('I am human') - if type(sup) is Superhero: - print('I am a superhero') - - # Ottieni il "Method Resolution search Order" usato sia da getattr () - # che da super (). Questo attributo è dinamico e può essere aggiornato - print(Superhero.__mro__) # => (, - # => , ) - - # Esegui il metodo principale ma utilizza il proprio attributo di classe - print(sup.get_species()) # => Superhuman - - # Esegui un metodo che è stato sovrascritto - print(sup.sing()) # => Dun, dun, DUN! - - # Esegui un metodo di Human - sup.say('Spoon') # => Tick: Spoon - - # Esegui un metodo che esiste solo in Superhero - sup.boast() # => I wield the power of super strength! - # => I wield the power of bulletproofing! - - # Attributo di classe ereditato - sup.age = 31 - print(sup.age) # => 31 - - # Attributo che esiste solo in Superhero - print('Am I Oscar eligible? ' + str(sup.movie)) - -#################################################### -## 6.2 Ereditarietà multipla -#################################################### - -# Un'altra definizione di classe -# bat.py -class Bat: - - species = 'Baty' - - def __init__(self, can_fly=True): - self.fly = can_fly - - # Questa classe ha anche un metodo "say" - def say(self, msg): - msg = '... ... ...' - return msg - - # E anche un suo metodo personale - def sonar(self): - return '))) ... (((' - -if __name__ == '__main__': - b = Bat() - print(b.say('hello')) - print(b.fly) - -# Definizione di classe che eredita da Superhero e Bat -# superhero.py -from superhero import Superhero -from bat import Bat - -# Definisci Batman come classe figlia che eredita sia da Superhero che da Bat -class Batman(Superhero, Bat): - - def __init__(self, *args, **kwargs): - # In genere per ereditare gli attributi devi chiamare super: - # super(Batman, self).__init__(*args, **kwargs) - # Ma qui abbiamo a che fare con l'ereditarietà multipla, e super() - # funziona solo con la successiva classe nell'elenco MRO. - # Quindi, invece, chiamiamo esplicitamente __init__ per tutti gli - # antenati. L'uso di *args e **kwargs consente di passare in modo - # pulito gli argomenti, con ciascun genitore che "sbuccia un - # livello della cipolla". - Superhero.__init__(self, 'anonymous', movie=True, - superpowers=['Wealthy'], *args, **kwargs) - Bat.__init__(self, *args, can_fly=False, **kwargs) - # sovrascrivere il valore per l'attributo name - self.name = 'Sad Affleck' - - def sing(self): - return 'nan nan nan nan nan batman!' - - -if __name__ == '__main__': - sup = Batman() - - # Ottieni il "Method Resolution search Order" utilizzato da getattr() e super(). - # Questo attributo è dinamico e può essere aggiornato - print(Batman.__mro__) # => (, - # => , - # => , - # => , ) - - # Esegui il metodo del genitore ma utilizza il proprio attributo di classe - print(sup.get_species()) # => Superhuman - - # Esegui un metodo che è stato sovrascritto - print(sup.sing()) # => nan nan nan nan nan batman! - - # Esegui un metodo da Human, perché l'ordine di ereditarietà è importante - sup.say('I agree') # => Sad Affleck: I agree - - # Esegui un metodo che esiste solo nel 2o antenato - print(sup.sonar()) # => ))) ... ((( - - # Attributo di classe ereditato - sup.age = 100 - print(sup.age) # => 100 - - # Attributo ereditato dal secondo antenato il cui valore predefinito - # è stato ignorato. - print('Can I fly? ' + str(sup.fly)) # => Can I fly? False - - - -#################################################### -## 7. Advanced -#################################################### - -# I generatori ti aiutano a creare codice pigro (lazy code). -# Codice che darà un risultato solo quando sarà "valutato" -def double_numbers(iterable): - for i in iterable: - yield i + i - -# I generatori sono efficienti in termini di memoria perché caricano -# solo i dati necessari per elaborare il valore successivo nell'iterabile. -# Ciò consente loro di eseguire operazioni su intervalli di valori -# altrimenti proibitivi. -# NOTA: `range` sostituisce` xrange` in Python 3. -for i in double_numbers(range(1, 900000000)): # `range` is a generator. - print(i) - if i >= 30: - break - -# Proprio come è possibile creare una "list comprehension", è possibile -# creare anche delle "generator comprehensions". -values = (-x for x in [1,2,3,4,5]) -for x in values: - print(x) # prints -1 -2 -3 -4 -5 to console/terminal - -# Puoi anche trasmettere una "generator comprehensions" direttamente -# ad un elenco. -values = (-x for x in [1,2,3,4,5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - - -# Decoratori -# In questo esempio "beg" avvolge/wrappa "say". -# Se say_please è True, cambierà il messaggio restituito. -from functools import wraps - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Per favore! Sono povero :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Puoi comprarmi una birra?" - return msg, say_please - - -print(say()) # Puoi comprarmi una birra? -print(say(say_please=True)) # Puoi comprarmi una birra? Per favore! Sono povero :( -``` - -## Pronto per qualcosa di più? - -### Gratis Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) -* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) -* [Dive Into Python 3](http://www.diveintopython3.net/index.html) -* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/ja-jp/python-jp.html.markdown b/ja-jp/python-jp.html.markdown new file mode 100644 index 00000000..b9731411 --- /dev/null +++ b/ja-jp/python-jp.html.markdown @@ -0,0 +1,1008 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] + - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] +translators: + - ["kakakaya", "https://github.com/kakakaya"] + - ["Ryota Kayanuma", "https://github.com/PicoSushi"] +filename: learnpython3-jp.py +lang: ja-jp +--- + +90年代の初め、Guido van RossumによってPythonは作成されました。現在となっては、最も有名な言語の1つです。 +私は構文の明快さによって、Pythonと恋に落ちました。 +以下は基本的に実行可能な疑似コードです。 + +フィードバッグは大歓迎です! [@louiedinh](http://twitter.com/louiedinh) または louiedinh [at] [google's email service] にご連絡下さい! + +Note: この記事はPython 3に内容を絞っています。もし古いPython 2.7を学習したいなら、 [こちら](http://learnxinyminutes.com/docs/python/) をご確認下さい。 + +```python +# 1行のコメントは番号記号(#)から始まります。 + +""" 複数行の文字は、"を3つ繋げることで + 書くことができます。 + また、これはドキュメントとしてもよく使われます。 +""" + +#################################################### +# 1. プリミティブ型と演算子 +#################################################### + +# 数字です +3 # => 3 + +# 四則演算はあなたの期待通りに動きます。 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# 整数除算の結果は、正負に関わらず小数の切り捨てが行われます。 +5 // 3 # => 1 +-5 // 3 # => -2 +5.0 // 3.0 # => 1.0 # 浮動小数点でも同様に動作します。 +-5.0 // 3.0 # => -2.0 + +# 除算の結果は常に浮動小数点になります。 +10.0 / 3 # => 3.3333333333333335 + +# 剰余の計算 +7 % 3 # => 1 + +# 冪乗 (x**y, x の y 乗) +2**3 # => 8 + +# 括弧により、計算の順番を優先させられます。 +(1 + 3) * 2 # => 8 + +# 真偽値はプリミティブ型です(大文字から始まっていることに注意!) +True +False + +# not で真偽を反転させられます。 +not True # => False +not False # => True + +# ブール演算 +# 注意: "and" と "or" は小文字です。 +True and False # => False +False or True # => True + +# TrueとFalseは実際には1と0になるキーワードです。 +True + True # => 2 +True * 8 # => 8 +False - 5 # => -5 + +# 比較演算子はTrueとFalseを数値として扱います。 +0 == False # => True +1 == True # => True +2 == True # => False +-5 != True # => True + +# bool論理演算子を整数に対して使うことで整数を真偽値に変換して評価できますが、キャストされていない値が +# bool(int)とビット演算子(& や |)を混同しないようにうにしましょう。 +bool(0) # => False +bool(4) # => True +bool(-6) # => True +0 and 2 # => 0 +-5 or 0 # => -5 + +# 値が等しいか確認するには == +1 == 1 # => True +2 == 1 # => False + +# 値が等しくないか確認するには != +1 != 1 # => False +2 != 1 # => True + +# 他の比較方法 +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# 値がある範囲の中にあるか調べる方法 +1 < 2 and 2 < 3 # => True +2 < 3 and 3 < 2 # => False + +# 連結させるともっと見やすくなります。 +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) +# "is" は、2つの変数が同一のオブジェクトを参照しているか確認します。 +# 一方 "==" は、それぞれが参照する2つのオブジェクトが同じ値を持つか確認します。 +a = [1, 2, 3, 4] # a は新しいリストの [1, 2, 3, 4] を指します。 +b = a # b は a が指すリストを指します。 +b is a # => True, a と b は同一のオブジェクトを参照しています。 +b == a # => True, a と b が参照するオブジェクトの値は等しいです。 +b = [1, 2, 3, 4] # b は新しいリストの [1, 2, 3, 4] を指します。 +b is a # => False, a と b は別々のオブジェクトを参照しています。 +b == a # => True, a と b が参照するオブジェクトの値は等しいです。 + +# " または ' を使って文字列を作成します。 +"This is a string." +'This is also a string.' + +# 文字列も加算をすることができます!でも、あまり行わないように。 +"Hello " + "world!" # => "Hello world!" +# '+' を使わなくても文字列リテラル(変数ではないもの)の連結ができます。 +"Hello " "world!" # => "Hello world!" + +# 文字列は文字のリストであるかのように扱うことができます。 +"This is a string"[0] # => 'T' + +# 文字列の長さを得るにはこのようにします。 +len("This is a string") # => 16 + +# .format で文字列のフォーマットを行えます +"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" + +# 入力を減らすために、フォーマットするときに引数を繰り返し使うことができます。 +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# 引数の順番を数えるのがお嫌い?キーワード引数をどうぞ。 +"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" + +# もし Python 3 のコードを Python 2.5以下でも使う必要があるなら、 +# 旧式のフォーマット方法を使うこともできます。 +"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" + +# Python3.6以上では、f-stringsやフォーマット文字列を使ってフォーマットすることもできます。 +name = "Reiko" +f"She said her name is {name}." # => "She said her name is Reiko" + +# 基本的に、任意のPythonの文を中括弧に書くことができ、それは評価されて出力されます。 +f"{name} is {len(name)} characters long." + +# None はオブジェクトです(大文字からです!) +None # => None + +# オブジェクトがNoneであるか確認するのに "==" 演算子を使わないように。 +# 代わりに "is" を使いましょう。オブジェクトの素性を確認できます。 +"etc" is None # => False +None is None # => True + +# None や 0 、空の 文字列/リスト/辞書/タプル は全て False として評価されます。 +# 他の全ての値は True になります。 +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +# 2. Variables and Collections +#################################################### + +# Python にはprint関数があります。 +print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! + +# 標準では、print関数は最後に改行を出力します。 +# この動作を変更するためには、オプション引数を利用します。 +print("Hello, World", end="!") # => Hello, World! + +# コンソールから入力を得るための簡単な例 +input_string_var = input("Enter some data: ") # 入力を文字列として返します +# Note: Python の初期のバージョンでは、 input() は raw_input() という名前で存在します。 + +# Pythonでは変数の宣言は存在せず、代入のみです。 +# 慣例的に、小文字でアンダースコア区切り ( lower_case_with_underscores ) の変数が使われます。 +some_var = 5 +some_var # => 5 + +# 代入されていない変数へのアクセスは例外を引き起こします。 +# 例外の取り扱いについては、3章の制御の流れをご確認ください。 +some_unknown_var # NameError を送出します + +# ifは式として使用できます。 +# C言語の「?:(三項演算子)」に対応する例: +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# リストは順序を保存します。 +li = [] +# 値の入っているリストも作成できます。 +other_li = [4, 5, 6] + +# append により、リストの末尾にものを入れられます。 +li.append(1) # li is now [1] +li.append(2) # li is now [1, 2] +li.append(4) # li is now [1, 2, 4] +li.append(3) # li is now [1, 2, 4, 3] +# pop でリストの末尾から取り除けます。 +li.pop() # => 3 and li is now [1, 2, 4] +# 元に戻しましょう! +li.append(3) # li is now [1, 2, 4, 3] again. + +# 配列のように、リストにアクセスできます。 +li[0] # => 1 +# 最後の要素を参照できます。 +li[-1] # => 3 + +# 範囲外の要素を参照すると IndexError になります。 +li[4] # IndexError が発生します + +# スライス構文により範囲を参照できます。 +# 開始部分のインデックスに対応する部分は含まれますが、終了部分のインデックスに対応する部分は含まれません。 +li[1:3] # => [2, 4] +# 先端を取り除いたリスト +li[2:] # => [4, 3] +# 末尾を取り除いたリスト +li[:3] # => [1, 2, 4] +# 1つ飛ばしで選択する +li[::2] # =>[1, 4] +# 反転したリストを得る +li[::-1] # => [3, 4, 2, 1] +# これらの任意の組み合わせにより、より複雑なスライスを作ることができます。 +# li[start:end:step] + +# スライスにより、深いコピーを1階層分行うことができます。 +li2 = li[:] # => li2 = [1, 2, 4, 3] だが、 (li2 is li) はFalseになる。 + +# "del"によりリストから任意の要素を削除できます。 +del li[2] # li は [1, 2, 3] になりました。 + +# "remove"で最初に出現する要素を削除できます。 +li.remove(2) # li は [1, 3] になりました。 +li.remove(2) # 2はリストの中に存在しないので、 ValueError が発生します。 + +# 要素を好きなところに挿入できます。 +li.insert(1, 2) # li は [1, 2, 3] に戻りました。 + +# "index"で引数の要素が最初に出現する場所のインデックスを得られます。 +li.index(2) # => 1 +li.index(4) # 4はリストの中に存在しないので、 ValueError が発生します。 + +# リスト同士を足すこともできます。 +# Note: li と other_li の値は変更されません。 +li + other_li # => [1, 2, 3, 4, 5, 6] + +# "extend()"で他のリストを連結することができます。 +li.extend(other_li) # li は [1, 2, 3, 4, 5, 6] になります。 + +# リストの中に値が存在するか、 "in" で確認できます。 +1 in li # => True + +# 長さは "len()" で確認できます。 +len(li) # => 6 + + +# タプルはリストのようなものですが、不変であるという違いがあります。 +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # 内容を変更しようとすると TypeError が発生します。 + +# 長さが1のタプルを作成するには、要素の後にカンマを付ける必要があります。 +# しかし、それ以外の長さなら、例え長さが0でもそのようにする必要はありません。 +type((1)) # => +type((1,)) # => +type(()) # => + +# 大抵のリスト操作はタプルでも行うことができます。 +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# タプルやリストから複数の変数に代入することができます。 +a, b, c = (1, 2, 3) # a, b, c にはそれぞれ 1, 2, 3 が代入されました。 +# 拡張記法もあります。 +a, *b, c = (1, 2, 3, 4) # a は 1 、 b は [2, 3] 、c は4 になります。 +# 括弧を作成しなくてもデフォルトでタプルが作成されます。 +d, e, f = 4, 5, 6 # 4、5、6がそれぞれd、 e、 fに代入されます。 +# 2つの変数を交換するのがどれほど簡単か見てみましょう。 +e, d = d, e # d は 5 、 e は e になります。 + + +# 辞書はマップ(キーと値の組み合わせ)を保存できます。 +empty_dict = {} +# 値が入っている辞書を直接作成することもできます。 +filled_dict = {"one": 1, "two": 2, "three": 3} + +# キーは不変の型である必要があります。 +# これは、高速化のため、キーを定数のハッシュ値に変換できるようにするためです。 +# 不変の型の例として、int、float、string、tupleなどが上げられます。 +invalid_dict = {[1, 2, 3]: "123"} # => list はハッシュ化できないので、 TypeError が発生します。 +valid_dict = {(1, 2, 3): [1, 2, 3]} # 一方、キーに対応する値はどのような型でも利用できます。 + +# [] で 値を取り出せます。 +filled_dict["one"] # => 1 + +# "keys()"により、全てのキーを反復可能な形式で取り出せます。 +# これをリストにするために、"list()"で囲んでいます。これについては後程解説します。 +# Note: Python3.7未満では、辞書のキーの順番は考慮されていません。実行した結果がこれと異なる場合があります。 +# しかし、Python3.7以降ではキーの挿入順を保つようになりました。 +list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7 +list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+ + + +# "values()"により、全ての値を反復可能な形式で取り出せます。 +# 前と同じように、これをリストにするために、"list()"で囲んでいます。 +# Note: 辞書の値の順番は考慮されていません。実行した結果がこれと異なる場合があります。 +list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 +list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ + +# "in" により、辞書のキーが存在するか確認できます。 +"one" in filled_dict # => True +1 in filled_dict # => False + +# 存在しないキーで辞書を参照すると KeyError になります。 +filled_dict["four"] # KeyError + +# "get()" メソッドを使うことで KeyError を回避できます。 +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# get ではキーが存在しなかったときのデフォルト値を指定できます。 +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" で、キーが存在しなかった場合のみ、値を設定できます。 +filled_dict.setdefault("five", 5) # filled_dict["five"] は 5 になりました。 +filled_dict.setdefault("five", 6) # filled_dict["five"] は 5 のままです。 + +# 辞書にマップを追加する +filled_dict.update({"four": 4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict["four"] = 4 # 辞書に追加する別の方法 + +# del により辞書からキーを削除できます。 +del filled_dict["one"] # "one" キーを辞書から削除します。 + +# Python 3.5 以降では、追加の値を取り出す方法があります。 +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + +# set では集合を表現できます。 +empty_set = set() +# 集合を一連の値で初期化する例です。辞書に似ていますね?ごめんなさい。 +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# 辞書のキーのように、集合の値は不変である必要があります。 +invalid_set = {[1], 1} # => list はハッシュ化できないので、 TypeError が送出されます。 +valid_set = {(1,), 1} + +# 集合に新しい要素を追加できます。 +filled_set = some_set +filled_set.add(5) # filled_set は {1, 2, 3, 4, 5} になりました。 +# 集合は重複した要素を持ちません。 +filled_set.add(5) # 以前の{1, 2, 3, 4, 5}のままです。 + +# & により、集合同士の共通部分が得られます。 +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# | により、集合同士の合併が得られます。 +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# - により、集合同士の差集合が得られます。 +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# ^ により、集合同士の対象差が得られます。 +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# 左の集合が右の集合の上位集合であるか確認。 +{1, 2} >= {1, 2, 3} # => False + +# 左の集合が右の集合の部分集合であるか確認。 +{1, 2} <= {1, 2, 3} # => True + +# in により値が集合の中に存在するか確認できます。 +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +# 3. 制御の流れとiterable +#################################################### + +# まずは変数を作りましょう。 +some_var = 5 + +# これはif文です。Pythonではインデントが特徴的ですね! +# 規約ではタブではなく4つのスペースでインデントすることが推奨されています。 +# 以下の例では"some_var is smaller than 10"と出力されます。 +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # この elif 節はオプションです。 + print("some_var is smaller than 10.") +else: # この else 節もオプションです。 + print("some_var is indeed 10.") + + +""" +for ループはリストの要素を反復することができます。 +出力: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # format() を使って文字列に変数を挿入して出力できます。 + print("{} is a mammal".format(animal)) + +""" +"range(数値)" は、ゼロから与えられた数値までのiterableを返します。 +出力: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(lower, upper)" は、 lower の数値から upper の数値までのiterableを返します。 +upper の数値は含まれません。 +出力: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(lower, upper, step)" は、lower の数値から upper の数値までが、 +step 刻みで表現されるiterableを返します +step が与えられない場合、デフォルトは1になります。 +出力: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +while によるループは条件が成立しなくなるまで実行されます。 +出力: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # x = x + 1 の省略記法 + +# try/except ブロックにより、例外を扱う +try: + # "raise" により例外を発生させます。 + raise IndexError("This is an index error") +except IndexError as e: + pass # pass は、何もしないという命令(no-op)に相当します。普通、ここで例外に対処します。 +except (TypeError, NameError): + pass # もし必要なら、複数の種類の例外を一緒に処理できます。 +else: # try/except ブロックへのオプションの節。他の全てのexceptブロックより後に置かなければなりません。 + print("All good!") # tryで例外が発生しなかった場合のみ実行されます。 +finally: # 例外が発生したか、しなかったか、どのような例外だったかに関らず実行されます。 + print("We can clean up resources here") + +# try/finallyでリソースの始末をする代わりに、 with 文を使うこともできます。 +with open("myfile.txt") as f: + for line in f: + print(line) + +# Pythonは、iterableと呼ばれる基本的な抽象化が提供しています。 +# iterableは、シーケンスとして取り扱えるオブジェクトです。 +# range関数で返されるオブジェクトもiterableの一種です。 +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['one', 'two', 'three']). これはiterableインタフェースを実装するオブジェクトです。 + +# iterableでループを行うことができます。 +for i in our_iterable: + print(i) # Prints one, two, three + +# しかし、インデックスで要素を参照することはできません。 +our_iterable[1] # TypeError が発生します。 + +# iterableは、iteratorの作り方がわかるオブジェクトです。 +our_iterator = iter(our_iterable) + +# iterator は、要素を取り出したときの状態を覚えるオブジェクトです。 +# "next()"により次の要素を取り出せます。 +next(our_iterator) # => "one" + +# 反復(iterate)する度に、状態を更新します。 +next(our_iterator) # => "two" +next(our_iterator) # => "three" + +# iteratorが自身の持つ全てのデータを返したあとは、 StopIteration 例外を発生させます。 +next(our_iterator) # StopIteration が発生します。 + +# "list()"を呼ぶことにより、iteratorの全ての要素を得られます。 +list(filled_dict.keys()) # => ["one", "two", "three"] + + +#################################################### +# 4. 関数 +#################################################### + +# 新しい関数を作成するには "def" を使います。 +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # return 文で値を返します。 + +# 引数付きで関数を呼んでみましょう。 +add(5, 6) # => "x is 5 and y is 6" と出力し、 11 を返します。 + +# キーワード引数で関数を呼ぶこともできます。 +add(y=6, x=5) # キーワード引数を使うと任意の順番で引数を指定できます。 + + +# 可変数の位置引数を持つ関数を定義できます。 +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# 可変数のキーワード引数を持つ関数を定義できます。 +def keyword_args(**kwargs): + return kwargs + +# 何が起こるか、試してみましょう +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# お望みなら、両方一気にやることもできます。 +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# 関数を呼ぶとき、 args/kwargs の逆のことをすることができます! +# * を使ってタプルを展開したり、 ** を使って辞書を展開できます。 +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # all_the_args(1, 2, 3, 4) と等しいです。 +all_the_args(**kwargs) # all_the_args(a=3, b=4) と等しいです。 +all_the_args(*args, **kwargs) # all_the_args(1, 2, 3, 4, a=3, b=4) と等しいです。 + + +# タプルで複数の値を返す +def swap(x, y): # 括弧を使わずに、複数の値をタプルとして返すことができます。 + return y, x # (Note: 括弧は使わなくてもいいですが、使うこともできます。) + + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # このように、括弧は使っても使わなくてもいいです。 + + +# 関数のスコープ +x = 5 + + +def set_x(num): + # ローカル変数の x はグローバル変数の x とは異なります + x = num # => 43 + print(x) # => 43 + + +def set_global_x(num): + global x + print(x) # => 5 + x = num # グローバル変数の x に 6 が代入されました。 + print(x) # => 6 + +set_x(43) +set_global_x(6) + + +# Pythonは第一級関数をサポートします。 +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# 無名関数もサポートしています。 +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# 高階関数も組込まれています。 +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# map や filter の代わりに、リスト内包表記を使うことができます。 +# リスト内包表記は、出力を別のリスト内包表記にネストさせることができます。 +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# 集合(set)や辞書も内包表記ができます。 +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +# 5. モジュール +#################################################### + +# Pythonではモジュールをインポートできます。 +import math +print(math.sqrt(16)) # => 4.0 + +# モジュールの中から特定の関数をインポートすることもできます。 +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# 全部の関数をモジュールからインポートすることができます。 +# Warning: この方法は推奨されません。 +from math import * + +# 短い名前でモジュールをインポートすることができます。 +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Pythonのモジュールは実際には単なるPythonのファイルです。 +# 自分で書くことも、インポートすることもできます。 +# ファイル名がそのままモジュール名になります。 + +# モジュールで定義されている関数と属性を調べることができます。 +import math +dir(math) + +# もし、現在書いているスクリプトと同じフォルダに「math.py」という +# Pythonのスクリプトが存在する場合、そのmath.pyが +# 組み込みのPythonモジュールの代わりに読み込まれるでしょう。 +# これは、ローカルのフォルダはPythonの組み込みライブラリよりも +# 優先度が高いため発生するのです。 + + +#################################################### +# 6. クラス +#################################################### + +# クラスを作成するために、class文を使います。 +class Human: + + # クラスの属性です。このクラスの全てのインスタンスで共有されます。 + species = "H. sapiens" + + # 標準的なイニシャライザで、このクラスがインスタンスを作成するときは毎回呼ばれます。 + # 2つのアンダースコアがオブジェクトや属性の前後についているとき、これらはPythonによって利用され、 + # ユーザーの名前空間には存在しないということに注意してください。 + # __init__ や __str__ 、 __repr__ のようなメソッド(やオブジェクト、属性)は、 + # special methods (または dunder methods)と呼ばれます。 + # 同じような名前を自分で発明しないほうがよいでしょう。 + def __init__(self, name): + # 引数をインスタンスのname属性に設定します。 + self.name = name + + # プロパティの初期化 + self._age = 0 + + # インスタンスメソッド。全てのメソッドは"self"を最初の引数に取ります。 + def say(self, msg): + print("{name}: {message}".format(name=self.name, message=msg)) + + # 別のインスタンスメソッドの例。 + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # クラスメソッドは全てのインスタンスで共有されます。 + # クラスメソッドではクラスを最初の引数として呼ばれます。 + @classmethod + def get_species(cls): + return cls.species + + # スタティックメソッドはクラスやインスタンスを参照せずに呼ばれます。 + @staticmethod + def grunt(): + return "*grunt*" + + # プロパティはgetterのようなものです。 + # age() メソッドを同名の読取専用属性に変換します。 + # Pythonではわざわざgetterやsetterを書く必要はありません。 + @property + def age(self): + return self._age + + # プロパティを設定できるようにします。 + @age.setter + def age(self, age): + self._age = age + + # プロパティを削除できるようにします。 + @age.deleter + def age(self): + del self._age + + +# Pythonインタプリタがソースファイルを読み込んだとき、全てのコードを実行します。 +# この __name__ による確認により、このモジュールがメインのプログラムである場合にのみ、 +# このコードブロックが実行されるようにします。 +if __name__ == '__main__': + # クラスのインスタンスを作成します。 + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i と j はHumanのインスタンスです。別の言葉で言うなら、これらはHumanのオブジェクトです。 + + # クラスメソッドを呼んでみましょう。 + i.say(i.get_species()) # "Ian: H. sapiens" + # 共有属性を変更してみましょう。 + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # スタティックメソッドを呼んでみましょう。 + print(Human.grunt()) # => "*grunt*" + + # スタティックメソッドはインスタンスから呼ぶことはできません。 + # なぜならば、 i.grunt() は自動的に"self" ( i オブジェクト ) を引数として渡してしまうからです。 + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # インスタンスのプロパティを更新してみましょう。 + i.age = 42 + # プロパティを取得してみましょう。 + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # プロパティを削除してみましょう。 + del i.age + # i.age # => AttributeError が発生します。 + + +#################################################### +# 6.1 継承 +#################################################### +# 継承を行うことで、親クラスからメソッドと変数を継承する新しい子クラスを定義できます。 + +# 上記で定義されたHumanクラスを親クラス(基底クラス)として使い、Superheroという子クラスを定義します。 +# これは"species"、"name"や"age"といった変数や、"sing"や"grunt"のようなメソッドをHumanから継承しますが、 +# Superhero独自のプロパティを持つこともできます。 + +# ファイルを分割してモジュール化の利点を活用するために、上記のHumanクラスを独自のファイル、ここでは human.py に記述ましょう。 + +# 別のファイルから関数をインポートするには次の形式を利用してください: +# from "拡張子なしのファイル名" import "関数やクラス" + +from human import Human + + +# 親クラスを子クラスのパラメータとして指定します +class Superhero(Human): + + # もし子クラスが親クラスの全ての定義を変更なしで継承する場合、"pass"キーワードのみを書くだけで良いです。 + # しかし、今回は親クラスとは異なる子クラスを作成するので、今回は以下の通りコメントアウトしています。 + # pass + + # 子クラスは親クラスの属性を上書きできます。 + species = 'Superhuman' + + # 子クラスは親クラスのコンストラクタを引数含めて自動的に継承しますが、 + # 追加の引数や定義を行ってコンストラクタのようなメソッドを上書きすることもできます。 + # このコンストラクタは"name"引数を"Human"クラスから継承し、"superpower"と"movie"という引数を追加します。 + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # 追加のクラス属性を作成する + self.fictional = True + self.movie = movie + # デフォルト値は共有されるので、可変のデフォルト値には注意してください。 + self.superpowers = superpowers + + # "super"関数を使うと子クラスに上書きされた親クラスのメソッド(今回は "__init__")にアクセスできます。 + # これで、親クラスのコンストラクタを呼んでいます。 + super().__init__(name) + + # singメソッドを上書きし、 + def sing(self): + return 'Dun, dun, DUN!' + + # 追加のインスタンスメソッドを作成します。 + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # インスタンスの型を調べる + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') + + # getattr()とsuper()で使われるメソッドの解決順序を調べてみます。 + # この属性は動的であり、変更可能です。 + print(Superhero.__mro__) # => (, + # => , ) + + # 親のメソッドを呼びだすものの、独自のクラス属性を参照します。 + print(sup.get_species()) # => Superhuman + + # 上書きされたメソッドを呼ぶ + print(sup.sing()) # => Dun, dun, DUN! + + # Humanのメソッドを呼ぶ + sup.say('Spoon') # => Tick: Spoon + + # Superhero限定のメソッドを呼ぶ + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # 継承されたクラス属性 + sup.age = 31 + print(sup.age) # => 31 + + # Superhero限定の属性 + print('Am I Oscar eligible? ' + str(sup.movie)) + + + +#################################################### +# 6.2 多重継承 +#################################################### + +# 別のクラスを定義します。 +# bat.py +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # このクラスも say メソッドを持ちます。 + def say(self, msg): + msg = '... ... ...' + return msg + + # 同様に、独自のメソッドも与えましょう。 + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + +# superhero.py +from superhero import Superhero +from bat import Bat + +# BatmanをSuperheroとBatの両方を継承した子クラスとして定義します。 +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # 通常、属性を継承するにはsuper()を呼び出します。 + # super(Batman, self).__init__(*args, **kwargs) + # しかし、ここでは多重継承を行っているので、 super() はMRO(メソッド解決順序)の次の基本クラスにのみ動作します。 + # なので、全ての祖先に対して明示的に __init__ を呼ぶことにします。 + # *args と **kwargs を使うことで、それぞれの継承元が + # たまねぎの皮を剥がすごとく、引数を用いることができます。 + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # 名前の属性の値を上書きします。 + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # getattr() や super() の両方で使われるMROを取得します。 + # この属性は動的であり、更新が可能です。 + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + + # 親メソッドを呼び出しますが、独自のクラス属性を参照します。 + print(sup.get_species()) # => Superhuman + + # 上書きされたメソッドを呼び出します。 + print(sup.sing()) # => nan nan nan nan nan batman! + + # 継承順により、Humanから継承されたメソッドを呼び出します。 + sup.say('I agree') # => Sad Affleck: I agree + + # 2番目の先祖にのみ存在するメソッドを呼び出してみます。 + print(sup.sonar()) # => ))) ... ((( + + # 継承されたクラス属性 + sup.age = 100 + print(sup.age) # => 100 + + # デフォルト値が上書きされて、2番目の先祖から継承された属性 + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False + + +#################################################### +# 7. 発展的内容 +#################################################### + +# ジェネレータは遅延をするコードの作成に役立ちます。 +def double_numbers(iterable): + for i in iterable: + yield i + i + +# 次の値を処理するのに必要なデータしか読み込まないので、ジェネレータはメモリをあまり消費しません。 +# この性質により、他の方法では非常に多くのメモリを消費するような操作が可能になります。 +for i in double_numbers(range(1, 900000000)): # `range` もジェネレータの1つです。 + print(i) + if i >= 30: + break + +# リスト内包表記のように、ジェネータ内包表記を作成することもできます。 +values = (-x for x in [1, 2, 3, 4, 5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 + +# ジェネレータ内包表記から直接リストを作成することもできます。 +values = (-x for x in [1, 2, 3, 4, 5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + +# デコレータ +# この例では`beg` が `say` を `wraps`します。 +# もし say_please が True なら、出力が変更されます。 +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +``` + +## Ready For More? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/ja-jp/python3-jp.html.markdown b/ja-jp/python3-jp.html.markdown deleted file mode 100644 index b9731411..00000000 --- a/ja-jp/python3-jp.html.markdown +++ /dev/null @@ -1,1008 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["evuez", "http://github.com/evuez"] - - ["Rommel Martinez", "https://ebzzry.io"] - - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] -translators: - - ["kakakaya", "https://github.com/kakakaya"] - - ["Ryota Kayanuma", "https://github.com/PicoSushi"] -filename: learnpython3-jp.py -lang: ja-jp ---- - -90年代の初め、Guido van RossumによってPythonは作成されました。現在となっては、最も有名な言語の1つです。 -私は構文の明快さによって、Pythonと恋に落ちました。 -以下は基本的に実行可能な疑似コードです。 - -フィードバッグは大歓迎です! [@louiedinh](http://twitter.com/louiedinh) または louiedinh [at] [google's email service] にご連絡下さい! - -Note: この記事はPython 3に内容を絞っています。もし古いPython 2.7を学習したいなら、 [こちら](http://learnxinyminutes.com/docs/python/) をご確認下さい。 - -```python -# 1行のコメントは番号記号(#)から始まります。 - -""" 複数行の文字は、"を3つ繋げることで - 書くことができます。 - また、これはドキュメントとしてもよく使われます。 -""" - -#################################################### -# 1. プリミティブ型と演算子 -#################################################### - -# 数字です -3 # => 3 - -# 四則演算はあなたの期待通りに動きます。 -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 - -# 整数除算の結果は、正負に関わらず小数の切り捨てが行われます。 -5 // 3 # => 1 --5 // 3 # => -2 -5.0 // 3.0 # => 1.0 # 浮動小数点でも同様に動作します。 --5.0 // 3.0 # => -2.0 - -# 除算の結果は常に浮動小数点になります。 -10.0 / 3 # => 3.3333333333333335 - -# 剰余の計算 -7 % 3 # => 1 - -# 冪乗 (x**y, x の y 乗) -2**3 # => 8 - -# 括弧により、計算の順番を優先させられます。 -(1 + 3) * 2 # => 8 - -# 真偽値はプリミティブ型です(大文字から始まっていることに注意!) -True -False - -# not で真偽を反転させられます。 -not True # => False -not False # => True - -# ブール演算 -# 注意: "and" と "or" は小文字です。 -True and False # => False -False or True # => True - -# TrueとFalseは実際には1と0になるキーワードです。 -True + True # => 2 -True * 8 # => 8 -False - 5 # => -5 - -# 比較演算子はTrueとFalseを数値として扱います。 -0 == False # => True -1 == True # => True -2 == True # => False --5 != True # => True - -# bool論理演算子を整数に対して使うことで整数を真偽値に変換して評価できますが、キャストされていない値が -# bool(int)とビット演算子(& や |)を混同しないようにうにしましょう。 -bool(0) # => False -bool(4) # => True -bool(-6) # => True -0 and 2 # => 0 --5 or 0 # => -5 - -# 値が等しいか確認するには == -1 == 1 # => True -2 == 1 # => False - -# 値が等しくないか確認するには != -1 != 1 # => False -2 != 1 # => True - -# 他の比較方法 -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# 値がある範囲の中にあるか調べる方法 -1 < 2 and 2 < 3 # => True -2 < 3 and 3 < 2 # => False - -# 連結させるともっと見やすくなります。 -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# (is vs. ==) -# "is" は、2つの変数が同一のオブジェクトを参照しているか確認します。 -# 一方 "==" は、それぞれが参照する2つのオブジェクトが同じ値を持つか確認します。 -a = [1, 2, 3, 4] # a は新しいリストの [1, 2, 3, 4] を指します。 -b = a # b は a が指すリストを指します。 -b is a # => True, a と b は同一のオブジェクトを参照しています。 -b == a # => True, a と b が参照するオブジェクトの値は等しいです。 -b = [1, 2, 3, 4] # b は新しいリストの [1, 2, 3, 4] を指します。 -b is a # => False, a と b は別々のオブジェクトを参照しています。 -b == a # => True, a と b が参照するオブジェクトの値は等しいです。 - -# " または ' を使って文字列を作成します。 -"This is a string." -'This is also a string.' - -# 文字列も加算をすることができます!でも、あまり行わないように。 -"Hello " + "world!" # => "Hello world!" -# '+' を使わなくても文字列リテラル(変数ではないもの)の連結ができます。 -"Hello " "world!" # => "Hello world!" - -# 文字列は文字のリストであるかのように扱うことができます。 -"This is a string"[0] # => 'T' - -# 文字列の長さを得るにはこのようにします。 -len("This is a string") # => 16 - -# .format で文字列のフォーマットを行えます -"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" - -# 入力を減らすために、フォーマットするときに引数を繰り返し使うことができます。 -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# 引数の順番を数えるのがお嫌い?キーワード引数をどうぞ。 -"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" - -# もし Python 3 のコードを Python 2.5以下でも使う必要があるなら、 -# 旧式のフォーマット方法を使うこともできます。 -"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" - -# Python3.6以上では、f-stringsやフォーマット文字列を使ってフォーマットすることもできます。 -name = "Reiko" -f"She said her name is {name}." # => "She said her name is Reiko" - -# 基本的に、任意のPythonの文を中括弧に書くことができ、それは評価されて出力されます。 -f"{name} is {len(name)} characters long." - -# None はオブジェクトです(大文字からです!) -None # => None - -# オブジェクトがNoneであるか確認するのに "==" 演算子を使わないように。 -# 代わりに "is" を使いましょう。オブジェクトの素性を確認できます。 -"etc" is None # => False -None is None # => True - -# None や 0 、空の 文字列/リスト/辞書/タプル は全て False として評価されます。 -# 他の全ての値は True になります。 -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False - -#################################################### -# 2. Variables and Collections -#################################################### - -# Python にはprint関数があります。 -print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! - -# 標準では、print関数は最後に改行を出力します。 -# この動作を変更するためには、オプション引数を利用します。 -print("Hello, World", end="!") # => Hello, World! - -# コンソールから入力を得るための簡単な例 -input_string_var = input("Enter some data: ") # 入力を文字列として返します -# Note: Python の初期のバージョンでは、 input() は raw_input() という名前で存在します。 - -# Pythonでは変数の宣言は存在せず、代入のみです。 -# 慣例的に、小文字でアンダースコア区切り ( lower_case_with_underscores ) の変数が使われます。 -some_var = 5 -some_var # => 5 - -# 代入されていない変数へのアクセスは例外を引き起こします。 -# 例外の取り扱いについては、3章の制御の流れをご確認ください。 -some_unknown_var # NameError を送出します - -# ifは式として使用できます。 -# C言語の「?:(三項演算子)」に対応する例: -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# リストは順序を保存します。 -li = [] -# 値の入っているリストも作成できます。 -other_li = [4, 5, 6] - -# append により、リストの末尾にものを入れられます。 -li.append(1) # li is now [1] -li.append(2) # li is now [1, 2] -li.append(4) # li is now [1, 2, 4] -li.append(3) # li is now [1, 2, 4, 3] -# pop でリストの末尾から取り除けます。 -li.pop() # => 3 and li is now [1, 2, 4] -# 元に戻しましょう! -li.append(3) # li is now [1, 2, 4, 3] again. - -# 配列のように、リストにアクセスできます。 -li[0] # => 1 -# 最後の要素を参照できます。 -li[-1] # => 3 - -# 範囲外の要素を参照すると IndexError になります。 -li[4] # IndexError が発生します - -# スライス構文により範囲を参照できます。 -# 開始部分のインデックスに対応する部分は含まれますが、終了部分のインデックスに対応する部分は含まれません。 -li[1:3] # => [2, 4] -# 先端を取り除いたリスト -li[2:] # => [4, 3] -# 末尾を取り除いたリスト -li[:3] # => [1, 2, 4] -# 1つ飛ばしで選択する -li[::2] # =>[1, 4] -# 反転したリストを得る -li[::-1] # => [3, 4, 2, 1] -# これらの任意の組み合わせにより、より複雑なスライスを作ることができます。 -# li[start:end:step] - -# スライスにより、深いコピーを1階層分行うことができます。 -li2 = li[:] # => li2 = [1, 2, 4, 3] だが、 (li2 is li) はFalseになる。 - -# "del"によりリストから任意の要素を削除できます。 -del li[2] # li は [1, 2, 3] になりました。 - -# "remove"で最初に出現する要素を削除できます。 -li.remove(2) # li は [1, 3] になりました。 -li.remove(2) # 2はリストの中に存在しないので、 ValueError が発生します。 - -# 要素を好きなところに挿入できます。 -li.insert(1, 2) # li は [1, 2, 3] に戻りました。 - -# "index"で引数の要素が最初に出現する場所のインデックスを得られます。 -li.index(2) # => 1 -li.index(4) # 4はリストの中に存在しないので、 ValueError が発生します。 - -# リスト同士を足すこともできます。 -# Note: li と other_li の値は変更されません。 -li + other_li # => [1, 2, 3, 4, 5, 6] - -# "extend()"で他のリストを連結することができます。 -li.extend(other_li) # li は [1, 2, 3, 4, 5, 6] になります。 - -# リストの中に値が存在するか、 "in" で確認できます。 -1 in li # => True - -# 長さは "len()" で確認できます。 -len(li) # => 6 - - -# タプルはリストのようなものですが、不変であるという違いがあります。 -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # 内容を変更しようとすると TypeError が発生します。 - -# 長さが1のタプルを作成するには、要素の後にカンマを付ける必要があります。 -# しかし、それ以外の長さなら、例え長さが0でもそのようにする必要はありません。 -type((1)) # => -type((1,)) # => -type(()) # => - -# 大抵のリスト操作はタプルでも行うことができます。 -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# タプルやリストから複数の変数に代入することができます。 -a, b, c = (1, 2, 3) # a, b, c にはそれぞれ 1, 2, 3 が代入されました。 -# 拡張記法もあります。 -a, *b, c = (1, 2, 3, 4) # a は 1 、 b は [2, 3] 、c は4 になります。 -# 括弧を作成しなくてもデフォルトでタプルが作成されます。 -d, e, f = 4, 5, 6 # 4、5、6がそれぞれd、 e、 fに代入されます。 -# 2つの変数を交換するのがどれほど簡単か見てみましょう。 -e, d = d, e # d は 5 、 e は e になります。 - - -# 辞書はマップ(キーと値の組み合わせ)を保存できます。 -empty_dict = {} -# 値が入っている辞書を直接作成することもできます。 -filled_dict = {"one": 1, "two": 2, "three": 3} - -# キーは不変の型である必要があります。 -# これは、高速化のため、キーを定数のハッシュ値に変換できるようにするためです。 -# 不変の型の例として、int、float、string、tupleなどが上げられます。 -invalid_dict = {[1, 2, 3]: "123"} # => list はハッシュ化できないので、 TypeError が発生します。 -valid_dict = {(1, 2, 3): [1, 2, 3]} # 一方、キーに対応する値はどのような型でも利用できます。 - -# [] で 値を取り出せます。 -filled_dict["one"] # => 1 - -# "keys()"により、全てのキーを反復可能な形式で取り出せます。 -# これをリストにするために、"list()"で囲んでいます。これについては後程解説します。 -# Note: Python3.7未満では、辞書のキーの順番は考慮されていません。実行した結果がこれと異なる場合があります。 -# しかし、Python3.7以降ではキーの挿入順を保つようになりました。 -list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7 -list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+ - - -# "values()"により、全ての値を反復可能な形式で取り出せます。 -# 前と同じように、これをリストにするために、"list()"で囲んでいます。 -# Note: 辞書の値の順番は考慮されていません。実行した結果がこれと異なる場合があります。 -list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 -list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ - -# "in" により、辞書のキーが存在するか確認できます。 -"one" in filled_dict # => True -1 in filled_dict # => False - -# 存在しないキーで辞書を参照すると KeyError になります。 -filled_dict["four"] # KeyError - -# "get()" メソッドを使うことで KeyError を回避できます。 -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# get ではキーが存在しなかったときのデフォルト値を指定できます。 -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# "setdefault()" で、キーが存在しなかった場合のみ、値を設定できます。 -filled_dict.setdefault("five", 5) # filled_dict["five"] は 5 になりました。 -filled_dict.setdefault("five", 6) # filled_dict["five"] は 5 のままです。 - -# 辞書にマップを追加する -filled_dict.update({"four": 4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -filled_dict["four"] = 4 # 辞書に追加する別の方法 - -# del により辞書からキーを削除できます。 -del filled_dict["one"] # "one" キーを辞書から削除します。 - -# Python 3.5 以降では、追加の値を取り出す方法があります。 -{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} -{'a': 1, **{'a': 2}} # => {'a': 2} - - -# set では集合を表現できます。 -empty_set = set() -# 集合を一連の値で初期化する例です。辞書に似ていますね?ごめんなさい。 -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} - -# 辞書のキーのように、集合の値は不変である必要があります。 -invalid_set = {[1], 1} # => list はハッシュ化できないので、 TypeError が送出されます。 -valid_set = {(1,), 1} - -# 集合に新しい要素を追加できます。 -filled_set = some_set -filled_set.add(5) # filled_set は {1, 2, 3, 4, 5} になりました。 -# 集合は重複した要素を持ちません。 -filled_set.add(5) # 以前の{1, 2, 3, 4, 5}のままです。 - -# & により、集合同士の共通部分が得られます。 -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# | により、集合同士の合併が得られます。 -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# - により、集合同士の差集合が得られます。 -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# ^ により、集合同士の対象差が得られます。 -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# 左の集合が右の集合の上位集合であるか確認。 -{1, 2} >= {1, 2, 3} # => False - -# 左の集合が右の集合の部分集合であるか確認。 -{1, 2} <= {1, 2, 3} # => True - -# in により値が集合の中に存在するか確認できます。 -2 in filled_set # => True -10 in filled_set # => False - - -#################################################### -# 3. 制御の流れとiterable -#################################################### - -# まずは変数を作りましょう。 -some_var = 5 - -# これはif文です。Pythonではインデントが特徴的ですね! -# 規約ではタブではなく4つのスペースでインデントすることが推奨されています。 -# 以下の例では"some_var is smaller than 10"と出力されます。 -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # この elif 節はオプションです。 - print("some_var is smaller than 10.") -else: # この else 節もオプションです。 - print("some_var is indeed 10.") - - -""" -for ループはリストの要素を反復することができます。 -出力: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # format() を使って文字列に変数を挿入して出力できます。 - print("{} is a mammal".format(animal)) - -""" -"range(数値)" は、ゼロから与えられた数値までのiterableを返します。 -出力: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(lower, upper)" は、 lower の数値から upper の数値までのiterableを返します。 -upper の数値は含まれません。 -出力: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(lower, upper, step)" は、lower の数値から upper の数値までが、 -step 刻みで表現されるiterableを返します -step が与えられない場合、デフォルトは1になります。 -出力: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) -""" - -while によるループは条件が成立しなくなるまで実行されます。 -出力: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # x = x + 1 の省略記法 - -# try/except ブロックにより、例外を扱う -try: - # "raise" により例外を発生させます。 - raise IndexError("This is an index error") -except IndexError as e: - pass # pass は、何もしないという命令(no-op)に相当します。普通、ここで例外に対処します。 -except (TypeError, NameError): - pass # もし必要なら、複数の種類の例外を一緒に処理できます。 -else: # try/except ブロックへのオプションの節。他の全てのexceptブロックより後に置かなければなりません。 - print("All good!") # tryで例外が発生しなかった場合のみ実行されます。 -finally: # 例外が発生したか、しなかったか、どのような例外だったかに関らず実行されます。 - print("We can clean up resources here") - -# try/finallyでリソースの始末をする代わりに、 with 文を使うこともできます。 -with open("myfile.txt") as f: - for line in f: - print(line) - -# Pythonは、iterableと呼ばれる基本的な抽象化が提供しています。 -# iterableは、シーケンスとして取り扱えるオブジェクトです。 -# range関数で返されるオブジェクトもiterableの一種です。 -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']). これはiterableインタフェースを実装するオブジェクトです。 - -# iterableでループを行うことができます。 -for i in our_iterable: - print(i) # Prints one, two, three - -# しかし、インデックスで要素を参照することはできません。 -our_iterable[1] # TypeError が発生します。 - -# iterableは、iteratorの作り方がわかるオブジェクトです。 -our_iterator = iter(our_iterable) - -# iterator は、要素を取り出したときの状態を覚えるオブジェクトです。 -# "next()"により次の要素を取り出せます。 -next(our_iterator) # => "one" - -# 反復(iterate)する度に、状態を更新します。 -next(our_iterator) # => "two" -next(our_iterator) # => "three" - -# iteratorが自身の持つ全てのデータを返したあとは、 StopIteration 例外を発生させます。 -next(our_iterator) # StopIteration が発生します。 - -# "list()"を呼ぶことにより、iteratorの全ての要素を得られます。 -list(filled_dict.keys()) # => ["one", "two", "three"] - - -#################################################### -# 4. 関数 -#################################################### - -# 新しい関数を作成するには "def" を使います。 -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # return 文で値を返します。 - -# 引数付きで関数を呼んでみましょう。 -add(5, 6) # => "x is 5 and y is 6" と出力し、 11 を返します。 - -# キーワード引数で関数を呼ぶこともできます。 -add(y=6, x=5) # キーワード引数を使うと任意の順番で引数を指定できます。 - - -# 可変数の位置引数を持つ関数を定義できます。 -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - - -# 可変数のキーワード引数を持つ関数を定義できます。 -def keyword_args(**kwargs): - return kwargs - -# 何が起こるか、試してみましょう -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# お望みなら、両方一気にやることもできます。 -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) prints: - (1, 2) - {"a": 3, "b": 4} -""" - -# 関数を呼ぶとき、 args/kwargs の逆のことをすることができます! -# * を使ってタプルを展開したり、 ** を使って辞書を展開できます。 -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # all_the_args(1, 2, 3, 4) と等しいです。 -all_the_args(**kwargs) # all_the_args(a=3, b=4) と等しいです。 -all_the_args(*args, **kwargs) # all_the_args(1, 2, 3, 4, a=3, b=4) と等しいです。 - - -# タプルで複数の値を返す -def swap(x, y): # 括弧を使わずに、複数の値をタプルとして返すことができます。 - return y, x # (Note: 括弧は使わなくてもいいですが、使うこともできます。) - - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # このように、括弧は使っても使わなくてもいいです。 - - -# 関数のスコープ -x = 5 - - -def set_x(num): - # ローカル変数の x はグローバル変数の x とは異なります - x = num # => 43 - print(x) # => 43 - - -def set_global_x(num): - global x - print(x) # => 5 - x = num # グローバル変数の x に 6 が代入されました。 - print(x) # => 6 - -set_x(43) -set_global_x(6) - - -# Pythonは第一級関数をサポートします。 -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# 無名関数もサポートしています。 -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# 高階関数も組込まれています。 -list(map(add_10, [1, 2, 3])) # => [11, 12, 13] -list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] - -list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] - -# map や filter の代わりに、リスト内包表記を使うことができます。 -# リスト内包表記は、出力を別のリスト内包表記にネストさせることができます。 -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# 集合(set)や辞書も内包表記ができます。 -{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} -{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -# 5. モジュール -#################################################### - -# Pythonではモジュールをインポートできます。 -import math -print(math.sqrt(16)) # => 4.0 - -# モジュールの中から特定の関数をインポートすることもできます。 -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# 全部の関数をモジュールからインポートすることができます。 -# Warning: この方法は推奨されません。 -from math import * - -# 短い名前でモジュールをインポートすることができます。 -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Pythonのモジュールは実際には単なるPythonのファイルです。 -# 自分で書くことも、インポートすることもできます。 -# ファイル名がそのままモジュール名になります。 - -# モジュールで定義されている関数と属性を調べることができます。 -import math -dir(math) - -# もし、現在書いているスクリプトと同じフォルダに「math.py」という -# Pythonのスクリプトが存在する場合、そのmath.pyが -# 組み込みのPythonモジュールの代わりに読み込まれるでしょう。 -# これは、ローカルのフォルダはPythonの組み込みライブラリよりも -# 優先度が高いため発生するのです。 - - -#################################################### -# 6. クラス -#################################################### - -# クラスを作成するために、class文を使います。 -class Human: - - # クラスの属性です。このクラスの全てのインスタンスで共有されます。 - species = "H. sapiens" - - # 標準的なイニシャライザで、このクラスがインスタンスを作成するときは毎回呼ばれます。 - # 2つのアンダースコアがオブジェクトや属性の前後についているとき、これらはPythonによって利用され、 - # ユーザーの名前空間には存在しないということに注意してください。 - # __init__ や __str__ 、 __repr__ のようなメソッド(やオブジェクト、属性)は、 - # special methods (または dunder methods)と呼ばれます。 - # 同じような名前を自分で発明しないほうがよいでしょう。 - def __init__(self, name): - # 引数をインスタンスのname属性に設定します。 - self.name = name - - # プロパティの初期化 - self._age = 0 - - # インスタンスメソッド。全てのメソッドは"self"を最初の引数に取ります。 - def say(self, msg): - print("{name}: {message}".format(name=self.name, message=msg)) - - # 別のインスタンスメソッドの例。 - def sing(self): - return 'yo... yo... microphone check... one two... one two...' - - # クラスメソッドは全てのインスタンスで共有されます。 - # クラスメソッドではクラスを最初の引数として呼ばれます。 - @classmethod - def get_species(cls): - return cls.species - - # スタティックメソッドはクラスやインスタンスを参照せずに呼ばれます。 - @staticmethod - def grunt(): - return "*grunt*" - - # プロパティはgetterのようなものです。 - # age() メソッドを同名の読取専用属性に変換します。 - # Pythonではわざわざgetterやsetterを書く必要はありません。 - @property - def age(self): - return self._age - - # プロパティを設定できるようにします。 - @age.setter - def age(self, age): - self._age = age - - # プロパティを削除できるようにします。 - @age.deleter - def age(self): - del self._age - - -# Pythonインタプリタがソースファイルを読み込んだとき、全てのコードを実行します。 -# この __name__ による確認により、このモジュールがメインのプログラムである場合にのみ、 -# このコードブロックが実行されるようにします。 -if __name__ == '__main__': - # クラスのインスタンスを作成します。 - i = Human(name="Ian") - i.say("hi") # "Ian: hi" - j = Human("Joel") - j.say("hello") # "Joel: hello" - # i と j はHumanのインスタンスです。別の言葉で言うなら、これらはHumanのオブジェクトです。 - - # クラスメソッドを呼んでみましょう。 - i.say(i.get_species()) # "Ian: H. sapiens" - # 共有属性を変更してみましょう。 - Human.species = "H. neanderthalensis" - i.say(i.get_species()) # => "Ian: H. neanderthalensis" - j.say(j.get_species()) # => "Joel: H. neanderthalensis" - - # スタティックメソッドを呼んでみましょう。 - print(Human.grunt()) # => "*grunt*" - - # スタティックメソッドはインスタンスから呼ぶことはできません。 - # なぜならば、 i.grunt() は自動的に"self" ( i オブジェクト ) を引数として渡してしまうからです。 - print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given - - # インスタンスのプロパティを更新してみましょう。 - i.age = 42 - # プロパティを取得してみましょう。 - i.say(i.age) # => "Ian: 42" - j.say(j.age) # => "Joel: 0" - # プロパティを削除してみましょう。 - del i.age - # i.age # => AttributeError が発生します。 - - -#################################################### -# 6.1 継承 -#################################################### -# 継承を行うことで、親クラスからメソッドと変数を継承する新しい子クラスを定義できます。 - -# 上記で定義されたHumanクラスを親クラス(基底クラス)として使い、Superheroという子クラスを定義します。 -# これは"species"、"name"や"age"といった変数や、"sing"や"grunt"のようなメソッドをHumanから継承しますが、 -# Superhero独自のプロパティを持つこともできます。 - -# ファイルを分割してモジュール化の利点を活用するために、上記のHumanクラスを独自のファイル、ここでは human.py に記述ましょう。 - -# 別のファイルから関数をインポートするには次の形式を利用してください: -# from "拡張子なしのファイル名" import "関数やクラス" - -from human import Human - - -# 親クラスを子クラスのパラメータとして指定します -class Superhero(Human): - - # もし子クラスが親クラスの全ての定義を変更なしで継承する場合、"pass"キーワードのみを書くだけで良いです。 - # しかし、今回は親クラスとは異なる子クラスを作成するので、今回は以下の通りコメントアウトしています。 - # pass - - # 子クラスは親クラスの属性を上書きできます。 - species = 'Superhuman' - - # 子クラスは親クラスのコンストラクタを引数含めて自動的に継承しますが、 - # 追加の引数や定義を行ってコンストラクタのようなメソッドを上書きすることもできます。 - # このコンストラクタは"name"引数を"Human"クラスから継承し、"superpower"と"movie"という引数を追加します。 - def __init__(self, name, movie=False, - superpowers=["super strength", "bulletproofing"]): - - # 追加のクラス属性を作成する - self.fictional = True - self.movie = movie - # デフォルト値は共有されるので、可変のデフォルト値には注意してください。 - self.superpowers = superpowers - - # "super"関数を使うと子クラスに上書きされた親クラスのメソッド(今回は "__init__")にアクセスできます。 - # これで、親クラスのコンストラクタを呼んでいます。 - super().__init__(name) - - # singメソッドを上書きし、 - def sing(self): - return 'Dun, dun, DUN!' - - # 追加のインスタンスメソッドを作成します。 - def boast(self): - for power in self.superpowers: - print("I wield the power of {pow}!".format(pow=power)) - - -if __name__ == '__main__': - sup = Superhero(name="Tick") - - # インスタンスの型を調べる - if isinstance(sup, Human): - print('I am human') - if type(sup) is Superhero: - print('I am a superhero') - - # getattr()とsuper()で使われるメソッドの解決順序を調べてみます。 - # この属性は動的であり、変更可能です。 - print(Superhero.__mro__) # => (, - # => , ) - - # 親のメソッドを呼びだすものの、独自のクラス属性を参照します。 - print(sup.get_species()) # => Superhuman - - # 上書きされたメソッドを呼ぶ - print(sup.sing()) # => Dun, dun, DUN! - - # Humanのメソッドを呼ぶ - sup.say('Spoon') # => Tick: Spoon - - # Superhero限定のメソッドを呼ぶ - sup.boast() # => I wield the power of super strength! - # => I wield the power of bulletproofing! - - # 継承されたクラス属性 - sup.age = 31 - print(sup.age) # => 31 - - # Superhero限定の属性 - print('Am I Oscar eligible? ' + str(sup.movie)) - - - -#################################################### -# 6.2 多重継承 -#################################################### - -# 別のクラスを定義します。 -# bat.py -class Bat: - - species = 'Baty' - - def __init__(self, can_fly=True): - self.fly = can_fly - - # このクラスも say メソッドを持ちます。 - def say(self, msg): - msg = '... ... ...' - return msg - - # 同様に、独自のメソッドも与えましょう。 - def sonar(self): - return '))) ... (((' - -if __name__ == '__main__': - b = Bat() - print(b.say('hello')) - print(b.fly) - -# superhero.py -from superhero import Superhero -from bat import Bat - -# BatmanをSuperheroとBatの両方を継承した子クラスとして定義します。 -class Batman(Superhero, Bat): - - def __init__(self, *args, **kwargs): - # 通常、属性を継承するにはsuper()を呼び出します。 - # super(Batman, self).__init__(*args, **kwargs) - # しかし、ここでは多重継承を行っているので、 super() はMRO(メソッド解決順序)の次の基本クラスにのみ動作します。 - # なので、全ての祖先に対して明示的に __init__ を呼ぶことにします。 - # *args と **kwargs を使うことで、それぞれの継承元が - # たまねぎの皮を剥がすごとく、引数を用いることができます。 - Superhero.__init__(self, 'anonymous', movie=True, - superpowers=['Wealthy'], *args, **kwargs) - Bat.__init__(self, *args, can_fly=False, **kwargs) - # 名前の属性の値を上書きします。 - self.name = 'Sad Affleck' - - def sing(self): - return 'nan nan nan nan nan batman!' - - -if __name__ == '__main__': - sup = Batman() - - # getattr() や super() の両方で使われるMROを取得します。 - # この属性は動的であり、更新が可能です。 - print(Batman.__mro__) # => (, - # => , - # => , - # => , ) - - - # 親メソッドを呼び出しますが、独自のクラス属性を参照します。 - print(sup.get_species()) # => Superhuman - - # 上書きされたメソッドを呼び出します。 - print(sup.sing()) # => nan nan nan nan nan batman! - - # 継承順により、Humanから継承されたメソッドを呼び出します。 - sup.say('I agree') # => Sad Affleck: I agree - - # 2番目の先祖にのみ存在するメソッドを呼び出してみます。 - print(sup.sonar()) # => ))) ... ((( - - # 継承されたクラス属性 - sup.age = 100 - print(sup.age) # => 100 - - # デフォルト値が上書きされて、2番目の先祖から継承された属性 - print('Can I fly? ' + str(sup.fly)) # => Can I fly? False - - -#################################################### -# 7. 発展的内容 -#################################################### - -# ジェネレータは遅延をするコードの作成に役立ちます。 -def double_numbers(iterable): - for i in iterable: - yield i + i - -# 次の値を処理するのに必要なデータしか読み込まないので、ジェネレータはメモリをあまり消費しません。 -# この性質により、他の方法では非常に多くのメモリを消費するような操作が可能になります。 -for i in double_numbers(range(1, 900000000)): # `range` もジェネレータの1つです。 - print(i) - if i >= 30: - break - -# リスト内包表記のように、ジェネータ内包表記を作成することもできます。 -values = (-x for x in [1, 2, 3, 4, 5]) -for x in values: - print(x) # prints -1 -2 -3 -4 -5 - -# ジェネレータ内包表記から直接リストを作成することもできます。 -values = (-x for x in [1, 2, 3, 4, 5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - -# デコレータ -# この例では`beg` が `say` を `wraps`します。 -# もし say_please が True なら、出力が変更されます。 -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( -``` - -## Ready For More? - -### Free Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) -* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) -* [Dive Into Python 3](http://www.diveintopython3.net/index.html) -* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/pt-br/python-pt.html.markdown b/pt-br/python-pt.html.markdown new file mode 100644 index 00000000..bc5f801c --- /dev/null +++ b/pt-br/python-pt.html.markdown @@ -0,0 +1,746 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] +translators: + - ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"] + - ["Monique Baptista", "https://github.com/bfmonique"] +lang: pt-br +filename: learnpython3-pt.py +--- + +Python foi criada por Guido Van Rossum nos anos 1990. Ela é atualmente uma +das linguagens mais populares existentes. Eu me apaixonei por +Python por sua clareza sintática. É praticamente pseudocódigo executável. + +Opniões são muito bem vindas. Você pode encontrar-me em +[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [em] +[serviço de e-mail do google]. + +Observação: Este artigo trata de Python 3 especificamente. Verifique +[aqui](http://learnxinyminutes.com/docs/pt-br/python-pt/) se você pretende +aprender o velho Python 2.7. + +```python + +# Comentários em uma única linha começam com uma cerquilha (também conhecido por sustenido). + +""" Strings de várias linhas podem ser escritas + usando três ", e são comumente usadas + como comentários. +""" + +#################################################### +## 1. Tipos de dados primitivos e operadores +#################################################### + +# Você usa números normalmente +3 # => 3 + +# Matemática é como você espera que seja +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Números são inteiros por padrão, exceto na divisão, que retorna número +# de ponto flutuante (float). +35 / 5 # => 7.0 + +# O resultado da divisão inteira arredonda para baixo tanto para números +# positivos como para negativos. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # funciona em float também +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Quando você usa um float, o resultado é float. +3 * 2.0 # => 6.0 + +# operador módulo +7 % 3 # => 1 + +# Exponenciação (x**y, x elevado à potência y) +2**4 # => 16 + +# Determine a precedência usando parênteses +(1 + 3) * 2 # => 8 + +# Valores lógicos são primitivos (Atenção à primeira letra maiúscula) +True +False + +# negação lógica com not +not True # => False +not False # => True + +# Operadores lógicos +# Observe que "and" e "or" são sensíveis a maiúsculas e minúsculas +True and False # => False +False or True # => True + +# Observe a utilização de operadores lógicos com números inteiros +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Igualdade é == +1 == 1 # => True +2 == 1 # => False + +# Diferença é != +1 != 1 # => False +2 != 1 # => True + +# Mais comparações +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Comparações podem ser agrupadas +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# 'is' verifica se duas variáveis representam o mesmo endereço +# na memória; '==' verifica se duas variáveis têm o mesmo valor +a = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] +b = a # b referencia o que está referenciado por a +b is a # => True, a e b referenciam o mesmo objeto +b == a # => True, objetos a e b tem o mesmo conteúdo +b = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] +b is a # => False, a e b não referenciam o mesmo objeto +b == a # => True, objetos a e b tem o mesmo conteúdo + +# Strings são criadas com " ou ' +"Isto é uma string." +'Isto também é uma string.' + +# Strings também podem ser somadas! Mas tente não fazer isso. +"Olá " + "mundo!" # => "Olá mundo!" +# Strings podem ser somadas sem usar o '+' +"Olá " "mundo!" # => "Olá mundo!" + +# Uma string pode ser manipulada como se fosse uma lista de caracteres +"Isso é uma string"[0] # => 'I' + +# .format pode ser usado para formatar strings, dessa forma: +"{} podem ser {}".format("Strings", "interpoladas") # => "Strings podem ser interpoladas" + +# Você pode repetir os argumentos para digitar menos. +"Seja ágil {0}, seja rápido {0}, salte sobre o {1} {0}".format("Jack", "castiçal") +# => "Seja ágil Jack, seja rápido Jack, salte sobre o castiçal Jack." + +# Você pode usar palavras-chave se quiser contar. +"{nome} quer comer {comida}".format(nome="Beto", comida="lasanha") # => "Beto quer comer lasanha" + +# Se você precisa executar seu código Python3 com um interpretador Python 2.5 ou acima, você pode usar a velha forma para formatação de texto: +"%s podem ser %s da forma %s" % ("Strings", "interpoladas", "antiga") # => "Strings podem ser interpoladas da forma antiga" + + +# None é um objeto +None # => None + +# Não use o operador de igualdade "==" para comparar objetos com None +# Use "is" para isso. Ele checará pela identidade dos objetos. +"etc" is None # => False +None is None # => True + +# None, 0, e strings/listas/dicionários vazios todos retornam False. +# Qualquer outra coisa retorna True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False + + +#################################################### +## 2. Variáveis e coleções +#################################################### + +# Python tem uma função print +print("Eu sou o Python. Prazer em conhecer!") # => Eu sou o Python. Prazer em conhecer! + +# Por padrão a função print também imprime o caractere de nova linha ao final. +# Use o argumento opcional end para mudar o caractere final. +print("Olá, Mundo", end="!") # => Olá, Mundo! + +# Forma simples para capturar dados de entrada via console +input_string_var = input("Digite alguma coisa: ") # Retorna o que foi digitado em uma string +# Observação: Em versões antigas do Python, o método input() era chamado raw_input() + +# Não é necessário declarar variáveis antes de iniciá-las +# É uma convenção usar letras_minúsculas_com_sublinhados +alguma_variavel = 5 +alguma_variavel # => 5 + +# Acessar uma variável que não tenha sido inicializada gera uma exceção. +# Veja Controle de Fluxo para aprender mais sobre tratamento de exceções. +alguma_variavel_nao_inicializada # Gera a exceção NameError + +# Listas armazenam sequências +li = [] +# Você pode iniciar uma lista com valores +outra_li = [4, 5, 6] + +# Adicione conteúdo ao fim da lista com append +li.append(1) # li agora é [1] +li.append(2) # li agora é [1, 2] +li.append(4) # li agora é [1, 2, 4] +li.append(3) # li agora é [1, 2, 4, 3] +# Remova do final da lista com pop +li.pop() # => 3 e agora li é [1, 2, 4] +# Vamos colocá-lo lá novamente! +li.append(3) # li agora é [1, 2, 4, 3] novamente. + +# Acesse uma lista da mesma forma que você faz com um array +li[0] # => 1 +# Acessando o último elemento +li[-1] # => 3 + +# Acessar além dos limites gera um IndexError +li[4] # Gera o IndexError + +# Você pode acessar vários elementos com a sintaxe de limites +# Inclusivo para o primeiro termo, exclusivo para o segundo +li[1:3] # => [2, 4] +# Omitindo o final +li[2:] # => [4, 3] +# Omitindo o início +li[:3] # => [1, 2, 4] +# Selecione cada segunda entrada +li[::2] # => [1, 4] +# Tenha uma cópia em ordem invertida da lista +li[::-1] # => [3, 4, 2, 1] +# Use qualquer combinação dessas para indicar limites complexos +# li[inicio:fim:passo] + +# Faça uma cópia profunda de um nível usando limites +li2 = li[:] # => li2 = [1, 2, 4, 3] mas (li2 is li) resultará em False. + +# Apague elementos específicos da lista com "del" +del li[2] # li agora é [1, 2, 3] + +# Você pode somar listas +# Observação: valores em li e other_li não são modificados. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concatene listas com "extend()" +li.extend(other_li) # Agora li é [1, 2, 3, 4, 5, 6] + +# Verifique se algo existe na lista com "in" +1 in li # => True + +# Examine tamanho com "len()" +len(li) # => 6 + + +# Tuplas são como l istas, mas imutáveis. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Gera um TypeError + +# Observe que uma tupla de tamanho um precisa ter uma vírgula depois do +# último elemento mas tuplas de outros tamanhos, mesmo vazias, não precisa,. +type((1)) # => +type((1,)) # => +type(()) # => + +# Você pode realizar com tuplas a maior parte das operações que faz com listas +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Você pode desmembrar tuplas (ou listas) em variáveis. +a, b, c = (1, 2, 3) # a é 1, b é 2 e c é 3 +# Por padrão, tuplas são criadas se você não coloca parêntesis. +d, e, f = 4, 5, 6 +# Veja como é fácil permutar dois valores +e, d = d, e # d é 5, e é 4 + +# Dicionários armazenam mapeamentos +empty_dict = {} +# Aqui está um dicionário preenchido na definição da referência +filled_dict = {"um": 1, "dois": 2, "três": 3} + +# Observe que chaves para dicionários devem ser tipos imutáveis. Isto é para +# assegurar que a chave pode ser convertida para uma valor hash constante para +# buscas rápidas. +# Tipos imutáveis incluem inteiros, flotas, strings e tuplas. +invalid_dict = {[1,2,3]: "123"} # => Gera um TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Já os valores, podem ser de qualquer tipo. + +# Acesse valores com [] +filled_dict["um"] # => 1 + +# Acesse todas as chaves como um iterável com "keys()". É necessário encapsular +# a chamada com um list() para transformá-las em uma lista. Falaremos sobre isso +# mais adiante. Observe que a ordem de uma chave de dicionário não é garantida. +# Por isso, os resultados aqui apresentados podem não ser exatamente como os +# aqui apresentados. +list(filled_dict.keys()) # => ["três", "dois", "um"] + + +# Acesse todos os valores de um iterável com "values()". Novamente, é +# necessário encapsular ele com list() para não termos um iterável, e sim os +# valores. Observe que, como foi dito acima, a ordem dos elementos não é +# garantida. +list(filled_dict.values()) # => [3, 2, 1] + + +# Verifique a existência de chaves em um dicionário com "in" +"um" in filled_dict # => True +1 in filled_dict # => False + +# Acessar uma chave inexistente gera um KeyError +filled_dict["quatro"] # KeyError + +# Use o método "get()" para evitar um KeyError +filled_dict.get("um") # => 1 +filled_dict.get("quatro") # => None +# O método get permite um parâmetro padrão para quando não existir a chave +filled_dict.get("um", 4) # => 1 +filled_dict.get("quatro", 4) # => 4 + +# "setdefault()" insere em dicionário apenas se a dada chave não existir +filled_dict.setdefault("cinco", 5) # filled_dict["cinco"] tem valor 5 +filled_dict.setdefault("cinco", 6) # filled_dict["cinco"] continua 5 + +# Inserindo em um dicionário +filled_dict.update({"quatro":4}) # => {"um": 1, "dois": 2, "três": 3, "quatro": 4} +#filled_dict["quatro"] = 4 #outra forma de inserir em um dicionário + +# Remova chaves de um dicionário com del +del filled_dict["um"] # Remove a chave "um" de filled_dict + + +# Armazenamento em sets... bem, são conjuntos +empty_set = set() +# Inicializa um set com alguns valores. Sim, ele parece um dicionário. Desculpe. +some_set = {1, 1, 2, 2, 3, 4} # some_set agora é {1, 2, 3, 4} + +# Da mesma forma que chaves em um dicionário, elementos de um set devem ser +# imutáveis. +invalid_set = {[1], 1} # => Gera um TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Pode definir novas variáveis para um conjunto +filled_set = some_set + +# Inclua mais um item no set +filled_set.add(5) # filled_set agora é {1, 2, 3, 4, 5} + +# Faça interseção de conjuntos com & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Faça união de conjuntos com | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Faça a diferença entre conjuntos com - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Verifique a existência em um conjunto com in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Controle de fluxo e iteráveis +#################################################### + +# Iniciemos um variável +some_var = 5 + +# Aqui está uma expressão if. Indentação é significante em python! +# imprime "somevar é menor que10" +if some_var > 10: + print("some_var é absolutamente maior que 10.") +elif some_var < 10: # Esta cláusula elif é opcional. + print("some_var é menor que 10.") +else: # Isto também é opcional. + print("some_var é, de fato, 10.") + + +""" +Laços for iteram sobre listas +imprime: + cachorro é um mamífero + gato é um mamífero + rato é um mamífero +""" +for animal in ["cachorro", "gato", "rato"]: + # Você pode usar format() para interpolar strings formatadas + print("{} é um mamífero".format(animal)) + +""" +"range(número)" retorna um iterável de números +de zero até o número escolhido +imprime: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(menor, maior)" gera um iterável de números +começando pelo menor até o maior +imprime: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(menor, maior, passo)" retorna um iterável de números +começando pelo menor número até o maior númeno, pulando de +passo em passo. Se o passo não for indicado, o valor padrão é um. +imprime: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +Laços while executam até que a condição não seja mais válida. +imprime: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Maneira mais curta para for x = x + 1 + +# Lide com exceções com um bloco try/except +try: + # Use "raise" para gerar um erro + raise IndexError("Isto é um erro de índice") +except IndexError as e: + pass # Pass é um não-operador. Normalmente você usa algum código de recuperação aqui. +except (TypeError, NameError): + pass # Varias exceções podem ser gerenciadas, se necessário. +else: # Cláusula opcional para o bloco try/except. Deve estar após todos os blocos de exceção. + print("Tudo certo!") # Executa apenas se o código em try não gera exceção +finally: # Sempre é executado + print("Nós podemos fazer o código de limpeza aqui.") + +# Ao invés de try/finally para limpeza você pode usar a cláusula with +with open("myfile.txt") as f: + for line in f: + print(line) + +# Python provê uma abstração fundamental chamada Iterável. +# Um iterável é um objeto que pode ser tratado como uma sequência. +# O objeto retornou a função range, um iterável. + +filled_dict = {"um": 1, "dois": 2, "três": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => range(1,10). Esse é um objeto que implementa nossa interface iterável. + +# Nós podemos percorrê-la. +for i in our_iterable: + print(i) # Imprime um, dois, três + +# Mas não podemos acessar os elementos pelo seu índice. +our_iterable[1] # Gera um TypeError + +# Um iterável é um objeto que sabe como criar um iterador. +our_iterator = iter(our_iterable) + +# Nosso iterador é um objeto que pode lembrar o estado enquanto nós o percorremos. +# Nós acessamos o próximo objeto com "next()". +next(our_iterator) # => "um" + +# Ele mantém o estado enquanto nós o percorremos. +next(our_iterator) # => "dois" +next(our_iterator) # => "três" + +# Após o iterador retornar todos os seus dados, ele gera a exceção StopIterator +next(our_iterator) # Gera StopIteration + +# Você pode capturar todos os elementos de um iterador aplicando list() nele. +list(filled_dict.keys()) # => Retorna ["um", "dois", "três"] + + +#################################################### +## 4. Funções +#################################################### + +# Use "def" para criar novas funções. +def add(x, y): + print("x é {} e y é {}".format(x, y)) + return x + y # Retorne valores com a cláusula return + +# Chamando funções com parâmetros +add(5, 6) # => imprime "x é 5 e y é 6" e retorna 11 + +# Outro meio de chamar funções é com argumentos nomeados +add(y=6, x=5) # Argumentos nomeados podem aparecer em qualquer ordem. + +# Você pode definir funções que pegam um número variável de argumentos +# posicionais +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Você pode definir funções que pegam um número variável de argumentos nomeados +# também +def keyword_args(**kwargs): + return kwargs + +# Vamos chamá-lo para ver o que acontece +keyword_args(peh="grande", lago="ness") # => {"peh": "grande", "lago": "ness"} + + +# Você pode fazer ambos simultaneamente, se você quiser +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) imprime: + (1, 2) + {"a": 3, "b": 4} +""" + +# Quando chamar funções, você pode fazer o oposto de args/kwargs! +# Use * para expandir tuplas e use ** para expandir dicionários! +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalente a foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalente a foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# Retornando múltiplos valores (com atribuição de tuplas) +def swap(x, y): + return y, x # Retorna múltiplos valores como uma tupla sem os parêntesis. + # (Observação: os parêntesis foram excluídos mas podem estar + # presentes) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Novamente, os parêntesis foram excluídos mas podem estar presentes. + +# Escopo de função +x = 5 + +def setX(num): + # A variável local x não é a mesma variável global x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # variável global x agora é 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python tem funções de primeira classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Também existem as funções anônimas +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# TODO - Fix for iterables +# Existem funções internas de alta ordem +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Nós podemos usar compreensão de lista para interessantes mapas e filtros +# Compreensão de lista armazena a saída como uma lista que pode ser uma lista +# aninhada +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Classes +#################################################### + + +# Nós usamos o operador "class" para ter uma classe +class Human: + + # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa + # classe. + species = "H. sapiens" + + # Construtor básico, é chamado quando esta classe é instanciada. + # Note que dois sublinhados no início e no final de uma identificados + # significa objetos ou atributos que são usados pelo python mas vivem em + # um namespace controlado pelo usuário. Métodos (ou objetos ou atributos) + # como: __init__, __str__, __repr__, etc. são chamados métodos mágicos (ou + # algumas vezes chamados métodos dunder - "double underscore") + # Você não deve usar nomes assim por sua vontade. + def __init__(self, name): + @ Atribui o argumento ao atributo da instância + self.name = name + + # Um método de instância. Todos os métodos tem "self" como primeiro + # argumento + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Um método de classe é compartilhado por todas as instâncias + # Eles são chamados com a classe requisitante como primeiro argumento + @classmethod + def get_species(cls): + return cls.species + + # Um método estático é chamado sem uma referência a classe ou instância + @staticmethod + def grunt(): + return "*grunt*" + + +# Instancie uma classe +i = Human(name="Ian") +print(i.say("oi")) # imprime "Ian: oi" + +j = Human("Joel") +print(j.say("olá")) # imprime "Joel: olá" + +# Chama nosso método de classe +i.get_species() # => "H. sapiens" + +# Altera um atributo compartilhado +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Chama o método estático +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Módulos +#################################################### + +# Você pode importar módulos +import math +print(math.sqrt(16)) # => 4.0 + +# Você pode importar apenas funções específicas de um módulo +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Você pode importar todas as funções de um módulo para o namespace atual +# Atenção: isso não é recomendado +from math import * + +# Você pode encurtar o nome dos módulos +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Módulos python são apenas arquivos python comuns. Você +# pode escrever os seus, e importá-los. O nome do +# módulo é o mesmo nome do arquivo. + +# Você pode procurar que atributos e funções definem um módulo. +import math +dir(math) + + +#################################################### +## 7. Avançado +#################################################### + +# Geradores podem ajudar você a escrever código "preguiçoso" +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Um gerador cria valores conforme necessário. +# Ao invés de gerar e retornar todos os valores de uma só vez ele cria um em +# cada interação. Isto significa que valores maiores que 15 não serão +# processados em double_numbers. +# Nós usamos um sublinhado ao final do nome das variáveis quando queremos usar +# um nome que normalmente colide com uma palavra reservada do python. +range_ = range(1, 900000000) +# Multiplica por 2 todos os números até encontrar um resultado >= 30 +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Decoradores +# Neste exemplo beg encapsula say +# beg irá chamar say. Se say_please é verdade então ele irá mudar a mensagem +# retornada +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Por favor! Eu sou pobre :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Você me paga uma cerveja?" + return msg, say_please + + +print(say()) # Você me paga uma cerveja? +print(say(say_please=True)) # Você me paga uma cerveja? Por favor! Eu sou pobre :( +``` + +## Pronto para mais? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/pt-br/python3-pt.html.markdown b/pt-br/python3-pt.html.markdown deleted file mode 100644 index bc5f801c..00000000 --- a/pt-br/python3-pt.html.markdown +++ /dev/null @@ -1,746 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] -translators: - - ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"] - - ["Monique Baptista", "https://github.com/bfmonique"] -lang: pt-br -filename: learnpython3-pt.py ---- - -Python foi criada por Guido Van Rossum nos anos 1990. Ela é atualmente uma -das linguagens mais populares existentes. Eu me apaixonei por -Python por sua clareza sintática. É praticamente pseudocódigo executável. - -Opniões são muito bem vindas. Você pode encontrar-me em -[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [em] -[serviço de e-mail do google]. - -Observação: Este artigo trata de Python 3 especificamente. Verifique -[aqui](http://learnxinyminutes.com/docs/pt-br/python-pt/) se você pretende -aprender o velho Python 2.7. - -```python - -# Comentários em uma única linha começam com uma cerquilha (também conhecido por sustenido). - -""" Strings de várias linhas podem ser escritas - usando três ", e são comumente usadas - como comentários. -""" - -#################################################### -## 1. Tipos de dados primitivos e operadores -#################################################### - -# Você usa números normalmente -3 # => 3 - -# Matemática é como você espera que seja -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 - -# Números são inteiros por padrão, exceto na divisão, que retorna número -# de ponto flutuante (float). -35 / 5 # => 7.0 - -# O resultado da divisão inteira arredonda para baixo tanto para números -# positivos como para negativos. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # funciona em float também --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Quando você usa um float, o resultado é float. -3 * 2.0 # => 6.0 - -# operador módulo -7 % 3 # => 1 - -# Exponenciação (x**y, x elevado à potência y) -2**4 # => 16 - -# Determine a precedência usando parênteses -(1 + 3) * 2 # => 8 - -# Valores lógicos são primitivos (Atenção à primeira letra maiúscula) -True -False - -# negação lógica com not -not True # => False -not False # => True - -# Operadores lógicos -# Observe que "and" e "or" são sensíveis a maiúsculas e minúsculas -True and False # => False -False or True # => True - -# Observe a utilização de operadores lógicos com números inteiros -0 and 2 # => 0 --5 or 0 # => -5 -0 == False # => True -2 == True # => False -1 == True # => True - -# Igualdade é == -1 == 1 # => True -2 == 1 # => False - -# Diferença é != -1 != 1 # => False -2 != 1 # => True - -# Mais comparações -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Comparações podem ser agrupadas -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# 'is' verifica se duas variáveis representam o mesmo endereço -# na memória; '==' verifica se duas variáveis têm o mesmo valor -a = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] -b = a # b referencia o que está referenciado por a -b is a # => True, a e b referenciam o mesmo objeto -b == a # => True, objetos a e b tem o mesmo conteúdo -b = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] -b is a # => False, a e b não referenciam o mesmo objeto -b == a # => True, objetos a e b tem o mesmo conteúdo - -# Strings são criadas com " ou ' -"Isto é uma string." -'Isto também é uma string.' - -# Strings também podem ser somadas! Mas tente não fazer isso. -"Olá " + "mundo!" # => "Olá mundo!" -# Strings podem ser somadas sem usar o '+' -"Olá " "mundo!" # => "Olá mundo!" - -# Uma string pode ser manipulada como se fosse uma lista de caracteres -"Isso é uma string"[0] # => 'I' - -# .format pode ser usado para formatar strings, dessa forma: -"{} podem ser {}".format("Strings", "interpoladas") # => "Strings podem ser interpoladas" - -# Você pode repetir os argumentos para digitar menos. -"Seja ágil {0}, seja rápido {0}, salte sobre o {1} {0}".format("Jack", "castiçal") -# => "Seja ágil Jack, seja rápido Jack, salte sobre o castiçal Jack." - -# Você pode usar palavras-chave se quiser contar. -"{nome} quer comer {comida}".format(nome="Beto", comida="lasanha") # => "Beto quer comer lasanha" - -# Se você precisa executar seu código Python3 com um interpretador Python 2.5 ou acima, você pode usar a velha forma para formatação de texto: -"%s podem ser %s da forma %s" % ("Strings", "interpoladas", "antiga") # => "Strings podem ser interpoladas da forma antiga" - - -# None é um objeto -None # => None - -# Não use o operador de igualdade "==" para comparar objetos com None -# Use "is" para isso. Ele checará pela identidade dos objetos. -"etc" is None # => False -None is None # => True - -# None, 0, e strings/listas/dicionários vazios todos retornam False. -# Qualquer outra coisa retorna True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False - - -#################################################### -## 2. Variáveis e coleções -#################################################### - -# Python tem uma função print -print("Eu sou o Python. Prazer em conhecer!") # => Eu sou o Python. Prazer em conhecer! - -# Por padrão a função print também imprime o caractere de nova linha ao final. -# Use o argumento opcional end para mudar o caractere final. -print("Olá, Mundo", end="!") # => Olá, Mundo! - -# Forma simples para capturar dados de entrada via console -input_string_var = input("Digite alguma coisa: ") # Retorna o que foi digitado em uma string -# Observação: Em versões antigas do Python, o método input() era chamado raw_input() - -# Não é necessário declarar variáveis antes de iniciá-las -# É uma convenção usar letras_minúsculas_com_sublinhados -alguma_variavel = 5 -alguma_variavel # => 5 - -# Acessar uma variável que não tenha sido inicializada gera uma exceção. -# Veja Controle de Fluxo para aprender mais sobre tratamento de exceções. -alguma_variavel_nao_inicializada # Gera a exceção NameError - -# Listas armazenam sequências -li = [] -# Você pode iniciar uma lista com valores -outra_li = [4, 5, 6] - -# Adicione conteúdo ao fim da lista com append -li.append(1) # li agora é [1] -li.append(2) # li agora é [1, 2] -li.append(4) # li agora é [1, 2, 4] -li.append(3) # li agora é [1, 2, 4, 3] -# Remova do final da lista com pop -li.pop() # => 3 e agora li é [1, 2, 4] -# Vamos colocá-lo lá novamente! -li.append(3) # li agora é [1, 2, 4, 3] novamente. - -# Acesse uma lista da mesma forma que você faz com um array -li[0] # => 1 -# Acessando o último elemento -li[-1] # => 3 - -# Acessar além dos limites gera um IndexError -li[4] # Gera o IndexError - -# Você pode acessar vários elementos com a sintaxe de limites -# Inclusivo para o primeiro termo, exclusivo para o segundo -li[1:3] # => [2, 4] -# Omitindo o final -li[2:] # => [4, 3] -# Omitindo o início -li[:3] # => [1, 2, 4] -# Selecione cada segunda entrada -li[::2] # => [1, 4] -# Tenha uma cópia em ordem invertida da lista -li[::-1] # => [3, 4, 2, 1] -# Use qualquer combinação dessas para indicar limites complexos -# li[inicio:fim:passo] - -# Faça uma cópia profunda de um nível usando limites -li2 = li[:] # => li2 = [1, 2, 4, 3] mas (li2 is li) resultará em False. - -# Apague elementos específicos da lista com "del" -del li[2] # li agora é [1, 2, 3] - -# Você pode somar listas -# Observação: valores em li e other_li não são modificados. -li + other_li # => [1, 2, 3, 4, 5, 6] - -# Concatene listas com "extend()" -li.extend(other_li) # Agora li é [1, 2, 3, 4, 5, 6] - -# Verifique se algo existe na lista com "in" -1 in li # => True - -# Examine tamanho com "len()" -len(li) # => 6 - - -# Tuplas são como l istas, mas imutáveis. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Gera um TypeError - -# Observe que uma tupla de tamanho um precisa ter uma vírgula depois do -# último elemento mas tuplas de outros tamanhos, mesmo vazias, não precisa,. -type((1)) # => -type((1,)) # => -type(()) # => - -# Você pode realizar com tuplas a maior parte das operações que faz com listas -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Você pode desmembrar tuplas (ou listas) em variáveis. -a, b, c = (1, 2, 3) # a é 1, b é 2 e c é 3 -# Por padrão, tuplas são criadas se você não coloca parêntesis. -d, e, f = 4, 5, 6 -# Veja como é fácil permutar dois valores -e, d = d, e # d é 5, e é 4 - -# Dicionários armazenam mapeamentos -empty_dict = {} -# Aqui está um dicionário preenchido na definição da referência -filled_dict = {"um": 1, "dois": 2, "três": 3} - -# Observe que chaves para dicionários devem ser tipos imutáveis. Isto é para -# assegurar que a chave pode ser convertida para uma valor hash constante para -# buscas rápidas. -# Tipos imutáveis incluem inteiros, flotas, strings e tuplas. -invalid_dict = {[1,2,3]: "123"} # => Gera um TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # Já os valores, podem ser de qualquer tipo. - -# Acesse valores com [] -filled_dict["um"] # => 1 - -# Acesse todas as chaves como um iterável com "keys()". É necessário encapsular -# a chamada com um list() para transformá-las em uma lista. Falaremos sobre isso -# mais adiante. Observe que a ordem de uma chave de dicionário não é garantida. -# Por isso, os resultados aqui apresentados podem não ser exatamente como os -# aqui apresentados. -list(filled_dict.keys()) # => ["três", "dois", "um"] - - -# Acesse todos os valores de um iterável com "values()". Novamente, é -# necessário encapsular ele com list() para não termos um iterável, e sim os -# valores. Observe que, como foi dito acima, a ordem dos elementos não é -# garantida. -list(filled_dict.values()) # => [3, 2, 1] - - -# Verifique a existência de chaves em um dicionário com "in" -"um" in filled_dict # => True -1 in filled_dict # => False - -# Acessar uma chave inexistente gera um KeyError -filled_dict["quatro"] # KeyError - -# Use o método "get()" para evitar um KeyError -filled_dict.get("um") # => 1 -filled_dict.get("quatro") # => None -# O método get permite um parâmetro padrão para quando não existir a chave -filled_dict.get("um", 4) # => 1 -filled_dict.get("quatro", 4) # => 4 - -# "setdefault()" insere em dicionário apenas se a dada chave não existir -filled_dict.setdefault("cinco", 5) # filled_dict["cinco"] tem valor 5 -filled_dict.setdefault("cinco", 6) # filled_dict["cinco"] continua 5 - -# Inserindo em um dicionário -filled_dict.update({"quatro":4}) # => {"um": 1, "dois": 2, "três": 3, "quatro": 4} -#filled_dict["quatro"] = 4 #outra forma de inserir em um dicionário - -# Remova chaves de um dicionário com del -del filled_dict["um"] # Remove a chave "um" de filled_dict - - -# Armazenamento em sets... bem, são conjuntos -empty_set = set() -# Inicializa um set com alguns valores. Sim, ele parece um dicionário. Desculpe. -some_set = {1, 1, 2, 2, 3, 4} # some_set agora é {1, 2, 3, 4} - -# Da mesma forma que chaves em um dicionário, elementos de um set devem ser -# imutáveis. -invalid_set = {[1], 1} # => Gera um TypeError: unhashable type: 'list' -valid_set = {(1,), 1} - -# Pode definir novas variáveis para um conjunto -filled_set = some_set - -# Inclua mais um item no set -filled_set.add(5) # filled_set agora é {1, 2, 3, 4, 5} - -# Faça interseção de conjuntos com & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# Faça união de conjuntos com | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Faça a diferença entre conjuntos com - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Verifique a existência em um conjunto com in -2 in filled_set # => True -10 in filled_set # => False - - - -#################################################### -## 3. Controle de fluxo e iteráveis -#################################################### - -# Iniciemos um variável -some_var = 5 - -# Aqui está uma expressão if. Indentação é significante em python! -# imprime "somevar é menor que10" -if some_var > 10: - print("some_var é absolutamente maior que 10.") -elif some_var < 10: # Esta cláusula elif é opcional. - print("some_var é menor que 10.") -else: # Isto também é opcional. - print("some_var é, de fato, 10.") - - -""" -Laços for iteram sobre listas -imprime: - cachorro é um mamífero - gato é um mamífero - rato é um mamífero -""" -for animal in ["cachorro", "gato", "rato"]: - # Você pode usar format() para interpolar strings formatadas - print("{} é um mamífero".format(animal)) - -""" -"range(número)" retorna um iterável de números -de zero até o número escolhido -imprime: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(menor, maior)" gera um iterável de números -começando pelo menor até o maior -imprime: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(menor, maior, passo)" retorna um iterável de números -começando pelo menor número até o maior númeno, pulando de -passo em passo. Se o passo não for indicado, o valor padrão é um. -imprime: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) -""" - -Laços while executam até que a condição não seja mais válida. -imprime: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Maneira mais curta para for x = x + 1 - -# Lide com exceções com um bloco try/except -try: - # Use "raise" para gerar um erro - raise IndexError("Isto é um erro de índice") -except IndexError as e: - pass # Pass é um não-operador. Normalmente você usa algum código de recuperação aqui. -except (TypeError, NameError): - pass # Varias exceções podem ser gerenciadas, se necessário. -else: # Cláusula opcional para o bloco try/except. Deve estar após todos os blocos de exceção. - print("Tudo certo!") # Executa apenas se o código em try não gera exceção -finally: # Sempre é executado - print("Nós podemos fazer o código de limpeza aqui.") - -# Ao invés de try/finally para limpeza você pode usar a cláusula with -with open("myfile.txt") as f: - for line in f: - print(line) - -# Python provê uma abstração fundamental chamada Iterável. -# Um iterável é um objeto que pode ser tratado como uma sequência. -# O objeto retornou a função range, um iterável. - -filled_dict = {"um": 1, "dois": 2, "três": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => range(1,10). Esse é um objeto que implementa nossa interface iterável. - -# Nós podemos percorrê-la. -for i in our_iterable: - print(i) # Imprime um, dois, três - -# Mas não podemos acessar os elementos pelo seu índice. -our_iterable[1] # Gera um TypeError - -# Um iterável é um objeto que sabe como criar um iterador. -our_iterator = iter(our_iterable) - -# Nosso iterador é um objeto que pode lembrar o estado enquanto nós o percorremos. -# Nós acessamos o próximo objeto com "next()". -next(our_iterator) # => "um" - -# Ele mantém o estado enquanto nós o percorremos. -next(our_iterator) # => "dois" -next(our_iterator) # => "três" - -# Após o iterador retornar todos os seus dados, ele gera a exceção StopIterator -next(our_iterator) # Gera StopIteration - -# Você pode capturar todos os elementos de um iterador aplicando list() nele. -list(filled_dict.keys()) # => Retorna ["um", "dois", "três"] - - -#################################################### -## 4. Funções -#################################################### - -# Use "def" para criar novas funções. -def add(x, y): - print("x é {} e y é {}".format(x, y)) - return x + y # Retorne valores com a cláusula return - -# Chamando funções com parâmetros -add(5, 6) # => imprime "x é 5 e y é 6" e retorna 11 - -# Outro meio de chamar funções é com argumentos nomeados -add(y=6, x=5) # Argumentos nomeados podem aparecer em qualquer ordem. - -# Você pode definir funções que pegam um número variável de argumentos -# posicionais -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# Você pode definir funções que pegam um número variável de argumentos nomeados -# também -def keyword_args(**kwargs): - return kwargs - -# Vamos chamá-lo para ver o que acontece -keyword_args(peh="grande", lago="ness") # => {"peh": "grande", "lago": "ness"} - - -# Você pode fazer ambos simultaneamente, se você quiser -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) imprime: - (1, 2) - {"a": 3, "b": 4} -""" - -# Quando chamar funções, você pode fazer o oposto de args/kwargs! -# Use * para expandir tuplas e use ** para expandir dicionários! -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalente a foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalente a foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) - -# Retornando múltiplos valores (com atribuição de tuplas) -def swap(x, y): - return y, x # Retorna múltiplos valores como uma tupla sem os parêntesis. - # (Observação: os parêntesis foram excluídos mas podem estar - # presentes) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # Novamente, os parêntesis foram excluídos mas podem estar presentes. - -# Escopo de função -x = 5 - -def setX(num): - # A variável local x não é a mesma variável global x - x = num # => 43 - print (x) # => 43 - -def setGlobalX(num): - global x - print (x) # => 5 - x = num # variável global x agora é 6 - print (x) # => 6 - -setX(43) -setGlobalX(6) - - -# Python tem funções de primeira classe -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Também existem as funções anônimas -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# TODO - Fix for iterables -# Existem funções internas de alta ordem -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] - -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# Nós podemos usar compreensão de lista para interessantes mapas e filtros -# Compreensão de lista armazena a saída como uma lista que pode ser uma lista -# aninhada -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -#################################################### -## 5. Classes -#################################################### - - -# Nós usamos o operador "class" para ter uma classe -class Human: - - # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa - # classe. - species = "H. sapiens" - - # Construtor básico, é chamado quando esta classe é instanciada. - # Note que dois sublinhados no início e no final de uma identificados - # significa objetos ou atributos que são usados pelo python mas vivem em - # um namespace controlado pelo usuário. Métodos (ou objetos ou atributos) - # como: __init__, __str__, __repr__, etc. são chamados métodos mágicos (ou - # algumas vezes chamados métodos dunder - "double underscore") - # Você não deve usar nomes assim por sua vontade. - def __init__(self, name): - @ Atribui o argumento ao atributo da instância - self.name = name - - # Um método de instância. Todos os métodos tem "self" como primeiro - # argumento - def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) - - # Um método de classe é compartilhado por todas as instâncias - # Eles são chamados com a classe requisitante como primeiro argumento - @classmethod - def get_species(cls): - return cls.species - - # Um método estático é chamado sem uma referência a classe ou instância - @staticmethod - def grunt(): - return "*grunt*" - - -# Instancie uma classe -i = Human(name="Ian") -print(i.say("oi")) # imprime "Ian: oi" - -j = Human("Joel") -print(j.say("olá")) # imprime "Joel: olá" - -# Chama nosso método de classe -i.get_species() # => "H. sapiens" - -# Altera um atributo compartilhado -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# Chama o método estático -Human.grunt() # => "*grunt*" - - -#################################################### -## 6. Módulos -#################################################### - -# Você pode importar módulos -import math -print(math.sqrt(16)) # => 4.0 - -# Você pode importar apenas funções específicas de um módulo -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Você pode importar todas as funções de um módulo para o namespace atual -# Atenção: isso não é recomendado -from math import * - -# Você pode encurtar o nome dos módulos -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Módulos python são apenas arquivos python comuns. Você -# pode escrever os seus, e importá-los. O nome do -# módulo é o mesmo nome do arquivo. - -# Você pode procurar que atributos e funções definem um módulo. -import math -dir(math) - - -#################################################### -## 7. Avançado -#################################################### - -# Geradores podem ajudar você a escrever código "preguiçoso" -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Um gerador cria valores conforme necessário. -# Ao invés de gerar e retornar todos os valores de uma só vez ele cria um em -# cada interação. Isto significa que valores maiores que 15 não serão -# processados em double_numbers. -# Nós usamos um sublinhado ao final do nome das variáveis quando queremos usar -# um nome que normalmente colide com uma palavra reservada do python. -range_ = range(1, 900000000) -# Multiplica por 2 todos os números até encontrar um resultado >= 30 -for i in double_numbers(range_): - print(i) - if i >= 30: - break - - -# Decoradores -# Neste exemplo beg encapsula say -# beg irá chamar say. Se say_please é verdade então ele irá mudar a mensagem -# retornada -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Por favor! Eu sou pobre :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Você me paga uma cerveja?" - return msg, say_please - - -print(say()) # Você me paga uma cerveja? -print(say(say_please=True)) # Você me paga uma cerveja? Por favor! Eu sou pobre :( -``` - -## Pronto para mais? - -### Free Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) - -### Dead Tree - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/python.html.markdown b/python.html.markdown new file mode 100644 index 00000000..f69ffb14 --- /dev/null +++ b/python.html.markdown @@ -0,0 +1,1042 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] + - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] + - ["caminsha", "https://github.com/caminsha"] +filename: learnpython3.py +--- + +Python was created by Guido van Rossum in the early 90s. It is now one of the most popular +languages in existence. I fell in love with Python for its syntactic clarity. It's basically +executable pseudocode. + +Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/python/) if you want to learn the old Python 2.7 + +```python + +# Single line comments start with a number symbol. + +""" Multiline strings can be written + using three "s, and are often used + as documentation. +""" + +#################################################### +## 1. Primitive Datatypes and Operators +#################################################### + +# You have numbers +3 # => 3 + +# Math is what you would expect +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# Integer division rounds down for both positive and negative numbers. +5 // 3 # => 1 +-5 // 3 # => -2 +5.0 // 3.0 # => 1.0 # works on floats too +-5.0 // 3.0 # => -2.0 + +# The result of division is always a float +10.0 / 3 # => 3.3333333333333335 + +# Modulo operation +7 % 3 # => 1 + +# Exponentiation (x**y, x to the yth power) +2**3 # => 8 + +# Enforce precedence with parentheses +1 + 3 * 2 # => 7 +(1 + 3) * 2 # => 8 + +# Boolean values are primitives (Note: the capitalization) +True # => True +False # => False + +# negate with not +not True # => False +not False # => True + +# Boolean Operators +# Note "and" and "or" are case-sensitive +True and False # => False +False or True # => True + +# True and False are actually 1 and 0 but with different keywords +True + True # => 2 +True * 8 # => 8 +False - 5 # => -5 + +# Comparison operators look at the numerical value of True and False +0 == False # => True +1 == True # => True +2 == True # => False +-5 != False # => True + +# Using boolean logical operators on ints casts them to booleans for evaluation, but their non-cast value is returned +# Don't mix up with bool(ints) and bitwise and/or (&,|) +bool(0) # => False +bool(4) # => True +bool(-6) # => True +0 and 2 # => 0 +-5 or 0 # => -5 + +# Equality is == +1 == 1 # => True +2 == 1 # => False + +# Inequality is != +1 != 1 # => False +2 != 1 # => True + +# More comparisons +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Seeing whether a value is in a range +1 < 2 and 2 < 3 # => True +2 < 3 and 3 < 2 # => False +# Chaining makes this look nicer +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) is checks if two variables refer to the same object, but == checks +# if the objects pointed to have the same values. +a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b = a # Point b at what a is pointing to +b is a # => True, a and b refer to the same object +b == a # => True, a's and b's objects are equal +b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4] +b is a # => False, a and b do not refer to the same object +b == a # => True, a's and b's objects are equal + +# Strings are created with " or ' +"This is a string." +'This is also a string.' + +# Strings can be added too! But try not to do this. +"Hello " + "world!" # => "Hello world!" +# String literals (but not variables) can be concatenated without using '+' +"Hello " "world!" # => "Hello world!" + +# A string can be treated like a list of characters +"This is a string"[0] # => 'T' + +# You can find the length of a string +len("This is a string") # => 16 + +# You can also format using f-strings or formatted string literals (in Python 3.6+) +name = "Reiko" +f"She said her name is {name}." # => "She said her name is Reiko" +# You can basically put any Python statement inside the braces and it will be output in the string. +f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long." + + +# None is an object +None # => None + +# Don't use the equality "==" symbol to compare objects to None +# Use "is" instead. This checks for equality of object identity. +"etc" is None # => False +None is None # => True + +# None, 0, and empty strings/lists/dicts/tuples all evaluate to False. +# All other values are True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +## 2. Variables and Collections +#################################################### + +# Python has a print function +print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! + +# By default the print function also prints out a newline at the end. +# Use the optional argument end to change the end string. +print("Hello, World", end="!") # => Hello, World! + +# Simple way to get input data from console +input_string_var = input("Enter some data: ") # Returns the data as a string +# Note: In earlier versions of Python, input() method was named as raw_input() + +# There are no declarations, only assignments. +# Convention is to use lower_case_with_underscores +some_var = 5 +some_var # => 5 + +# Accessing a previously unassigned variable is an exception. +# See Control Flow to learn more about exception handling. +some_unknown_var # Raises a NameError + +# if can be used as an expression +# Equivalent of C's '?:' ternary operator +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Lists store sequences +li = [] +# You can start with a prefilled list +other_li = [4, 5, 6] + +# Add stuff to the end of a list with append +li.append(1) # li is now [1] +li.append(2) # li is now [1, 2] +li.append(4) # li is now [1, 2, 4] +li.append(3) # li is now [1, 2, 4, 3] +# Remove from the end with pop +li.pop() # => 3 and li is now [1, 2, 4] +# Let's put it back +li.append(3) # li is now [1, 2, 4, 3] again. + +# Access a list like you would any array +li[0] # => 1 +# Look at the last element +li[-1] # => 3 + +# Looking out of bounds is an IndexError +li[4] # Raises an IndexError + +# You can look at ranges with slice syntax. +# The start index is included, the end index is not +# (It's a closed/open range for you mathy types.) +li[1:3] # Return list from index 1 to 3 => [2, 4] +li[2:] # Return list starting from index 2 => [4, 3] +li[:3] # Return list from beginning until index 3 => [1, 2, 4] +li[::2] # Return list selecting every second entry => [1, 4] +li[::-1] # Return list in reverse order => [3, 4, 2, 1] +# Use any combination of these to make advanced slices +# li[start:end:step] + +# Make a one layer deep copy using slices +li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. + +# Remove arbitrary elements from a list with "del" +del li[2] # li is now [1, 2, 3] + +# Remove first occurrence of a value +li.remove(2) # li is now [1, 3] +li.remove(2) # Raises a ValueError as 2 is not in the list + +# Insert an element at a specific index +li.insert(1, 2) # li is now [1, 2, 3] again + +# Get the index of the first item found matching the argument +li.index(2) # => 1 +li.index(4) # Raises a ValueError as 4 is not in the list + +# You can add lists +# Note: values for li and for other_li are not modified. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concatenate lists with "extend()" +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# Check for existence in a list with "in" +1 in li # => True + +# Examine the length with "len()" +len(li) # => 6 + + +# Tuples are like lists but are immutable. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Raises a TypeError + +# Note that a tuple of length one has to have a comma after the last element but +# tuples of other lengths, even zero, do not. +type((1)) # => +type((1,)) # => +type(()) # => + +# You can do most of the list operations on tuples too +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# You can unpack tuples (or lists) into variables +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +# You can also do extended unpacking +a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 +# Tuples are created by default if you leave out the parentheses +d, e, f = 4, 5, 6 # tuple 4, 5, 6 is unpacked into variables d, e and f +# respectively such that d = 4, e = 5 and f = 6 +# Now look how easy it is to swap two values +e, d = d, e # d is now 5 and e is now 4 + + +# Dictionaries store mappings from keys to values +empty_dict = {} +# Here is a prefilled dictionary +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Note keys for dictionaries have to be immutable types. This is to ensure that +# the key can be converted to a constant hash value for quick look-ups. +# Immutable types include ints, floats, strings, tuples. +invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. + +# Look up values with [] +filled_dict["one"] # => 1 + +# Get all keys as an iterable with "keys()". We need to wrap the call in list() +# to turn it into a list. We'll talk about those later. Note - for Python +# versions <3.7, dictionary key ordering is not guaranteed. Your results might +# not match the example below exactly. However, as of Python 3.7, dictionary +# items maintain the order at which they are inserted into the dictionary. +list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7 +list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+ + + +# Get all values as an iterable with "values()". Once again we need to wrap it +# in list() to get it out of the iterable. Note - Same as above regarding key +# ordering. +list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 +list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ + +# Check for existence of keys in a dictionary with "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# Looking up a non-existing key is a KeyError +filled_dict["four"] # KeyError + +# Use "get()" method to avoid the KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# The get method supports a default argument when the value is missing +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" inserts into a dictionary only if the given key isn't present +filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 + +# Adding to a dictionary +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict["four"] = 4 # another way to add to dict + +# Remove keys from a dictionary with del +del filled_dict["one"] # Removes the key "one" from filled dict + +# From Python 3.5 you can also use the additional unpacking options +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + + +# Sets store ... well sets +empty_set = set() +# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# Similar to keys of a dictionary, elements of a set have to be immutable. +invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Add one more item to the set +filled_set = some_set +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} +# Sets do not have duplicate elements +filled_set.add(5) # it remains as before {1, 2, 3, 4, 5} + +# Do set intersection with & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Do set union with | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Do set difference with - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Do set symmetric difference with ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Check if set on the left is a superset of set on the right +{1, 2} >= {1, 2, 3} # => False + +# Check if set on the left is a subset of set on the right +{1, 2} <= {1, 2, 3} # => True + +# Check for existence in a set with in +2 in filled_set # => True +10 in filled_set # => False + +# Make a one layer deep copy +filled_set = some_set.copy() # filled_set is {1, 2, 3, 4, 5} +filled_set is some_set # => False + + +#################################################### +## 3. Control Flow and Iterables +#################################################### + +# Let's just make a variable +some_var = 5 + +# Here is an if statement. Indentation is significant in Python! +# Convention is to use four spaces, not tabs. +# This prints "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # This elif clause is optional. + print("some_var is smaller than 10.") +else: # This is optional too. + print("some_var is indeed 10.") + + +""" +For loops iterate over lists +prints: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # You can use format() to interpolate formatted strings + print("{} is a mammal".format(animal)) + +""" +"range(number)" returns an iterable of numbers +from zero to the given number +prints: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(lower, upper)" returns an iterable of numbers +from the lower number to the upper number +prints: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(lower, upper, step)" returns an iterable of numbers +from the lower number to the upper number, while incrementing +by step. If step is not indicated, the default value is 1. +prints: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) + +""" +To loop over a list, and retrieve both the index and the value of each item in the list +prints: + 0 dog + 1 cat + 2 mouse +""" +animals = ["dog", "cat", "mouse"] +for i, value in enumerate(animals): + print(i, value) + +""" +While loops go until a condition is no longer met. +prints: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Shorthand for x = x + 1 + +# Handle exceptions with a try/except block +try: + # Use "raise" to raise an error + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass is just a no-op. Usually you would do recovery here. +except (TypeError, NameError): + pass # Multiple exceptions can be handled together, if required. +else: # Optional clause to the try/except block. Must follow all except blocks + print("All good!") # Runs only if the code in try raises no exceptions +finally: # Execute under all circumstances + print("We can clean up resources here") + +# Instead of try/finally to cleanup resources you can use a with statement +with open("myfile.txt") as f: + for line in f: + print(line) + +# Writing to a file +contents = {"aa": 12, "bb": 21} +with open("myfile1.txt", "w+") as file: + file.write(str(contents)) # writes a string to a file + +with open("myfile2.txt", "w+") as file: + file.write(json.dumps(contents)) # writes an object to a file + +# Reading from a file +with open('myfile1.txt', "r+") as file: + contents = file.read() # reads a string from a file +print(contents) +# print: {"aa": 12, "bb": 21} + +with open('myfile2.txt', "r+") as file: + contents = json.load(file) # reads a json object from a file +print(contents) +# print: {"aa": 12, "bb": 21} + + +# Python offers a fundamental abstraction called the Iterable. +# An iterable is an object that can be treated as a sequence. +# The object returned by the range function, is an iterable. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface. + +# We can loop over it. +for i in our_iterable: + print(i) # Prints one, two, three + +# However we cannot address elements by index. +our_iterable[1] # Raises a TypeError + +# An iterable is an object that knows how to create an iterator. +our_iterator = iter(our_iterable) + +# Our iterator is an object that can remember the state as we traverse through it. +# We get the next object with "next()". +next(our_iterator) # => "one" + +# It maintains state as we iterate. +next(our_iterator) # => "two" +next(our_iterator) # => "three" + +# After the iterator has returned all of its data, it raises a StopIteration exception +next(our_iterator) # Raises StopIteration + +# We can also loop over it, in fact, "for" does this implicitly! +our_iterator = iter(our_iterable) +for i in our_iterator: + print(i) # Prints one, two, three + +# You can grab all the elements of an iterable or iterator by calling list() on it. +list(our_iterable) # => Returns ["one", "two", "three"] +list(our_iterator) # => Returns [] because state is saved + + +#################################################### +## 4. Functions +#################################################### + +# Use "def" to create new functions +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # Return values with a return statement + +# Calling functions with parameters +add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 + +# Another way to call functions is with keyword arguments +add(y=6, x=5) # Keyword arguments can arrive in any order. + +# You can define functions that take a variable number of +# positional arguments +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# You can define functions that take a variable number of +# keyword arguments, as well +def keyword_args(**kwargs): + return kwargs + +# Let's call it to see what happens +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# You can do both at once, if you like +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# When calling functions, you can do the opposite of args/kwargs! +# Use * to expand tuples and use ** to expand kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4) + +# Returning multiple values (with tuple assignments) +def swap(x, y): + return y, x # Return multiple values as a tuple without the parenthesis. + # (Note: parenthesis have been excluded but can be included) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included. + +# Function Scope +x = 5 + +def set_x(num): + # Local var x not the same as global variable x + x = num # => 43 + print(x) # => 43 + +def set_global_x(num): + global x + print(x) # => 5 + x = num # global var x is now set to 6 + print(x) # => 6 + +set_x(43) +set_global_x(6) + + +# Python has first class functions +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# There are also anonymous functions +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# There are built-in higher order functions +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# We can use list comprehensions for nice maps and filters +# List comprehension stores the output as a list which can itself be a nested list +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# You can construct set and dict comprehensions as well. +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Modules +#################################################### + +# You can import modules +import math +print(math.sqrt(16)) # => 4.0 + +# You can get specific functions from a module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python modules are just ordinary Python files. You +# can write your own, and import them. The name of the +# module is the same as the name of the file. + +# You can find out which functions and attributes +# are defined in a module. +import math +dir(math) + +# If you have a Python script named math.py in the same +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. +# This happens because the local folder has priority +# over Python's built-in libraries. + + +#################################################### +## 6. Classes +#################################################### + +# We use the "class" statement to create a class +class Human: + + # A class attribute. It is shared by all instances of this class + species = "H. sapiens" + + # Basic initializer, this is called when this class is instantiated. + # Note that the double leading and trailing underscores denote objects + # or attributes that are used by Python but that live in user-controlled + # namespaces. Methods(or objects or attributes) like: __init__, __str__, + # __repr__ etc. are called special methods (or sometimes called dunder methods) + # You should not invent such names on your own. + def __init__(self, name): + # Assign the argument to the instance's name attribute + self.name = name + + # Initialize property + self._age = 0 + + # An instance method. All methods take "self" as the first argument + def say(self, msg): + print("{name}: {message}".format(name=self.name, message=msg)) + + # Another instance method + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # A class method is shared among all instances + # They are called with the calling class as the first argument + @classmethod + def get_species(cls): + return cls.species + + # A static method is called without a class or instance reference + @staticmethod + def grunt(): + return "*grunt*" + + # A property is just like a getter. + # It turns the method age() into an read-only attribute of the same name. + # There's no need to write trivial getters and setters in Python, though. + @property + def age(self): + return self._age + + # This allows the property to be set + @age.setter + def age(self, age): + self._age = age + + # This allows the property to be deleted + @age.deleter + def age(self): + del self._age + + +# When a Python interpreter reads a source file it executes all its code. +# This __name__ check makes sure this code block is only executed when this +# module is the main program. +if __name__ == '__main__': + # Instantiate a class + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i and j are instances of type Human, or in other words: they are Human objects + + # Call our class method + i.say(i.get_species()) # "Ian: H. sapiens" + # Change the shared attribute + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Call the static method + print(Human.grunt()) # => "*grunt*" + + # Cannot call static method with instance of object + # because i.grunt() will automatically put "self" (the object i) as an argument + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # Update the property for this instance + i.age = 42 + # Get the property + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # Delete the property + del i.age + # i.age # => this would raise an AttributeError + + +#################################################### +## 6.1 Inheritance +#################################################### + +# Inheritance allows new child classes to be defined that inherit methods and +# variables from their parent class. + +# Using the Human class defined above as the base or parent class, we can +# define a child class, Superhero, which inherits the class variables like +# "species", "name", and "age", as well as methods, like "sing" and "grunt" +# from the Human class, but can also have its own unique properties. + +# To take advantage of modularization by file you could place the classes above in their own files, +# say, human.py + +# To import functions from other files use the following format +# from "filename-without-extension" import "function-or-class" + +from human import Human + + +# Specify the parent class(es) as parameters to the class definition +class Superhero(Human): + + # If the child class should inherit all of the parent's definitions without + # any modifications, you can just use the "pass" keyword (and nothing else) + # but in this case it is commented out to allow for a unique child class: + # pass + + # Child classes can override their parents' attributes + species = 'Superhuman' + + # Children automatically inherit their parent class's constructor including + # its arguments, but can also define additional arguments or definitions + # and override its methods such as the class constructor. + # This constructor inherits the "name" argument from the "Human" class and + # adds the "superpower" and "movie" arguments: + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # add additional class attributes: + self.fictional = True + self.movie = movie + # be aware of mutable default values, since defaults are shared + self.superpowers = superpowers + + # The "super" function lets you access the parent class's methods + # that are overridden by the child, in this case, the __init__ method. + # This calls the parent class constructor: + super().__init__(name) + + # override the sing method + def sing(self): + return 'Dun, dun, DUN!' + + # add an additional instance method + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # Instance type checks + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') + + # Get the Method Resolution search Order used by both getattr() and super() + # This attribute is dynamic and can be updated + print(Superhero.__mro__) # => (, + # => , ) + + # Calls parent method but uses its own class attribute + print(sup.get_species()) # => Superhuman + + # Calls overridden method + print(sup.sing()) # => Dun, dun, DUN! + + # Calls method from Human + sup.say('Spoon') # => Tick: Spoon + + # Call method that exists only in Superhero + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # Inherited class attribute + sup.age = 31 + print(sup.age) # => 31 + + # Attribute that only exists within Superhero + print('Am I Oscar eligible? ' + str(sup.movie)) + +#################################################### +## 6.2 Multiple Inheritance +#################################################### + +# Another class definition +# bat.py +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # This class also has a say method + def say(self, msg): + msg = '... ... ...' + return msg + + # And its own method as well + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + + +# And yet another class definition that inherits from Superhero and Bat +# superhero.py +from superhero import Superhero +from bat import Bat + +# Define Batman as a child that inherits from both Superhero and Bat +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # Typically to inherit attributes you have to call super: + # super(Batman, self).__init__(*args, **kwargs) + # However we are dealing with multiple inheritance here, and super() + # only works with the next base class in the MRO list. + # So instead we explicitly call __init__ for all ancestors. + # The use of *args and **kwargs allows for a clean way to pass arguments, + # with each parent "peeling a layer of the onion". + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # override the value for the name attribute + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # Get the Method Resolution search Order used by both getattr() and super(). + # This attribute is dynamic and can be updated + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + # Calls parent method but uses its own class attribute + print(sup.get_species()) # => Superhuman + + # Calls overridden method + print(sup.sing()) # => nan nan nan nan nan batman! + + # Calls method from Human, because inheritance order matters + sup.say('I agree') # => Sad Affleck: I agree + + # Call method that exists only in 2nd ancestor + print(sup.sonar()) # => ))) ... ((( + + # Inherited class attribute + sup.age = 100 + print(sup.age) # => 100 + + # Inherited attribute from 2nd ancestor whose default value was overridden. + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False + + + +#################################################### +## 7. Advanced +#################################################### + +# Generators help you make lazy code. +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Generators are memory-efficient because they only load the data needed to +# process the next value in the iterable. This allows them to perform +# operations on otherwise prohibitively large value ranges. +# NOTE: `range` replaces `xrange` in Python 3. +for i in double_numbers(range(1, 900000000)): # `range` is a generator. + print(i) + if i >= 30: + break + +# Just as you can create a list comprehension, you can create generator +# comprehensions as well. +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# You can also cast a generator comprehension directly to a list. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# Decorators +# In this example `beg` wraps `say`. If say_please is True then it +# will change the returned message. +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +``` + +## Ready For More? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/python3.html.markdown b/python3.html.markdown deleted file mode 100644 index f69ffb14..00000000 --- a/python3.html.markdown +++ /dev/null @@ -1,1042 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["evuez", "http://github.com/evuez"] - - ["Rommel Martinez", "https://ebzzry.io"] - - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] - - ["caminsha", "https://github.com/caminsha"] -filename: learnpython3.py ---- - -Python was created by Guido van Rossum in the early 90s. It is now one of the most popular -languages in existence. I fell in love with Python for its syntactic clarity. It's basically -executable pseudocode. - -Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/python/) if you want to learn the old Python 2.7 - -```python - -# Single line comments start with a number symbol. - -""" Multiline strings can be written - using three "s, and are often used - as documentation. -""" - -#################################################### -## 1. Primitive Datatypes and Operators -#################################################### - -# You have numbers -3 # => 3 - -# Math is what you would expect -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 - -# Integer division rounds down for both positive and negative numbers. -5 // 3 # => 1 --5 // 3 # => -2 -5.0 // 3.0 # => 1.0 # works on floats too --5.0 // 3.0 # => -2.0 - -# The result of division is always a float -10.0 / 3 # => 3.3333333333333335 - -# Modulo operation -7 % 3 # => 1 - -# Exponentiation (x**y, x to the yth power) -2**3 # => 8 - -# Enforce precedence with parentheses -1 + 3 * 2 # => 7 -(1 + 3) * 2 # => 8 - -# Boolean values are primitives (Note: the capitalization) -True # => True -False # => False - -# negate with not -not True # => False -not False # => True - -# Boolean Operators -# Note "and" and "or" are case-sensitive -True and False # => False -False or True # => True - -# True and False are actually 1 and 0 but with different keywords -True + True # => 2 -True * 8 # => 8 -False - 5 # => -5 - -# Comparison operators look at the numerical value of True and False -0 == False # => True -1 == True # => True -2 == True # => False --5 != False # => True - -# Using boolean logical operators on ints casts them to booleans for evaluation, but their non-cast value is returned -# Don't mix up with bool(ints) and bitwise and/or (&,|) -bool(0) # => False -bool(4) # => True -bool(-6) # => True -0 and 2 # => 0 --5 or 0 # => -5 - -# Equality is == -1 == 1 # => True -2 == 1 # => False - -# Inequality is != -1 != 1 # => False -2 != 1 # => True - -# More comparisons -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Seeing whether a value is in a range -1 < 2 and 2 < 3 # => True -2 < 3 and 3 < 2 # => False -# Chaining makes this look nicer -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# (is vs. ==) is checks if two variables refer to the same object, but == checks -# if the objects pointed to have the same values. -a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] -b = a # Point b at what a is pointing to -b is a # => True, a and b refer to the same object -b == a # => True, a's and b's objects are equal -b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4] -b is a # => False, a and b do not refer to the same object -b == a # => True, a's and b's objects are equal - -# Strings are created with " or ' -"This is a string." -'This is also a string.' - -# Strings can be added too! But try not to do this. -"Hello " + "world!" # => "Hello world!" -# String literals (but not variables) can be concatenated without using '+' -"Hello " "world!" # => "Hello world!" - -# A string can be treated like a list of characters -"This is a string"[0] # => 'T' - -# You can find the length of a string -len("This is a string") # => 16 - -# You can also format using f-strings or formatted string literals (in Python 3.6+) -name = "Reiko" -f"She said her name is {name}." # => "She said her name is Reiko" -# You can basically put any Python statement inside the braces and it will be output in the string. -f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long." - - -# None is an object -None # => None - -# Don't use the equality "==" symbol to compare objects to None -# Use "is" instead. This checks for equality of object identity. -"etc" is None # => False -None is None # => True - -# None, 0, and empty strings/lists/dicts/tuples all evaluate to False. -# All other values are True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False - -#################################################### -## 2. Variables and Collections -#################################################### - -# Python has a print function -print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! - -# By default the print function also prints out a newline at the end. -# Use the optional argument end to change the end string. -print("Hello, World", end="!") # => Hello, World! - -# Simple way to get input data from console -input_string_var = input("Enter some data: ") # Returns the data as a string -# Note: In earlier versions of Python, input() method was named as raw_input() - -# There are no declarations, only assignments. -# Convention is to use lower_case_with_underscores -some_var = 5 -some_var # => 5 - -# Accessing a previously unassigned variable is an exception. -# See Control Flow to learn more about exception handling. -some_unknown_var # Raises a NameError - -# if can be used as an expression -# Equivalent of C's '?:' ternary operator -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# Lists store sequences -li = [] -# You can start with a prefilled list -other_li = [4, 5, 6] - -# Add stuff to the end of a list with append -li.append(1) # li is now [1] -li.append(2) # li is now [1, 2] -li.append(4) # li is now [1, 2, 4] -li.append(3) # li is now [1, 2, 4, 3] -# Remove from the end with pop -li.pop() # => 3 and li is now [1, 2, 4] -# Let's put it back -li.append(3) # li is now [1, 2, 4, 3] again. - -# Access a list like you would any array -li[0] # => 1 -# Look at the last element -li[-1] # => 3 - -# Looking out of bounds is an IndexError -li[4] # Raises an IndexError - -# You can look at ranges with slice syntax. -# The start index is included, the end index is not -# (It's a closed/open range for you mathy types.) -li[1:3] # Return list from index 1 to 3 => [2, 4] -li[2:] # Return list starting from index 2 => [4, 3] -li[:3] # Return list from beginning until index 3 => [1, 2, 4] -li[::2] # Return list selecting every second entry => [1, 4] -li[::-1] # Return list in reverse order => [3, 4, 2, 1] -# Use any combination of these to make advanced slices -# li[start:end:step] - -# Make a one layer deep copy using slices -li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. - -# Remove arbitrary elements from a list with "del" -del li[2] # li is now [1, 2, 3] - -# Remove first occurrence of a value -li.remove(2) # li is now [1, 3] -li.remove(2) # Raises a ValueError as 2 is not in the list - -# Insert an element at a specific index -li.insert(1, 2) # li is now [1, 2, 3] again - -# Get the index of the first item found matching the argument -li.index(2) # => 1 -li.index(4) # Raises a ValueError as 4 is not in the list - -# You can add lists -# Note: values for li and for other_li are not modified. -li + other_li # => [1, 2, 3, 4, 5, 6] - -# Concatenate lists with "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] - -# Check for existence in a list with "in" -1 in li # => True - -# Examine the length with "len()" -len(li) # => 6 - - -# Tuples are like lists but are immutable. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Raises a TypeError - -# Note that a tuple of length one has to have a comma after the last element but -# tuples of other lengths, even zero, do not. -type((1)) # => -type((1,)) # => -type(()) # => - -# You can do most of the list operations on tuples too -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# You can unpack tuples (or lists) into variables -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 -# You can also do extended unpacking -a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 -# Tuples are created by default if you leave out the parentheses -d, e, f = 4, 5, 6 # tuple 4, 5, 6 is unpacked into variables d, e and f -# respectively such that d = 4, e = 5 and f = 6 -# Now look how easy it is to swap two values -e, d = d, e # d is now 5 and e is now 4 - - -# Dictionaries store mappings from keys to values -empty_dict = {} -# Here is a prefilled dictionary -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Note keys for dictionaries have to be immutable types. This is to ensure that -# the key can be converted to a constant hash value for quick look-ups. -# Immutable types include ints, floats, strings, tuples. -invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. - -# Look up values with [] -filled_dict["one"] # => 1 - -# Get all keys as an iterable with "keys()". We need to wrap the call in list() -# to turn it into a list. We'll talk about those later. Note - for Python -# versions <3.7, dictionary key ordering is not guaranteed. Your results might -# not match the example below exactly. However, as of Python 3.7, dictionary -# items maintain the order at which they are inserted into the dictionary. -list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7 -list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+ - - -# Get all values as an iterable with "values()". Once again we need to wrap it -# in list() to get it out of the iterable. Note - Same as above regarding key -# ordering. -list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 -list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ - -# Check for existence of keys in a dictionary with "in" -"one" in filled_dict # => True -1 in filled_dict # => False - -# Looking up a non-existing key is a KeyError -filled_dict["four"] # KeyError - -# Use "get()" method to avoid the KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# The get method supports a default argument when the value is missing -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# "setdefault()" inserts into a dictionary only if the given key isn't present -filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 - -# Adding to a dictionary -filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -filled_dict["four"] = 4 # another way to add to dict - -# Remove keys from a dictionary with del -del filled_dict["one"] # Removes the key "one" from filled dict - -# From Python 3.5 you can also use the additional unpacking options -{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} -{'a': 1, **{'a': 2}} # => {'a': 2} - - - -# Sets store ... well sets -empty_set = set() -# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} - -# Similar to keys of a dictionary, elements of a set have to be immutable. -invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list' -valid_set = {(1,), 1} - -# Add one more item to the set -filled_set = some_set -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} -# Sets do not have duplicate elements -filled_set.add(5) # it remains as before {1, 2, 3, 4, 5} - -# Do set intersection with & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# Do set union with | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Do set difference with - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Do set symmetric difference with ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Check if set on the left is a superset of set on the right -{1, 2} >= {1, 2, 3} # => False - -# Check if set on the left is a subset of set on the right -{1, 2} <= {1, 2, 3} # => True - -# Check for existence in a set with in -2 in filled_set # => True -10 in filled_set # => False - -# Make a one layer deep copy -filled_set = some_set.copy() # filled_set is {1, 2, 3, 4, 5} -filled_set is some_set # => False - - -#################################################### -## 3. Control Flow and Iterables -#################################################### - -# Let's just make a variable -some_var = 5 - -# Here is an if statement. Indentation is significant in Python! -# Convention is to use four spaces, not tabs. -# This prints "some_var is smaller than 10" -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # This elif clause is optional. - print("some_var is smaller than 10.") -else: # This is optional too. - print("some_var is indeed 10.") - - -""" -For loops iterate over lists -prints: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # You can use format() to interpolate formatted strings - print("{} is a mammal".format(animal)) - -""" -"range(number)" returns an iterable of numbers -from zero to the given number -prints: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(lower, upper)" returns an iterable of numbers -from the lower number to the upper number -prints: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(lower, upper, step)" returns an iterable of numbers -from the lower number to the upper number, while incrementing -by step. If step is not indicated, the default value is 1. -prints: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) - -""" -To loop over a list, and retrieve both the index and the value of each item in the list -prints: - 0 dog - 1 cat - 2 mouse -""" -animals = ["dog", "cat", "mouse"] -for i, value in enumerate(animals): - print(i, value) - -""" -While loops go until a condition is no longer met. -prints: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Shorthand for x = x + 1 - -# Handle exceptions with a try/except block -try: - # Use "raise" to raise an error - raise IndexError("This is an index error") -except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. -except (TypeError, NameError): - pass # Multiple exceptions can be handled together, if required. -else: # Optional clause to the try/except block. Must follow all except blocks - print("All good!") # Runs only if the code in try raises no exceptions -finally: # Execute under all circumstances - print("We can clean up resources here") - -# Instead of try/finally to cleanup resources you can use a with statement -with open("myfile.txt") as f: - for line in f: - print(line) - -# Writing to a file -contents = {"aa": 12, "bb": 21} -with open("myfile1.txt", "w+") as file: - file.write(str(contents)) # writes a string to a file - -with open("myfile2.txt", "w+") as file: - file.write(json.dumps(contents)) # writes an object to a file - -# Reading from a file -with open('myfile1.txt', "r+") as file: - contents = file.read() # reads a string from a file -print(contents) -# print: {"aa": 12, "bb": 21} - -with open('myfile2.txt', "r+") as file: - contents = json.load(file) # reads a json object from a file -print(contents) -# print: {"aa": 12, "bb": 21} - - -# Python offers a fundamental abstraction called the Iterable. -# An iterable is an object that can be treated as a sequence. -# The object returned by the range function, is an iterable. - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface. - -# We can loop over it. -for i in our_iterable: - print(i) # Prints one, two, three - -# However we cannot address elements by index. -our_iterable[1] # Raises a TypeError - -# An iterable is an object that knows how to create an iterator. -our_iterator = iter(our_iterable) - -# Our iterator is an object that can remember the state as we traverse through it. -# We get the next object with "next()". -next(our_iterator) # => "one" - -# It maintains state as we iterate. -next(our_iterator) # => "two" -next(our_iterator) # => "three" - -# After the iterator has returned all of its data, it raises a StopIteration exception -next(our_iterator) # Raises StopIteration - -# We can also loop over it, in fact, "for" does this implicitly! -our_iterator = iter(our_iterable) -for i in our_iterator: - print(i) # Prints one, two, three - -# You can grab all the elements of an iterable or iterator by calling list() on it. -list(our_iterable) # => Returns ["one", "two", "three"] -list(our_iterator) # => Returns [] because state is saved - - -#################################################### -## 4. Functions -#################################################### - -# Use "def" to create new functions -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # Return values with a return statement - -# Calling functions with parameters -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 - -# Another way to call functions is with keyword arguments -add(y=6, x=5) # Keyword arguments can arrive in any order. - -# You can define functions that take a variable number of -# positional arguments -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# You can define functions that take a variable number of -# keyword arguments, as well -def keyword_args(**kwargs): - return kwargs - -# Let's call it to see what happens -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# You can do both at once, if you like -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) prints: - (1, 2) - {"a": 3, "b": 4} -""" - -# When calling functions, you can do the opposite of args/kwargs! -# Use * to expand tuples and use ** to expand kwargs. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4) - -# Returning multiple values (with tuple assignments) -def swap(x, y): - return y, x # Return multiple values as a tuple without the parenthesis. - # (Note: parenthesis have been excluded but can be included) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included. - -# Function Scope -x = 5 - -def set_x(num): - # Local var x not the same as global variable x - x = num # => 43 - print(x) # => 43 - -def set_global_x(num): - global x - print(x) # => 5 - x = num # global var x is now set to 6 - print(x) # => 6 - -set_x(43) -set_global_x(6) - - -# Python has first class functions -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# There are also anonymous functions -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# There are built-in higher order functions -list(map(add_10, [1, 2, 3])) # => [11, 12, 13] -list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] - -list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] - -# We can use list comprehensions for nice maps and filters -# List comprehension stores the output as a list which can itself be a nested list -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# You can construct set and dict comprehensions as well. -{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} -{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -## 5. Modules -#################################################### - -# You can import modules -import math -print(math.sqrt(16)) # => 4.0 - -# You can get specific functions from a module -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# You can import all functions from a module. -# Warning: this is not recommended -from math import * - -# You can shorten module names -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Python modules are just ordinary Python files. You -# can write your own, and import them. The name of the -# module is the same as the name of the file. - -# You can find out which functions and attributes -# are defined in a module. -import math -dir(math) - -# If you have a Python script named math.py in the same -# folder as your current script, the file math.py will -# be loaded instead of the built-in Python module. -# This happens because the local folder has priority -# over Python's built-in libraries. - - -#################################################### -## 6. Classes -#################################################### - -# We use the "class" statement to create a class -class Human: - - # A class attribute. It is shared by all instances of this class - species = "H. sapiens" - - # Basic initializer, this is called when this class is instantiated. - # Note that the double leading and trailing underscores denote objects - # or attributes that are used by Python but that live in user-controlled - # namespaces. Methods(or objects or attributes) like: __init__, __str__, - # __repr__ etc. are called special methods (or sometimes called dunder methods) - # You should not invent such names on your own. - def __init__(self, name): - # Assign the argument to the instance's name attribute - self.name = name - - # Initialize property - self._age = 0 - - # An instance method. All methods take "self" as the first argument - def say(self, msg): - print("{name}: {message}".format(name=self.name, message=msg)) - - # Another instance method - def sing(self): - return 'yo... yo... microphone check... one two... one two...' - - # A class method is shared among all instances - # They are called with the calling class as the first argument - @classmethod - def get_species(cls): - return cls.species - - # A static method is called without a class or instance reference - @staticmethod - def grunt(): - return "*grunt*" - - # A property is just like a getter. - # It turns the method age() into an read-only attribute of the same name. - # There's no need to write trivial getters and setters in Python, though. - @property - def age(self): - return self._age - - # This allows the property to be set - @age.setter - def age(self, age): - self._age = age - - # This allows the property to be deleted - @age.deleter - def age(self): - del self._age - - -# When a Python interpreter reads a source file it executes all its code. -# This __name__ check makes sure this code block is only executed when this -# module is the main program. -if __name__ == '__main__': - # Instantiate a class - i = Human(name="Ian") - i.say("hi") # "Ian: hi" - j = Human("Joel") - j.say("hello") # "Joel: hello" - # i and j are instances of type Human, or in other words: they are Human objects - - # Call our class method - i.say(i.get_species()) # "Ian: H. sapiens" - # Change the shared attribute - Human.species = "H. neanderthalensis" - i.say(i.get_species()) # => "Ian: H. neanderthalensis" - j.say(j.get_species()) # => "Joel: H. neanderthalensis" - - # Call the static method - print(Human.grunt()) # => "*grunt*" - - # Cannot call static method with instance of object - # because i.grunt() will automatically put "self" (the object i) as an argument - print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given - - # Update the property for this instance - i.age = 42 - # Get the property - i.say(i.age) # => "Ian: 42" - j.say(j.age) # => "Joel: 0" - # Delete the property - del i.age - # i.age # => this would raise an AttributeError - - -#################################################### -## 6.1 Inheritance -#################################################### - -# Inheritance allows new child classes to be defined that inherit methods and -# variables from their parent class. - -# Using the Human class defined above as the base or parent class, we can -# define a child class, Superhero, which inherits the class variables like -# "species", "name", and "age", as well as methods, like "sing" and "grunt" -# from the Human class, but can also have its own unique properties. - -# To take advantage of modularization by file you could place the classes above in their own files, -# say, human.py - -# To import functions from other files use the following format -# from "filename-without-extension" import "function-or-class" - -from human import Human - - -# Specify the parent class(es) as parameters to the class definition -class Superhero(Human): - - # If the child class should inherit all of the parent's definitions without - # any modifications, you can just use the "pass" keyword (and nothing else) - # but in this case it is commented out to allow for a unique child class: - # pass - - # Child classes can override their parents' attributes - species = 'Superhuman' - - # Children automatically inherit their parent class's constructor including - # its arguments, but can also define additional arguments or definitions - # and override its methods such as the class constructor. - # This constructor inherits the "name" argument from the "Human" class and - # adds the "superpower" and "movie" arguments: - def __init__(self, name, movie=False, - superpowers=["super strength", "bulletproofing"]): - - # add additional class attributes: - self.fictional = True - self.movie = movie - # be aware of mutable default values, since defaults are shared - self.superpowers = superpowers - - # The "super" function lets you access the parent class's methods - # that are overridden by the child, in this case, the __init__ method. - # This calls the parent class constructor: - super().__init__(name) - - # override the sing method - def sing(self): - return 'Dun, dun, DUN!' - - # add an additional instance method - def boast(self): - for power in self.superpowers: - print("I wield the power of {pow}!".format(pow=power)) - - -if __name__ == '__main__': - sup = Superhero(name="Tick") - - # Instance type checks - if isinstance(sup, Human): - print('I am human') - if type(sup) is Superhero: - print('I am a superhero') - - # Get the Method Resolution search Order used by both getattr() and super() - # This attribute is dynamic and can be updated - print(Superhero.__mro__) # => (, - # => , ) - - # Calls parent method but uses its own class attribute - print(sup.get_species()) # => Superhuman - - # Calls overridden method - print(sup.sing()) # => Dun, dun, DUN! - - # Calls method from Human - sup.say('Spoon') # => Tick: Spoon - - # Call method that exists only in Superhero - sup.boast() # => I wield the power of super strength! - # => I wield the power of bulletproofing! - - # Inherited class attribute - sup.age = 31 - print(sup.age) # => 31 - - # Attribute that only exists within Superhero - print('Am I Oscar eligible? ' + str(sup.movie)) - -#################################################### -## 6.2 Multiple Inheritance -#################################################### - -# Another class definition -# bat.py -class Bat: - - species = 'Baty' - - def __init__(self, can_fly=True): - self.fly = can_fly - - # This class also has a say method - def say(self, msg): - msg = '... ... ...' - return msg - - # And its own method as well - def sonar(self): - return '))) ... (((' - -if __name__ == '__main__': - b = Bat() - print(b.say('hello')) - print(b.fly) - - -# And yet another class definition that inherits from Superhero and Bat -# superhero.py -from superhero import Superhero -from bat import Bat - -# Define Batman as a child that inherits from both Superhero and Bat -class Batman(Superhero, Bat): - - def __init__(self, *args, **kwargs): - # Typically to inherit attributes you have to call super: - # super(Batman, self).__init__(*args, **kwargs) - # However we are dealing with multiple inheritance here, and super() - # only works with the next base class in the MRO list. - # So instead we explicitly call __init__ for all ancestors. - # The use of *args and **kwargs allows for a clean way to pass arguments, - # with each parent "peeling a layer of the onion". - Superhero.__init__(self, 'anonymous', movie=True, - superpowers=['Wealthy'], *args, **kwargs) - Bat.__init__(self, *args, can_fly=False, **kwargs) - # override the value for the name attribute - self.name = 'Sad Affleck' - - def sing(self): - return 'nan nan nan nan nan batman!' - - -if __name__ == '__main__': - sup = Batman() - - # Get the Method Resolution search Order used by both getattr() and super(). - # This attribute is dynamic and can be updated - print(Batman.__mro__) # => (, - # => , - # => , - # => , ) - - # Calls parent method but uses its own class attribute - print(sup.get_species()) # => Superhuman - - # Calls overridden method - print(sup.sing()) # => nan nan nan nan nan batman! - - # Calls method from Human, because inheritance order matters - sup.say('I agree') # => Sad Affleck: I agree - - # Call method that exists only in 2nd ancestor - print(sup.sonar()) # => ))) ... ((( - - # Inherited class attribute - sup.age = 100 - print(sup.age) # => 100 - - # Inherited attribute from 2nd ancestor whose default value was overridden. - print('Can I fly? ' + str(sup.fly)) # => Can I fly? False - - - -#################################################### -## 7. Advanced -#################################################### - -# Generators help you make lazy code. -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Generators are memory-efficient because they only load the data needed to -# process the next value in the iterable. This allows them to perform -# operations on otherwise prohibitively large value ranges. -# NOTE: `range` replaces `xrange` in Python 3. -for i in double_numbers(range(1, 900000000)): # `range` is a generator. - print(i) - if i >= 30: - break - -# Just as you can create a list comprehension, you can create generator -# comprehensions as well. -values = (-x for x in [1,2,3,4,5]) -for x in values: - print(x) # prints -1 -2 -3 -4 -5 to console/terminal - -# You can also cast a generator comprehension directly to a list. -values = (-x for x in [1,2,3,4,5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - - -# Decorators -# In this example `beg` wraps `say`. If say_please is True then it -# will change the returned message. -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( -``` - -## Ready For More? - -### Free Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) -* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) -* [Dive Into Python 3](http://www.diveintopython3.net/index.html) -* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown new file mode 100644 index 00000000..bf80fed2 --- /dev/null +++ b/ru-ru/python-ru.html.markdown @@ -0,0 +1,651 @@ +--- +language: python3 +lang: ru-ru +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Steven Basart", "http://github.com/xksteven"] +translators: + - ["Andre Polykanine", "https://github.com/Oire"] +filename: learnpython3-ru.py +--- + +Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из +самых популярных языков. Я влюбился в Python за понятный и доходчивый синтаксис — это +почти что исполняемый псевдокод. + +С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh) +или louiedinh [at] [почтовый сервис Google] + +Замечание: Эта статья относится только к Python 3. +Если вы хотите изучить Python 2.7, обратитесь к другой статье. + +```python +# Однострочные комментарии начинаются с символа решётки. +""" Многострочный текст может быть + записан, используя 3 знака " и обычно используется + в качестве встроенной документации +""" + +#################################################### +## 1. Примитивные типы данных и операторы +#################################################### + +# У вас есть числа +3 #=> 3 + +# Математика работает вполне ожидаемо +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 + +# Кроме деления, которое по умолчанию возвращает число с плавающей запятой +35 / 5 # => 7.0 + +# Результат целочисленного деления округляется в меньшую сторону +# как для положительных, так и для отрицательных чисел. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Когда вы используете числа с плавающей запятой, +# результатом будет также число с плавающей запятой +3 * 2.0 # => 6.0 + +# Остаток от деления +7 % 3 # => 1 + +# Возведение в степень +2**4 # => 16 + +# Приоритет операций указывается скобками +(1 + 3) * 2 #=> 8 + +# Для логических (булевых) значений существует отдельный примитивный тип +True +False + +# Для отрицания используется ключевое слово not +not True #=> False +not False #=> True + +# Логические операторы +# Обратите внимание: ключевые слова «and» и «or» чувствительны к регистру букв +True and False #=> False +False or True #=> True + +# Обратите внимание, что логические операторы используются и с целыми числами +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Равенство — это == +1 == 1 #=> True +2 == 1 #=> False + +# Неравенство — это != +1 != 1 #=> False +2 != 1 #=> True + +# Ещё немного сравнений +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Сравнения могут быть записаны цепочкой: +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Строки определяются символом " или ' +"Это строка." +'Это тоже строка.' + +# И строки тоже могут складываться! Хотя лучше не злоупотребляйте этим. +"Привет " + "мир!" #=> "Привет мир!" + +# Строки можно умножать. +"aa" * 4 #=> "aaaaaaaa" + +# Со строкой можно работать, как со списком символов +"Это строка"[0] #=> 'Э' + +# Метод format используется для форматирования строк: +"{0} могут быть {1}".format("строки", "форматированы") + +# Вы можете повторять аргументы форматирования, чтобы меньше печатать. +"Ехал {0} через реку, видит {0} - в реке {1}! Сунул {0} руку в реку, {1} за руку греку цап!".format("грека", "рак") +#=> "Ехал грека через реку, видит грека - в реке рак! Сунул грека руку в реку, рак за руку греку цап!" +# Если вы не хотите считать, можете использовать ключевые слова. +"{name} хочет есть {food}".format(name="Боб", food="лазанью") + +# Если ваш код на Python 3 нужно запускать также и под Python 2.5 и ниже, +# вы также можете использовать старый способ форматирования: +"%s можно %s %s способом" % ("строки", "интерполировать", "старым") + +# None является объектом +None #=> None + +# Не используйте оператор равенства '==' для сравнения +# объектов с None. Используйте для этого 'is' +"etc" is None #=> False +None is None #=> True + +# Оператор «is» проверяет идентичность объектов. Он не +# очень полезен при работе с примитивными типами, но +# зато просто незаменим при работе с объектами. + +# None, 0 и пустые строки/списки/словари приводятся к False. +# Все остальные значения равны True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Переменные и коллекции +#################################################### + +# В Python есть функция Print +print("Я Python. Приятно познакомиться!") + +# Объявлять переменные перед инициализацией не нужно. +# По соглашению используется нижний_регистр_с_подчёркиваниями +some_var = 5 +some_var #=> 5 + +# При попытке доступа к неинициализированной переменной +# выбрасывается исключение. +# Об исключениях см. раздел «Поток управления и итерируемые объекты». +some_unknown_var # Выбрасывает ошибку именования + +# Списки хранят последовательности +li = [] +# Можно сразу начать с заполненного списка +other_li = [4, 5, 6] + +# Объекты добавляются в конец списка методом append +li.append(1) # [1] +li.append(2) # [1, 2] +li.append(4) # [1, 2, 4] +li.append(3) # [1, 2, 4, 3] +# И удаляются с конца методом pop +li.pop() #=> возвращает 3 и li становится равен [1, 2, 4] +# Положим элемент обратно +li.append(3) # [1, 2, 4, 3]. + +# Обращайтесь со списком, как с обычным массивом +li[0] #=> 1 +# Обратимся к последнему элементу +li[-1] #=> 3 + +# Попытка выйти за границы массива приведёт к ошибке индекса +li[4] # Выдаёт IndexError + +# Можно обращаться к диапазону, используя так называемые срезы +# (Для тех, кто любит математику, это называется замкнуто-открытый интервал). +li[1:3] #=> [2, 4] +# Опускаем начало +li[2:] #=> [4, 3] +# Опускаем конец +li[:3] #=> [1, 2, 4] +# Выбираем каждый второй элемент +li[::2] # =>[1, 4] +# Переворачиваем список +li[::-1] # => [3, 4, 2, 1] +# Используйте сочетания всего вышеназванного для выделения более сложных срезов +# li[начало:конец:шаг] + +# Удаляем произвольные элементы из списка оператором del +del li[2] # [1, 2, 3] + +# Вы можете складывать, или, как ещё говорят, конкатенировать списки +# Обратите внимание: значения li и other_li при этом не изменились. +li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются + +# Объединять списки можно методом extend +li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6] + +# Проверить элемент на вхождение в список можно оператором in +1 in li #=> True + +# Длина списка вычисляется функцией len +len(li) #=> 6 + + +# Кортежи — это такие списки, только неизменяемые +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Выдаёт TypeError + +# Всё то же самое можно делать и с кортежами +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Вы можете распаковывать кортежи (или списки) в переменные +a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3 +# Кортежи создаются по умолчанию, если опущены скобки +d, e, f = 4, 5, 6 +# Обратите внимание, как легко поменять местами значения двух переменных +e, d = d, e # теперь d == 5, а e == 4 + + +# Словари содержат ассоциативные массивы +empty_dict = {} +# Вот так описывается предзаполненный словарь +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Значения извлекаются так же, как из списка, с той лишь разницей, +# что индекс — у словарей он называется ключом — не обязан быть числом +filled_dict["one"] #=> 1 + +# Все ключи в виде списка получаются с помощью метода keys(). +# Его вызов нужно обернуть в list(), так как обратно мы получаем +# итерируемый объект, о которых поговорим позднее. +list(filled_dict.keys()) # => ["three", "two", "one"] +# Замечание: сохранение порядка ключей в словаре не гарантируется +# Ваши результаты могут не совпадать с этими. + +# Все значения в виде списка можно получить с помощью values(). +# И снова нам нужно обернуть вызов в list(), чтобы превратить +# итерируемый объект в список. +list(filled_dict.values()) # => [3, 2, 1] +# То же самое замечание насчёт порядка ключей справедливо и здесь + +# При помощи оператора in можно проверять ключи на вхождение в словарь +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Попытка получить значение по несуществующему ключу выбросит ошибку ключа +filled_dict["four"] # KeyError + +# Чтобы избежать этого, используйте метод get() +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# Метод get также принимает аргумент по умолчанию, значение которого будет +# возвращено при отсутствии указанного ключа +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# Метод setdefault вставляет пару ключ-значение, только если такого ключа нет +filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5 +filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5 + +# Добавление элементов в словарь +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 # Другой способ добавления элементов + +# Удаляйте ключи из словаря с помощью оператора del +del filled_dict["one"] # Удаляет ключ «one» из словаря + + +# Множества содержат... ну, в общем, множества +empty_set = set() +# Инициализация множества набором значений. +# Да, оно выглядит примерно как словарь… ну извините, так уж вышло. +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Множеству можно назначать новую переменную +filled_set = some_set + +# Добавление новых элементов в множество +filled_set.add(5) # filled_set равно {1, 2, 3, 4, 5} + +# Пересечение множеств: & +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Объединение множеств: | +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Разность множеств: - +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Проверка на вхождение во множество: in +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Поток управления и итерируемые объекты +#################################################### + +# Для начала заведём переменную +some_var = 5 + +# Так выглядит выражение if. Отступы в python очень важны! +# результат: «some_var меньше, чем 10» +if some_var > 10: + print("some_var намного больше, чем 10.") +elif some_var < 10: # Выражение elif необязательно. + print("some_var меньше, чем 10.") +else: # Это тоже необязательно. + print("some_var равно 10.") + + +# Циклы For проходят по спискам. Результат: + # собака — это млекопитающее + # кошка — это млекопитающее + # мышь — это млекопитающее +for animal in ["собака", "кошка", "мышь"]: + # Можете использовать format() для интерполяции форматированных строк + print("{} — это млекопитающее".format(animal)) + +""" +«range(число)» возвращает список чисел +от нуля до заданного числа +Результат: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +Циклы while продолжаются до тех пор, пока указанное условие не станет ложным. +Результат: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Краткая запись для x = x + 1 + +# Обрабатывайте исключения блоками try/except +try: + # Чтобы выбросить ошибку, используется raise + raise IndexError("Это ошибка индекса") +except IndexError as e: + # pass — это просто отсутствие оператора. Обычно здесь происходит + # восстановление после ошибки. + pass +except (TypeError, NameError): + pass # Несколько исключений можно обработать вместе, если нужно. +else: # Необязательное выражение. Должно следовать за последним блоком except + print("Всё хорошо!") # Выполнится, только если не было никаких исключений + +# Python предоставляет фундаментальную абстракцию, +# которая называется итерируемым объектом (an iterable). +# Итерируемый объект — это объект, который воспринимается как последовательность. +# Объект, который возвратила функция range(), итерируемый. +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). Это объект, реализующий интерфейс iterable + +# Мы можем проходить по нему циклом. +for i in our_iterable: + print(i) # Выводит one, two, three + +# Но мы не можем обращаться к элементу по индексу. +our_iterable[1] # Выбрасывает ошибку типа + +# Итерируемый объект знает, как создавать итератор. +our_iterator = iter(our_iterable) + +# Итератор может запоминать состояние при проходе по объекту. +# Мы получаем следующий объект, вызывая функцию __next__. +our_iterator.__next__() #=> "one" + +# Он сохраняет состояние при вызове __next__. +our_iterator.__next__() #=> "two" +our_iterator.__next__() #=> "three" + +# Возвратив все данные, итератор выбрасывает исключение StopIterator +our_iterator.__next__() # Выбрасывает исключение остановки итератора + +# Вы можете получить сразу все элементы итератора, вызвав на нём функцию list(). +list(filled_dict.keys()) #=> Возвращает ["one", "two", "three"] + + +#################################################### +## 4. Функции +#################################################### + +# Используйте def для создания новых функций +def add(x, y): + print("x равен %s, а y равен %s" % (x, y)) + return x + y # Возвращайте результат с помощью ключевого слова return + +# Вызов функции с аргументами +add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвращает 11 + +# Другой способ вызова функции — вызов с именованными аргументами +add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке. + +# Вы можете определить функцию, принимающую переменное число аргументов +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# А также можете определить функцию, принимающую переменное число +# именованных аргументов +def keyword_args(**kwargs): + return kwargs + +# Вызовем эту функцию и посмотрим, что из этого получится +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Если хотите, можете использовать оба способа одновременно +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) выводит: + (1, 2) + {"a": 3, "b": 4} +""" + +# Вызывая функции, можете сделать наоборот! +# Используйте символ * для распаковки кортежей и ** для распаковки словарей +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # эквивалентно foo(1, 2, 3, 4) +all_the_args(**kwargs) # эквивалентно foo(a=3, b=4) +all_the_args(*args, **kwargs) # эквивалентно foo(1, 2, 3, 4, a=3, b=4) + +# Область определения функций +x = 5 + +def setX(num): + # Локальная переменная x — это не то же самое, что глобальная переменная x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # Глобальная переменная x теперь равна 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + +# В Python функции — «объекты первого класса» +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Также есть и анонимные функции +(lambda x: x > 2)(3) #=> True + +# Есть встроенные функции высшего порядка +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Для удобного отображения и фильтрации можно использовать списочные включения +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#################################################### +## 5. Классы +#################################################### + +# Чтобы получить класс, мы наследуемся от object. +class Human(object): + + # Атрибут класса. Он разделяется всеми экземплярами этого класса + species = "H. sapiens" + + # Обычный конструктор, вызывается при инициализации экземпляра класса + # Обратите внимание, что двойное подчёркивание в начале и в конце имени + # означает объекты и атрибуты, которые используются Python, но находятся + # в пространствах имён, управляемых пользователем. + # Не придумывайте им имена самостоятельно. + def __init__(self, name): + # Присваивание значения аргумента атрибуту класса name + self.name = name + + # Метод экземпляра. Все методы принимают self в качестве первого аргумента + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Метод класса разделяется между всеми экземплярами + # Они вызываются с указыванием вызывающего класса в качестве первого аргумента + @classmethod + def get_species(cls): + return cls.species + + # Статический метод вызывается без ссылки на класс или экземпляр + @staticmethod + def grunt(): + return "*grunt*" + + +# Инициализация экземпляра класса +i = Human(name="Иван") +print(i.say("привет")) # Выводит: «Иван: привет» + +j = Human("Пётр") +print(j.say("Привет")) # Выводит: «Пётр: привет» + +# Вызов метода класса +i.get_species() #=> "H. sapiens" + +# Изменение разделяемого атрибута +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Вызов статического метода +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Модули +#################################################### + +# Вы можете импортировать модули +import math +print(math.sqrt(16)) #=> 4.0 + +# Вы можете импортировать отдельные функции модуля +from math import ceil, floor +print(ceil(3.7)) #=> 4.0 +print(floor(3.7)) #=> 3.0 + +# Можете импортировать все функции модуля. +# (Хотя это и не рекомендуется) +from math import * + +# Можете сокращать имена модулей +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Модули в Python — это обычные Python-файлы. Вы +# можете писать свои модули и импортировать их. Название +# модуля совпадает с названием файла. + +# Вы можете узнать, какие функции и атрибуты определены +# в модуле +import math +dir(math) + +#################################################### +## 7. Дополнительно +#################################################### + +# Генераторы помогут выполнить ленивые вычисления +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Генератор создаёт значения на лету. +# Он не возвращает все значения разом, а создаёт каждое из них при каждой +# итерации. Это значит, что значения больше 15 в double_numbers +# обработаны не будут. +# Обратите внимание: range — это тоже генератор. +# Создание списка чисел от 1 до 900000000 требует много места и времени. +# Если нам нужно имя переменной, совпадающее с ключевым словом Python, +# мы используем подчёркивание в конце +range_ = range(1, 900000000) + +# Будет удваивать все числа, пока результат не превысит 30 +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Декораторы +# В этом примере beg оборачивает say +# Метод beg вызовет say. Если say_please равно True, +# он изменит возвращаемое сообщение +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, " Пожалуйста! У меня нет денег :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Вы не купите мне пива?" + return msg, say_please + + +print(say()) # Вы не купите мне пива? +print(say(say_please=True)) # Вы не купите мне пива? Пожалуйста! У меня нет денег :( + +``` + +## Хотите ещё? + +### Бесплатные онлайн-материалы + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [Официальная документация](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/3/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### Платные + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown deleted file mode 100644 index bf80fed2..00000000 --- a/ru-ru/python3-ru.html.markdown +++ /dev/null @@ -1,651 +0,0 @@ ---- -language: python3 -lang: ru-ru -contributors: - - ["Louie Dinh", "http://ldinh.ca"] - - ["Steven Basart", "http://github.com/xksteven"] -translators: - - ["Andre Polykanine", "https://github.com/Oire"] -filename: learnpython3-ru.py ---- - -Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из -самых популярных языков. Я влюбился в Python за понятный и доходчивый синтаксис — это -почти что исполняемый псевдокод. - -С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh) -или louiedinh [at] [почтовый сервис Google] - -Замечание: Эта статья относится только к Python 3. -Если вы хотите изучить Python 2.7, обратитесь к другой статье. - -```python -# Однострочные комментарии начинаются с символа решётки. -""" Многострочный текст может быть - записан, используя 3 знака " и обычно используется - в качестве встроенной документации -""" - -#################################################### -## 1. Примитивные типы данных и операторы -#################################################### - -# У вас есть числа -3 #=> 3 - -# Математика работает вполне ожидаемо -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 - -# Кроме деления, которое по умолчанию возвращает число с плавающей запятой -35 / 5 # => 7.0 - -# Результат целочисленного деления округляется в меньшую сторону -# как для положительных, так и для отрицательных чисел. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Когда вы используете числа с плавающей запятой, -# результатом будет также число с плавающей запятой -3 * 2.0 # => 6.0 - -# Остаток от деления -7 % 3 # => 1 - -# Возведение в степень -2**4 # => 16 - -# Приоритет операций указывается скобками -(1 + 3) * 2 #=> 8 - -# Для логических (булевых) значений существует отдельный примитивный тип -True -False - -# Для отрицания используется ключевое слово not -not True #=> False -not False #=> True - -# Логические операторы -# Обратите внимание: ключевые слова «and» и «or» чувствительны к регистру букв -True and False #=> False -False or True #=> True - -# Обратите внимание, что логические операторы используются и с целыми числами -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True - -# Равенство — это == -1 == 1 #=> True -2 == 1 #=> False - -# Неравенство — это != -1 != 1 #=> False -2 != 1 #=> True - -# Ещё немного сравнений -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True - -# Сравнения могут быть записаны цепочкой: -1 < 2 < 3 #=> True -2 < 3 < 2 #=> False - -# Строки определяются символом " или ' -"Это строка." -'Это тоже строка.' - -# И строки тоже могут складываться! Хотя лучше не злоупотребляйте этим. -"Привет " + "мир!" #=> "Привет мир!" - -# Строки можно умножать. -"aa" * 4 #=> "aaaaaaaa" - -# Со строкой можно работать, как со списком символов -"Это строка"[0] #=> 'Э' - -# Метод format используется для форматирования строк: -"{0} могут быть {1}".format("строки", "форматированы") - -# Вы можете повторять аргументы форматирования, чтобы меньше печатать. -"Ехал {0} через реку, видит {0} - в реке {1}! Сунул {0} руку в реку, {1} за руку греку цап!".format("грека", "рак") -#=> "Ехал грека через реку, видит грека - в реке рак! Сунул грека руку в реку, рак за руку греку цап!" -# Если вы не хотите считать, можете использовать ключевые слова. -"{name} хочет есть {food}".format(name="Боб", food="лазанью") - -# Если ваш код на Python 3 нужно запускать также и под Python 2.5 и ниже, -# вы также можете использовать старый способ форматирования: -"%s можно %s %s способом" % ("строки", "интерполировать", "старым") - -# None является объектом -None #=> None - -# Не используйте оператор равенства '==' для сравнения -# объектов с None. Используйте для этого 'is' -"etc" is None #=> False -None is None #=> True - -# Оператор «is» проверяет идентичность объектов. Он не -# очень полезен при работе с примитивными типами, но -# зато просто незаменим при работе с объектами. - -# None, 0 и пустые строки/списки/словари приводятся к False. -# Все остальные значения равны True -bool(0) # => False -bool("") # => False -bool([]) #=> False -bool({}) #=> False - - -#################################################### -## 2. Переменные и коллекции -#################################################### - -# В Python есть функция Print -print("Я Python. Приятно познакомиться!") - -# Объявлять переменные перед инициализацией не нужно. -# По соглашению используется нижний_регистр_с_подчёркиваниями -some_var = 5 -some_var #=> 5 - -# При попытке доступа к неинициализированной переменной -# выбрасывается исключение. -# Об исключениях см. раздел «Поток управления и итерируемые объекты». -some_unknown_var # Выбрасывает ошибку именования - -# Списки хранят последовательности -li = [] -# Можно сразу начать с заполненного списка -other_li = [4, 5, 6] - -# Объекты добавляются в конец списка методом append -li.append(1) # [1] -li.append(2) # [1, 2] -li.append(4) # [1, 2, 4] -li.append(3) # [1, 2, 4, 3] -# И удаляются с конца методом pop -li.pop() #=> возвращает 3 и li становится равен [1, 2, 4] -# Положим элемент обратно -li.append(3) # [1, 2, 4, 3]. - -# Обращайтесь со списком, как с обычным массивом -li[0] #=> 1 -# Обратимся к последнему элементу -li[-1] #=> 3 - -# Попытка выйти за границы массива приведёт к ошибке индекса -li[4] # Выдаёт IndexError - -# Можно обращаться к диапазону, используя так называемые срезы -# (Для тех, кто любит математику, это называется замкнуто-открытый интервал). -li[1:3] #=> [2, 4] -# Опускаем начало -li[2:] #=> [4, 3] -# Опускаем конец -li[:3] #=> [1, 2, 4] -# Выбираем каждый второй элемент -li[::2] # =>[1, 4] -# Переворачиваем список -li[::-1] # => [3, 4, 2, 1] -# Используйте сочетания всего вышеназванного для выделения более сложных срезов -# li[начало:конец:шаг] - -# Удаляем произвольные элементы из списка оператором del -del li[2] # [1, 2, 3] - -# Вы можете складывать, или, как ещё говорят, конкатенировать списки -# Обратите внимание: значения li и other_li при этом не изменились. -li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются - -# Объединять списки можно методом extend -li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6] - -# Проверить элемент на вхождение в список можно оператором in -1 in li #=> True - -# Длина списка вычисляется функцией len -len(li) #=> 6 - - -# Кортежи — это такие списки, только неизменяемые -tup = (1, 2, 3) -tup[0] #=> 1 -tup[0] = 3 # Выдаёт TypeError - -# Всё то же самое можно делать и с кортежами -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True - -# Вы можете распаковывать кортежи (или списки) в переменные -a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3 -# Кортежи создаются по умолчанию, если опущены скобки -d, e, f = 4, 5, 6 -# Обратите внимание, как легко поменять местами значения двух переменных -e, d = d, e # теперь d == 5, а e == 4 - - -# Словари содержат ассоциативные массивы -empty_dict = {} -# Вот так описывается предзаполненный словарь -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Значения извлекаются так же, как из списка, с той лишь разницей, -# что индекс — у словарей он называется ключом — не обязан быть числом -filled_dict["one"] #=> 1 - -# Все ключи в виде списка получаются с помощью метода keys(). -# Его вызов нужно обернуть в list(), так как обратно мы получаем -# итерируемый объект, о которых поговорим позднее. -list(filled_dict.keys()) # => ["three", "two", "one"] -# Замечание: сохранение порядка ключей в словаре не гарантируется -# Ваши результаты могут не совпадать с этими. - -# Все значения в виде списка можно получить с помощью values(). -# И снова нам нужно обернуть вызов в list(), чтобы превратить -# итерируемый объект в список. -list(filled_dict.values()) # => [3, 2, 1] -# То же самое замечание насчёт порядка ключей справедливо и здесь - -# При помощи оператора in можно проверять ключи на вхождение в словарь -"one" in filled_dict #=> True -1 in filled_dict #=> False - -# Попытка получить значение по несуществующему ключу выбросит ошибку ключа -filled_dict["four"] # KeyError - -# Чтобы избежать этого, используйте метод get() -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None -# Метод get также принимает аргумент по умолчанию, значение которого будет -# возвращено при отсутствии указанного ключа -filled_dict.get("one", 4) #=> 1 -filled_dict.get("four", 4) #=> 4 - -# Метод setdefault вставляет пару ключ-значение, только если такого ключа нет -filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5 -filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5 - -# Добавление элементов в словарь -filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} -#filled_dict["four"] = 4 # Другой способ добавления элементов - -# Удаляйте ключи из словаря с помощью оператора del -del filled_dict["one"] # Удаляет ключ «one» из словаря - - -# Множества содержат... ну, в общем, множества -empty_set = set() -# Инициализация множества набором значений. -# Да, оно выглядит примерно как словарь… ну извините, так уж вышло. -filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} - -# Множеству можно назначать новую переменную -filled_set = some_set - -# Добавление новых элементов в множество -filled_set.add(5) # filled_set равно {1, 2, 3, 4, 5} - -# Пересечение множеств: & -other_set = {3, 4, 5, 6} -filled_set & other_set #=> {3, 4, 5} - -# Объединение множеств: | -filled_set | other_set #=> {1, 2, 3, 4, 5, 6} - -# Разность множеств: - -{1,2,3,4} - {2,3,5} #=> {1, 4} - -# Проверка на вхождение во множество: in -2 in filled_set #=> True -10 in filled_set #=> False - - -#################################################### -## 3. Поток управления и итерируемые объекты -#################################################### - -# Для начала заведём переменную -some_var = 5 - -# Так выглядит выражение if. Отступы в python очень важны! -# результат: «some_var меньше, чем 10» -if some_var > 10: - print("some_var намного больше, чем 10.") -elif some_var < 10: # Выражение elif необязательно. - print("some_var меньше, чем 10.") -else: # Это тоже необязательно. - print("some_var равно 10.") - - -# Циклы For проходят по спискам. Результат: - # собака — это млекопитающее - # кошка — это млекопитающее - # мышь — это млекопитающее -for animal in ["собака", "кошка", "мышь"]: - # Можете использовать format() для интерполяции форматированных строк - print("{} — это млекопитающее".format(animal)) - -""" -«range(число)» возвращает список чисел -от нуля до заданного числа -Результат: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -Циклы while продолжаются до тех пор, пока указанное условие не станет ложным. -Результат: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Краткая запись для x = x + 1 - -# Обрабатывайте исключения блоками try/except -try: - # Чтобы выбросить ошибку, используется raise - raise IndexError("Это ошибка индекса") -except IndexError as e: - # pass — это просто отсутствие оператора. Обычно здесь происходит - # восстановление после ошибки. - pass -except (TypeError, NameError): - pass # Несколько исключений можно обработать вместе, если нужно. -else: # Необязательное выражение. Должно следовать за последним блоком except - print("Всё хорошо!") # Выполнится, только если не было никаких исключений - -# Python предоставляет фундаментальную абстракцию, -# которая называется итерируемым объектом (an iterable). -# Итерируемый объект — это объект, который воспринимается как последовательность. -# Объект, который возвратила функция range(), итерируемый. -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) #=> range(1,10). Это объект, реализующий интерфейс iterable - -# Мы можем проходить по нему циклом. -for i in our_iterable: - print(i) # Выводит one, two, three - -# Но мы не можем обращаться к элементу по индексу. -our_iterable[1] # Выбрасывает ошибку типа - -# Итерируемый объект знает, как создавать итератор. -our_iterator = iter(our_iterable) - -# Итератор может запоминать состояние при проходе по объекту. -# Мы получаем следующий объект, вызывая функцию __next__. -our_iterator.__next__() #=> "one" - -# Он сохраняет состояние при вызове __next__. -our_iterator.__next__() #=> "two" -our_iterator.__next__() #=> "three" - -# Возвратив все данные, итератор выбрасывает исключение StopIterator -our_iterator.__next__() # Выбрасывает исключение остановки итератора - -# Вы можете получить сразу все элементы итератора, вызвав на нём функцию list(). -list(filled_dict.keys()) #=> Возвращает ["one", "two", "three"] - - -#################################################### -## 4. Функции -#################################################### - -# Используйте def для создания новых функций -def add(x, y): - print("x равен %s, а y равен %s" % (x, y)) - return x + y # Возвращайте результат с помощью ключевого слова return - -# Вызов функции с аргументами -add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвращает 11 - -# Другой способ вызова функции — вызов с именованными аргументами -add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке. - -# Вы можете определить функцию, принимающую переменное число аргументов -def varargs(*args): - return args - -varargs(1, 2, 3) #=> (1,2,3) - - -# А также можете определить функцию, принимающую переменное число -# именованных аргументов -def keyword_args(**kwargs): - return kwargs - -# Вызовем эту функцию и посмотрим, что из этого получится -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} - -# Если хотите, можете использовать оба способа одновременно -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) выводит: - (1, 2) - {"a": 3, "b": 4} -""" - -# Вызывая функции, можете сделать наоборот! -# Используйте символ * для распаковки кортежей и ** для распаковки словарей -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # эквивалентно foo(1, 2, 3, 4) -all_the_args(**kwargs) # эквивалентно foo(a=3, b=4) -all_the_args(*args, **kwargs) # эквивалентно foo(1, 2, 3, 4, a=3, b=4) - -# Область определения функций -x = 5 - -def setX(num): - # Локальная переменная x — это не то же самое, что глобальная переменная x - x = num # => 43 - print (x) # => 43 - -def setGlobalX(num): - global x - print (x) # => 5 - x = num # Глобальная переменная x теперь равна 6 - print (x) # => 6 - -setX(43) -setGlobalX(6) - -# В Python функции — «объекты первого класса» -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) #=> 13 - -# Также есть и анонимные функции -(lambda x: x > 2)(3) #=> True - -# Есть встроенные функции высшего порядка -map(add_10, [1,2,3]) #=> [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] - -# Для удобного отображения и фильтрации можно использовать списочные включения -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] - -#################################################### -## 5. Классы -#################################################### - -# Чтобы получить класс, мы наследуемся от object. -class Human(object): - - # Атрибут класса. Он разделяется всеми экземплярами этого класса - species = "H. sapiens" - - # Обычный конструктор, вызывается при инициализации экземпляра класса - # Обратите внимание, что двойное подчёркивание в начале и в конце имени - # означает объекты и атрибуты, которые используются Python, но находятся - # в пространствах имён, управляемых пользователем. - # Не придумывайте им имена самостоятельно. - def __init__(self, name): - # Присваивание значения аргумента атрибуту класса name - self.name = name - - # Метод экземпляра. Все методы принимают self в качестве первого аргумента - def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) - - # Метод класса разделяется между всеми экземплярами - # Они вызываются с указыванием вызывающего класса в качестве первого аргумента - @classmethod - def get_species(cls): - return cls.species - - # Статический метод вызывается без ссылки на класс или экземпляр - @staticmethod - def grunt(): - return "*grunt*" - - -# Инициализация экземпляра класса -i = Human(name="Иван") -print(i.say("привет")) # Выводит: «Иван: привет» - -j = Human("Пётр") -print(j.say("Привет")) # Выводит: «Пётр: привет» - -# Вызов метода класса -i.get_species() #=> "H. sapiens" - -# Изменение разделяемого атрибута -Human.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" - -# Вызов статического метода -Human.grunt() #=> "*grunt*" - - -#################################################### -## 6. Модули -#################################################### - -# Вы можете импортировать модули -import math -print(math.sqrt(16)) #=> 4.0 - -# Вы можете импортировать отдельные функции модуля -from math import ceil, floor -print(ceil(3.7)) #=> 4.0 -print(floor(3.7)) #=> 3.0 - -# Можете импортировать все функции модуля. -# (Хотя это и не рекомендуется) -from math import * - -# Можете сокращать имена модулей -import math as m -math.sqrt(16) == m.sqrt(16) #=> True - -# Модули в Python — это обычные Python-файлы. Вы -# можете писать свои модули и импортировать их. Название -# модуля совпадает с названием файла. - -# Вы можете узнать, какие функции и атрибуты определены -# в модуле -import math -dir(math) - -#################################################### -## 7. Дополнительно -#################################################### - -# Генераторы помогут выполнить ленивые вычисления -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Генератор создаёт значения на лету. -# Он не возвращает все значения разом, а создаёт каждое из них при каждой -# итерации. Это значит, что значения больше 15 в double_numbers -# обработаны не будут. -# Обратите внимание: range — это тоже генератор. -# Создание списка чисел от 1 до 900000000 требует много места и времени. -# Если нам нужно имя переменной, совпадающее с ключевым словом Python, -# мы используем подчёркивание в конце -range_ = range(1, 900000000) - -# Будет удваивать все числа, пока результат не превысит 30 -for i in double_numbers(range_): - print(i) - if i >= 30: - break - - -# Декораторы -# В этом примере beg оборачивает say -# Метод beg вызовет say. Если say_please равно True, -# он изменит возвращаемое сообщение -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, " Пожалуйста! У меня нет денег :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Вы не купите мне пива?" - return msg, say_please - - -print(say()) # Вы не купите мне пива? -print(say(say_please=True)) # Вы не купите мне пива? Пожалуйста! У меня нет денег :( - -``` - -## Хотите ещё? - -### Бесплатные онлайн-материалы - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [Официальная документация](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/3/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) - -### Платные - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/tr-tr/python-tr.html.markdown b/tr-tr/python-tr.html.markdown new file mode 100644 index 00000000..b78d517f --- /dev/null +++ b/tr-tr/python-tr.html.markdown @@ -0,0 +1,640 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Batuhan Osman T.", "https://github.com/BTaskaya"] +translators: + - ["Eray AYDIN", "http://erayaydin.me/"] +lang: tr-tr +filename: learnpython3-tr.py +--- + +Python,90ların başlarında Guido Van Rossum tarafından oluşturulmuştur. En popüler olan dillerden biridir. Beni Python'a aşık eden sebep onun syntax beraklığı. Çok basit bir çalıştırılabilir söz koddur. + +Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [burayı](http://learnxinyminutes.com/docs/python/) kontrol edebilirsiniz. + +```python + +# Tek satırlık yorum satırı kare(#) işareti ile başlamaktadır. + +""" Çok satırlı olmasını istediğiniz yorumlar + üç adet tırnak(") işareti ile + yapılmaktadır +""" + +#################################################### +## 1. Temel Veri Türleri ve Operatörler +#################################################### + +# Sayılar +3 # => 3 + +# Tahmin edebileceğiniz gibi matematik +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Bölme işlemi varsayılan olarak onluk döndürür +35 / 5 # => 7.0 + +# Tam sayı bölmeleri, pozitif ve negatif sayılar için aşağıya yuvarlar +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # onluklar için de bu böyledir +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Onluk kullanırsanız, sonuç da onluk olur +3 * 2.0 # => 6.0 + +# Kalan operatörü +7 % 3 # => 1 + +# Üs (2 üzeri 4) +2**4 # => 16 + +# Parantez ile önceliği değiştirebilirsiniz +(1 + 3) * 2 # => 8 + +# Boolean(Doğru-Yanlış) değerleri standart +True +False + +# 'değil' ile terse çevirme +not True # => False +not False # => True + +# Boolean Operatörleri +# "and" ve "or" büyük küçük harf duyarlıdır +True and False #=> False +False or True #=> True + +# Bool operatörleri ile sayı kullanımı +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Eşitlik kontrolü == +1 == 1 # => True +2 == 1 # => False + +# Eşitsizlik Kontrolü != +1 != 1 # => False +2 != 1 # => True + +# Diğer karşılaştırmalar +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Zincirleme şeklinde karşılaştırma da yapabilirsiniz! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Yazı(Strings) " veya ' işaretleri ile oluşturulabilir +"Bu bir yazı." +'Bu da bir yazı.' + +# Yazılar da eklenebilir! Fakat bunu yapmanızı önermem. +"Merhaba " + "dünya!" # => "Merhaba dünya!" + +# Bir yazı(string) karakter listesi gibi işlenebilir +"Bu bir yazı"[0] # => 'B' + +# .format ile yazıyı biçimlendirebilirsiniz, şu şekilde: +"{} da ayrıca {}".format("yazılar", "işlenebilir") + +# Biçimlendirme işleminde aynı argümanı da birden fazla kullanabilirsiniz. +"{0} çeviktir, {0} hızlıdır, {0} , {1} üzerinden atlayabilir".format("Ahmet", "şeker çubuğu") +#=> "Ahmet çeviktir, Ahmet hızlıdır, Ahmet , şeker çubuğu üzerinden atlayabilir" + +# Argümanın sırasını saymak istemiyorsanız, anahtar kelime kullanabilirsiniz. +"{isim} yemek olarak {yemek} istiyor".format(isim="Ahmet", yemek="patates") #=> "Ahmet yemek olarak patates istiyor" + +# Eğer Python 3 kodunuz ayrıca Python 2.5 ve üstünde çalışmasını istiyorsanız, +# eski stil formatlamayı kullanabilirsiniz: +"%s bu %s yolla da %s" % ("yazılar", "eski", "biçimlendirilebilir") + + +# Hiçbir şey(none) da bir objedir +None # => None + +# Bir değerin none ile eşitlik kontrolü için "==" sembolünü kullanmayın +# Bunun yerine "is" kullanın. Obje türünün eşitliğini kontrol edecektir. +"vb" is None # => False +None is None # => True + +# None, 0, ve boş yazılar/listeler/sözlükler hepsi False değeri döndürü. +# Diğer veriler ise True değeri döndürür +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Değişkenler ve Koleksiyonlar +#################################################### + +# Python bir yazdırma fonksiyonuna sahip +print("Ben Python. Tanıştığıma memnun oldum!") + +# Değişkenlere veri atamak için önce değişkeni oluşturmanıza gerek yok. +# Düzenli bir değişken için hepsi_kucuk_ve_alt_cizgi_ile_ayirin +bir_degisken = 5 +bir_degisken # => 5 + +# Önceden tanımlanmamış değişkene erişmek hata oluşturacaktır. +# Kontrol akışları başlığından hata kontrolünü öğrenebilirsiniz. +bir_bilinmeyen_degisken # NameError hatası oluşturur + +# Listeler ile sıralamaları tutabilirsiniz +li = [] +# Önceden doldurulmuş listeler ile başlayabilirsiniz +diger_li = [4, 5, 6] + +# 'append' ile listenin sonuna ekleme yapabilirsiniz +li.append(1) # li artık [1] oldu +li.append(2) # li artık [1, 2] oldu +li.append(4) # li artık [1, 2, 4] oldu +li.append(3) # li artık [1, 2, 4, 3] oldu +# 'pop' ile listenin son elementini kaldırabilirsiniz +li.pop() # => 3 ve li artık [1, 2, 4] +# Çıkarttığımız tekrardan ekleyelim +li.append(3) # li yeniden [1, 2, 4, 3] oldu. + +# Dizi gibi listeye erişim sağlayın +li[0] # => 1 +# Son elemente bakın +li[-1] # => 3 + +# Listede olmayan bir elemente erişim sağlamaya çalışmak IndexError hatası oluşturur +li[4] # IndexError hatası oluşturur + +# Bir kısmını almak isterseniz. +li[1:3] # => [2, 4] +# Başlangıç belirtmezseniz +li[2:] # => [4, 3] +# Sonu belirtmesseniz +li[:3] # => [1, 2, 4] +# Her ikişer objeyi seçme +li[::2] # =>[1, 4] +# Listeyi tersten almak +li[::-1] # => [3, 4, 2, 1] +# Kombinasyonları kullanarak gelişmiş bir şekilde listenin bir kısmını alabilirsiniz +# li[baslangic:son:adim] + +# "del" ile isteğe bağlı, elementleri listeden kaldırabilirsiniz +del li[2] # li artık [1, 2, 3] oldu + +# Listelerde de ekleme yapabilirsiniz +# Not: değerler üzerinde değişiklik yapılmaz. +li + diger_li # => [1, 2, 3, 4, 5, 6] + +# Listeleri birbirine bağlamak için "extend()" kullanılabilir +li.extend(diger_li) # li artık [1, 2, 3, 4, 5, 6] oldu + +# Listedeki bir elementin olup olmadığı kontrolü "in" ile yapılabilir +1 in li # => True + +# Uzunluğu öğrenmek için "len()" kullanılabilir +len(li) # => 6 + + +# Tüpler listeler gibidir fakat değiştirilemez. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # TypeError hatası oluşturur + +# Diğer liste işlemlerini tüplerde de uygulayabilirsiniz +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Tüpleri(veya listeleri) değişkenlere açabilirsiniz +a, b, c = (1, 2, 3) # 'a' artık 1, 'b' artık 2 ve 'c' artık 3 +# Eğer parantez kullanmazsanız varsayılan oalrak tüpler oluşturulur +d, e, f = 4, 5, 6 +# 2 değeri birbirine değiştirmek bu kadar kolay +e, d = d, e # 'd' artık 5 ve 'e' artık 4 + + +# Sözlükler anahtar kodlarla verileri tutar +bos_sozl = {} +# Önceden doldurulmuş sözlük oluşturma +dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} + +# Değere bakmak için [] kullanalım +dolu_sozl["bir"] # => 1 + +# Bütün anahtarları almak için "keys()" kullanılabilir. +# Listelemek için list() kullanacağınız çünkü dönen değerin işlenmesi gerekiyor. Bu konuya daha sonra değineceğiz. +# Not - Sözlük anahtarlarının sıralaması kesin değildir. +# Beklediğiniz çıktı sizinkiyle tam uyuşmuyor olabilir. +list(dolu_sozl.keys()) # => ["uc", "iki", "bir"] + + +# Tüm değerleri almak için "values()" kullanacağız. Dönen değeri biçimlendirmek için de list() kullanmamız gerekiyor +# Not - Sıralama değişebilir. +list(dolu_sozl.values()) # => [3, 2, 1] + + +# Bir anahtarın sözlükte olup olmadığını "in" ile kontrol edebilirsiniz +"bir" in dolu_sozl # => True +1 in dolu_sozl # => False + +# Olmayan bir anahtardan değer elde etmek isterseniz KeyError sorunu oluşacaktır. +dolu_sozl["dort"] # KeyError hatası oluşturur + +# "get()" metodu ile değeri almaya çalışırsanız KeyError sorunundan kurtulursunuz +dolu_sozl.get("bir") # => 1 +dolu_sozl.get("dort") # => None +# "get" metoduna parametre belirterek değerin olmaması durumunda varsayılan bir değer döndürebilirsiniz. +dolu_sozl.get("bir", 4) # => 1 +dolu_sozl.get("dort", 4) # => 4 + +# "setdefault()" metodu sözlükte, belirttiğiniz anahtarın [olmaması] durumunda varsayılan bir değer atayacaktır +dolu_sozl.setdefault("bes", 5) # dolu_sozl["bes"] artık 5 değerine sahip +dolu_sozl.setdefault("bes", 6) # dolu_sozl["bes"] değişmedi, hala 5 değerine sahip + +# Sözlüğe ekleme +dolu_sozl.update({"dort":4}) #=> {"bir": 1, "iki": 2, "uc": 3, "dort": 4} +#dolu_sozl["dort"] = 4 #sözlüğe eklemenin bir diğer yolu + +# Sözlükten anahtar silmek için 'del' kullanılabilir +del dolu_sozl["bir"] # "bir" anahtarını dolu sözlükten silecektir + + +# Setler ... set işte :D +bos_set = set() +# Seti bir veri listesi ile de oluşturabilirsiniz. Evet, biraz sözlük gibi duruyor. Üzgünüm. +bir_set = {1, 1, 2, 2, 3, 4} # bir_set artık {1, 2, 3, 4} + +# Sete yeni setler ekleyebilirsiniz +dolu_set = bir_set + +# Sete bir diğer öğe ekleme +dolu_set.add(5) # dolu_set artık {1, 2, 3, 4, 5} oldu + +# Setlerin çakışan kısımlarını almak için '&' kullanabilirsiniz +diger_set = {3, 4, 5, 6} +dolu_set & diger_set # => {3, 4, 5} + +# '|' ile aynı olan elementleri almayacak şekilde setleri birleştirebilirsiniz +dolu_set | diger_set # => {1, 2, 3, 4, 5, 6} + +# Farklılıkları almak için "-" kullanabilirsiniz +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Bir değerin olup olmadığının kontrolü için "in" kullanılabilir +2 in dolu_set # => True +10 in dolu_set # => False + + +#################################################### +## 3. Kontrol Akışları ve Temel Soyutlandırma +#################################################### + +# Bir değişken oluşturalım +bir_degisken = 5 + +# Burada bir "if" ifadesi var. Girinti(boşluk,tab) python için önemlidir! +# çıktı olarak "bir_degisken 10 dan küçük" yazar +if bir_degisken > 10: + print("bir_degisken 10 dan büyük") +elif bir_degisken < 10: # Bu 'elif' ifadesi zorunlu değildir. + print("bir_degisken 10 dan küçük") +else: # Bu ifade de zorunlu değil. + print("bir_degisken değeri 10") + + +""" +Döngülerle lsiteleri döngüye alabilirsiniz +çıktı: + köpek bir memeli hayvandır + kedi bir memeli hayvandır + fare bir memeli hayvandır +""" +for hayvan in ["köpek", "kedi, "fare"]: + # format ile kolayca yazıyı biçimlendirelim + print("{} bir memeli hayvandır".format(hayvan)) + +""" +"range(sayi)" bir sayı listesi döndür +0'dan belirttiğiniz sayıyıa kadar +çıktı: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +'While' döngüleri koşul çalıştıkça işlemleri gerçekleştirir. +çıktı: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Uzun hali x = x + 1 + +# Hataları kontrol altına almak için try/except bloklarını kullanabilirsiniz +try: + # Bir hata oluşturmak için "raise" kullanabilirsiniz + raise IndexError("Bu bir index hatası") +except IndexError as e: + pass # Önemsiz, devam et. +except (TypeError, NameError): + pass # Çoklu bir şekilde hataları kontrol edebilirsiniz, tabi gerekirse. +else: # İsteğe bağlı bir kısım. Eğer hiçbir hata kontrol mekanizması desteklemiyorsa bu blok çalışacaktır + print("Her şey iyi!") # IndexError, TypeError ve NameError harici bir hatada bu blok çalıştı + +# Temel Soyutlandırma, bir objenin işlenmiş halidir. +# Aşağıdaki örnekte; Obje, range fonksiyonuna temel soyutlandırma gönderdi. + +dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} +temel_soyut = dolu_sozl.keys() +print(temel_soyut) #=> range(1,10). Bu obje temel soyutlandırma arayüzü ile oluşturuldu + +# Temel Soyutlandırılmış objeyi döngüye sokabiliriz. +for i in temel_soyut: + print(i) # Çıktısı: bir, iki, uc + +# Fakat, elementin anahtarına değerine. +temel_soyut[1] # TypeError hatası! + +# 'iterable' bir objenin nasıl temel soyutlandırıldığıdır. +iterator = iter(temel_soyut) + +# 'iterator' o obje üzerinde yaptığımız değişiklikleri hatırlayacaktır +# Bir sonraki objeyi almak için __next__ fonksiyonunu kullanabilirsiniz. +iterator.__next__() #=> "bir" + +# Bir önceki __next__ fonksiyonumuzu hatırlayıp bir sonraki kullanımda bu sefer ondan bir sonraki objeyi döndürecektir +iterator.__next__() #=> "iki" +iterator.__next__() #=> "uc" + +# Bütün nesneleri aldıktan sonra bir daha __next__ kullanımınızda, StopIterator hatası oluşturacaktır. +iterator.__next__() # StopIteration hatası + +# iterator'deki tüm nesneleri almak için list() kullanabilirsiniz. +list(dolu_sozl.keys()) #=> Returns ["bir", "iki", "uc"] + + +#################################################### +## 4. Fonksiyonlar +#################################################### + +# "def" ile yeni fonksiyonlar oluşturabilirsiniz +def topla(x, y): + print("x = {} ve y = {}".format(x, y)) + return x + y # Değer döndürmek için 'return' kullanmalısınız + +# Fonksiyonu parametleri ile çağırıyoruz +topla(5, 6) # => çıktı "x = 5 ve y = 6" ve değer olarak 11 döndürür + +# Bir diğer fonksiyon çağırma yöntemi de anahtar değerleri ile belirtmek +topla(y=6, x=5) # Anahtar değeri belirttiğiniz için parametre sıralaması önemsiz. + +# Sınırsız sayıda argüman da alabilirsiniz +def argumanlar(*argumanlar): + return argumanlar + +argumanlar(1, 2, 3) # => (1, 2, 3) + +# Parametrelerin anahtar değerlerini almak isterseniz +def anahtar_par(**anahtarlar): + return anahtar + +# Çalıştırdığımızda +anahtar_par(anah1="deg1", anah2="deg2") # => {"anah1": "deg1", "anah2": "deg2"} + + +# İsterseniz, bu ikisini birden kullanabilirsiniz +def tum_argumanlar(*argumanlar, **anahtarla): + print(argumanlar) + print(anahtarla) +""" +tum_argumanlar(1, 2, a=3, b=4) çıktı: + (1, 2) + {"a": 3, "b": 4} +""" + +# Fonksiyonu çağırırken de aynısını kullanabilirsiniz +argumanlar = (1, 2, 3, 4) +anahtarla = {"a": 3, "b": 4} +tum_argumanlar(*argumanlar) # = foo(1, 2, 3, 4) +tum_argumanlar(**anahtarla) # = foo(a=3, b=4) +tum_argumanlar(*argumanlar, **anahtarla) # = foo(1, 2, 3, 4, a=3, b=4) + + +# Fonksiyonlarda kullanacağımız bir değişken oluşturalım +x = 5 + +def belirleX(sayi): + # Fonksiyon içerisindeki x ile global tanımladığımız x aynı değil + x = sayi # => 43 + print (x) # => 43 + +def globalBelirleX(sayi): + global x + print (x) # => 5 + x = sayi # global olan x değişkeni artık 6 + print (x) # => 6 + +belirleX(43) +globalBelirleX(6) + + +# Sınıf fonksiyonları oluşturma +def toplama_olustur(x): + def topla(y): + return x + y + return topla + +ekle_10 = toplama_olustur(10) +ekle_10(3) # => 13 + +# Bilinmeyen fonksiyon +(lambda x: x > 2)(3) # => True + +# TODO - Fix for iterables +# Belirli sayıdan yükseğini alma fonksiyonu +map(ekle_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Filtreleme işlemi için liste comprehensions da kullanabiliriz +[ekle_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Sınıflar +#################################################### + + +# Sınıf oluşturmak için objeden alt sınıf oluşturacağız. +class Insan(object): + + # Sınıf değeri. Sınıfın tüm nesneleri tarafından kullanılabilir + tur = "H. sapiens" + + # Basit başlatıcı, Sınıf çağrıldığında tetiklenecektir. + # Dikkat edin, iki adet alt çizgi(_) bulunmakta. Bunlar + # python tarafından tanımlanan isimlerdir. + # Kendinize ait bir fonksiyon oluştururken __fonksiyon__ kullanmayınız! + def __init__(self, isim): + # Parametreyi sınıfın değerine atayalım + self.isim = isim + + # Bir metot. Bütün metotlar ilk parametre olarak "self "alır. + def soyle(self, mesaj): + return "{isim}: {mesaj}".format(isim=self.isim, mesaj=mesaj) + + # Bir sınıf metotu bütün nesnelere paylaştırılır + # İlk parametre olarak sınıf alırlar + @classmethod + def getir_tur(snf): + return snf.tur + + # Bir statik metot, sınıf ve nesnesiz çağrılır + @staticmethod + def grunt(): + return "*grunt*" + + +# Sınıfı çağıralım +i = Insan(isim="Ahmet") +print(i.soyle("merhaba")) # çıktı "Ahmet: merhaba" + +j = Insan("Ali") +print(j.soyle("selam")) # çıktı "Ali: selam" + +# Sınıf metodumuzu çağıraim +i.getir_tur() # => "H. sapiens" + +# Paylaşılan değeri değiştirelim +Insan.tur = "H. neanderthalensis" +i.getir_tur() # => "H. neanderthalensis" +j.getir_tur() # => "H. neanderthalensis" + +# Statik metodumuzu çağıralım +Insan.grunt() # => "*grunt*" + + +#################################################### +## 6. Moduller +#################################################### + +# Modülleri içe aktarabilirsiniz +import math +print(math.sqrt(16)) # => 4.0 + +# Modülden belirli bir fonksiyonları alabilirsiniz +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Modüldeki tüm fonksiyonları içe aktarabilirsiniz +# Dikkat: bunu yapmanızı önermem. +from math import * + +# Modül isimlerini değiştirebilirsiniz. +# Not: Modül ismini kısaltmanız çok daha iyi olacaktır +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python modulleri aslında birer python dosyalarıdır. +# İsterseniz siz de yazabilir ve içe aktarabilirsiniz Modulün +# ismi ile dosyanın ismi aynı olacaktır. + +# Moduldeki fonksiyon ve değerleri öğrenebilirsiniz. +import math +dir(math) + + +#################################################### +## 7. Gelişmiş +#################################################### + +# Oluşturucular uzun uzun kod yazmamanızı sağlayacak ve yardımcı olacaktır +def kare_sayilar(nesne): + for i in nesne: + yield i + i + +# Bir oluşturucu(generator) değerleri anında oluşturur. +# Bir seferde tüm değerleri oluşturup göndermek yerine teker teker her oluşumdan +# sonra geri döndürür. Bu demektir ki, kare_sayilar fonksiyonumuzda 15'ten büyük +# değerler işlenmeyecektir. +# Not: range() da bir oluşturucu(generator)dur. 1-900000000 arası bir liste yapmaya çalıştığınızda +# çok fazla vakit alacaktır. +# Python tarafından belirlenen anahtar kelimelerden kaçınmak için basitçe alt çizgi(_) kullanılabilir. +range_ = range(1, 900000000) +# kare_sayilar'dan dönen değer 30'a ulaştığında durduralım +for i in kare_sayilar(range_): + print(i) + if i >= 30: + break + + +# Dekoratörler +# Bu örnekte, +# Eğer lutfen_soyle True ise dönen değer değişecektir. +from functools import wraps + + +def yalvar(hedef_fonksiyon): + @wraps(hedef_fonksiyon) + def metot(*args, **kwargs): + msj, lutfen_soyle = hedef_fonksiyon(*args, **kwargs) + if lutfen_soyle: + return "{} {}".format(msj, "Lütfen! Artık dayanamıyorum :(") + return msj + + return metot + + +@yalvar +def soyle(lutfen_soyle=False): + msj = "Bana soda alır mısın?" + return msj, lutfen_soyle + + +print(soyle()) # Bana soda alır mısın? +print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayanamıyorum :( +``` + +## Daha Fazlasına Hazır Mısınız? + +### Ücretsiz Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) + +### Kitaplar + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown deleted file mode 100644 index b78d517f..00000000 --- a/tr-tr/python3-tr.html.markdown +++ /dev/null @@ -1,640 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Batuhan Osman T.", "https://github.com/BTaskaya"] -translators: - - ["Eray AYDIN", "http://erayaydin.me/"] -lang: tr-tr -filename: learnpython3-tr.py ---- - -Python,90ların başlarında Guido Van Rossum tarafından oluşturulmuştur. En popüler olan dillerden biridir. Beni Python'a aşık eden sebep onun syntax beraklığı. Çok basit bir çalıştırılabilir söz koddur. - -Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [burayı](http://learnxinyminutes.com/docs/python/) kontrol edebilirsiniz. - -```python - -# Tek satırlık yorum satırı kare(#) işareti ile başlamaktadır. - -""" Çok satırlı olmasını istediğiniz yorumlar - üç adet tırnak(") işareti ile - yapılmaktadır -""" - -#################################################### -## 1. Temel Veri Türleri ve Operatörler -#################################################### - -# Sayılar -3 # => 3 - -# Tahmin edebileceğiniz gibi matematik -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 - -# Bölme işlemi varsayılan olarak onluk döndürür -35 / 5 # => 7.0 - -# Tam sayı bölmeleri, pozitif ve negatif sayılar için aşağıya yuvarlar -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # onluklar için de bu böyledir --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Onluk kullanırsanız, sonuç da onluk olur -3 * 2.0 # => 6.0 - -# Kalan operatörü -7 % 3 # => 1 - -# Üs (2 üzeri 4) -2**4 # => 16 - -# Parantez ile önceliği değiştirebilirsiniz -(1 + 3) * 2 # => 8 - -# Boolean(Doğru-Yanlış) değerleri standart -True -False - -# 'değil' ile terse çevirme -not True # => False -not False # => True - -# Boolean Operatörleri -# "and" ve "or" büyük küçük harf duyarlıdır -True and False #=> False -False or True #=> True - -# Bool operatörleri ile sayı kullanımı -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True - -# Eşitlik kontrolü == -1 == 1 # => True -2 == 1 # => False - -# Eşitsizlik Kontrolü != -1 != 1 # => False -2 != 1 # => True - -# Diğer karşılaştırmalar -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Zincirleme şeklinde karşılaştırma da yapabilirsiniz! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# Yazı(Strings) " veya ' işaretleri ile oluşturulabilir -"Bu bir yazı." -'Bu da bir yazı.' - -# Yazılar da eklenebilir! Fakat bunu yapmanızı önermem. -"Merhaba " + "dünya!" # => "Merhaba dünya!" - -# Bir yazı(string) karakter listesi gibi işlenebilir -"Bu bir yazı"[0] # => 'B' - -# .format ile yazıyı biçimlendirebilirsiniz, şu şekilde: -"{} da ayrıca {}".format("yazılar", "işlenebilir") - -# Biçimlendirme işleminde aynı argümanı da birden fazla kullanabilirsiniz. -"{0} çeviktir, {0} hızlıdır, {0} , {1} üzerinden atlayabilir".format("Ahmet", "şeker çubuğu") -#=> "Ahmet çeviktir, Ahmet hızlıdır, Ahmet , şeker çubuğu üzerinden atlayabilir" - -# Argümanın sırasını saymak istemiyorsanız, anahtar kelime kullanabilirsiniz. -"{isim} yemek olarak {yemek} istiyor".format(isim="Ahmet", yemek="patates") #=> "Ahmet yemek olarak patates istiyor" - -# Eğer Python 3 kodunuz ayrıca Python 2.5 ve üstünde çalışmasını istiyorsanız, -# eski stil formatlamayı kullanabilirsiniz: -"%s bu %s yolla da %s" % ("yazılar", "eski", "biçimlendirilebilir") - - -# Hiçbir şey(none) da bir objedir -None # => None - -# Bir değerin none ile eşitlik kontrolü için "==" sembolünü kullanmayın -# Bunun yerine "is" kullanın. Obje türünün eşitliğini kontrol edecektir. -"vb" is None # => False -None is None # => True - -# None, 0, ve boş yazılar/listeler/sözlükler hepsi False değeri döndürü. -# Diğer veriler ise True değeri döndürür -bool(0) # => False -bool("") # => False -bool([]) #=> False -bool({}) #=> False - - -#################################################### -## 2. Değişkenler ve Koleksiyonlar -#################################################### - -# Python bir yazdırma fonksiyonuna sahip -print("Ben Python. Tanıştığıma memnun oldum!") - -# Değişkenlere veri atamak için önce değişkeni oluşturmanıza gerek yok. -# Düzenli bir değişken için hepsi_kucuk_ve_alt_cizgi_ile_ayirin -bir_degisken = 5 -bir_degisken # => 5 - -# Önceden tanımlanmamış değişkene erişmek hata oluşturacaktır. -# Kontrol akışları başlığından hata kontrolünü öğrenebilirsiniz. -bir_bilinmeyen_degisken # NameError hatası oluşturur - -# Listeler ile sıralamaları tutabilirsiniz -li = [] -# Önceden doldurulmuş listeler ile başlayabilirsiniz -diger_li = [4, 5, 6] - -# 'append' ile listenin sonuna ekleme yapabilirsiniz -li.append(1) # li artık [1] oldu -li.append(2) # li artık [1, 2] oldu -li.append(4) # li artık [1, 2, 4] oldu -li.append(3) # li artık [1, 2, 4, 3] oldu -# 'pop' ile listenin son elementini kaldırabilirsiniz -li.pop() # => 3 ve li artık [1, 2, 4] -# Çıkarttığımız tekrardan ekleyelim -li.append(3) # li yeniden [1, 2, 4, 3] oldu. - -# Dizi gibi listeye erişim sağlayın -li[0] # => 1 -# Son elemente bakın -li[-1] # => 3 - -# Listede olmayan bir elemente erişim sağlamaya çalışmak IndexError hatası oluşturur -li[4] # IndexError hatası oluşturur - -# Bir kısmını almak isterseniz. -li[1:3] # => [2, 4] -# Başlangıç belirtmezseniz -li[2:] # => [4, 3] -# Sonu belirtmesseniz -li[:3] # => [1, 2, 4] -# Her ikişer objeyi seçme -li[::2] # =>[1, 4] -# Listeyi tersten almak -li[::-1] # => [3, 4, 2, 1] -# Kombinasyonları kullanarak gelişmiş bir şekilde listenin bir kısmını alabilirsiniz -# li[baslangic:son:adim] - -# "del" ile isteğe bağlı, elementleri listeden kaldırabilirsiniz -del li[2] # li artık [1, 2, 3] oldu - -# Listelerde de ekleme yapabilirsiniz -# Not: değerler üzerinde değişiklik yapılmaz. -li + diger_li # => [1, 2, 3, 4, 5, 6] - -# Listeleri birbirine bağlamak için "extend()" kullanılabilir -li.extend(diger_li) # li artık [1, 2, 3, 4, 5, 6] oldu - -# Listedeki bir elementin olup olmadığı kontrolü "in" ile yapılabilir -1 in li # => True - -# Uzunluğu öğrenmek için "len()" kullanılabilir -len(li) # => 6 - - -# Tüpler listeler gibidir fakat değiştirilemez. -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # TypeError hatası oluşturur - -# Diğer liste işlemlerini tüplerde de uygulayabilirsiniz -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Tüpleri(veya listeleri) değişkenlere açabilirsiniz -a, b, c = (1, 2, 3) # 'a' artık 1, 'b' artık 2 ve 'c' artık 3 -# Eğer parantez kullanmazsanız varsayılan oalrak tüpler oluşturulur -d, e, f = 4, 5, 6 -# 2 değeri birbirine değiştirmek bu kadar kolay -e, d = d, e # 'd' artık 5 ve 'e' artık 4 - - -# Sözlükler anahtar kodlarla verileri tutar -bos_sozl = {} -# Önceden doldurulmuş sözlük oluşturma -dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} - -# Değere bakmak için [] kullanalım -dolu_sozl["bir"] # => 1 - -# Bütün anahtarları almak için "keys()" kullanılabilir. -# Listelemek için list() kullanacağınız çünkü dönen değerin işlenmesi gerekiyor. Bu konuya daha sonra değineceğiz. -# Not - Sözlük anahtarlarının sıralaması kesin değildir. -# Beklediğiniz çıktı sizinkiyle tam uyuşmuyor olabilir. -list(dolu_sozl.keys()) # => ["uc", "iki", "bir"] - - -# Tüm değerleri almak için "values()" kullanacağız. Dönen değeri biçimlendirmek için de list() kullanmamız gerekiyor -# Not - Sıralama değişebilir. -list(dolu_sozl.values()) # => [3, 2, 1] - - -# Bir anahtarın sözlükte olup olmadığını "in" ile kontrol edebilirsiniz -"bir" in dolu_sozl # => True -1 in dolu_sozl # => False - -# Olmayan bir anahtardan değer elde etmek isterseniz KeyError sorunu oluşacaktır. -dolu_sozl["dort"] # KeyError hatası oluşturur - -# "get()" metodu ile değeri almaya çalışırsanız KeyError sorunundan kurtulursunuz -dolu_sozl.get("bir") # => 1 -dolu_sozl.get("dort") # => None -# "get" metoduna parametre belirterek değerin olmaması durumunda varsayılan bir değer döndürebilirsiniz. -dolu_sozl.get("bir", 4) # => 1 -dolu_sozl.get("dort", 4) # => 4 - -# "setdefault()" metodu sözlükte, belirttiğiniz anahtarın [olmaması] durumunda varsayılan bir değer atayacaktır -dolu_sozl.setdefault("bes", 5) # dolu_sozl["bes"] artık 5 değerine sahip -dolu_sozl.setdefault("bes", 6) # dolu_sozl["bes"] değişmedi, hala 5 değerine sahip - -# Sözlüğe ekleme -dolu_sozl.update({"dort":4}) #=> {"bir": 1, "iki": 2, "uc": 3, "dort": 4} -#dolu_sozl["dort"] = 4 #sözlüğe eklemenin bir diğer yolu - -# Sözlükten anahtar silmek için 'del' kullanılabilir -del dolu_sozl["bir"] # "bir" anahtarını dolu sözlükten silecektir - - -# Setler ... set işte :D -bos_set = set() -# Seti bir veri listesi ile de oluşturabilirsiniz. Evet, biraz sözlük gibi duruyor. Üzgünüm. -bir_set = {1, 1, 2, 2, 3, 4} # bir_set artık {1, 2, 3, 4} - -# Sete yeni setler ekleyebilirsiniz -dolu_set = bir_set - -# Sete bir diğer öğe ekleme -dolu_set.add(5) # dolu_set artık {1, 2, 3, 4, 5} oldu - -# Setlerin çakışan kısımlarını almak için '&' kullanabilirsiniz -diger_set = {3, 4, 5, 6} -dolu_set & diger_set # => {3, 4, 5} - -# '|' ile aynı olan elementleri almayacak şekilde setleri birleştirebilirsiniz -dolu_set | diger_set # => {1, 2, 3, 4, 5, 6} - -# Farklılıkları almak için "-" kullanabilirsiniz -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Bir değerin olup olmadığının kontrolü için "in" kullanılabilir -2 in dolu_set # => True -10 in dolu_set # => False - - -#################################################### -## 3. Kontrol Akışları ve Temel Soyutlandırma -#################################################### - -# Bir değişken oluşturalım -bir_degisken = 5 - -# Burada bir "if" ifadesi var. Girinti(boşluk,tab) python için önemlidir! -# çıktı olarak "bir_degisken 10 dan küçük" yazar -if bir_degisken > 10: - print("bir_degisken 10 dan büyük") -elif bir_degisken < 10: # Bu 'elif' ifadesi zorunlu değildir. - print("bir_degisken 10 dan küçük") -else: # Bu ifade de zorunlu değil. - print("bir_degisken değeri 10") - - -""" -Döngülerle lsiteleri döngüye alabilirsiniz -çıktı: - köpek bir memeli hayvandır - kedi bir memeli hayvandır - fare bir memeli hayvandır -""" -for hayvan in ["köpek", "kedi, "fare"]: - # format ile kolayca yazıyı biçimlendirelim - print("{} bir memeli hayvandır".format(hayvan)) - -""" -"range(sayi)" bir sayı listesi döndür -0'dan belirttiğiniz sayıyıa kadar -çıktı: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -'While' döngüleri koşul çalıştıkça işlemleri gerçekleştirir. -çıktı: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # Uzun hali x = x + 1 - -# Hataları kontrol altına almak için try/except bloklarını kullanabilirsiniz -try: - # Bir hata oluşturmak için "raise" kullanabilirsiniz - raise IndexError("Bu bir index hatası") -except IndexError as e: - pass # Önemsiz, devam et. -except (TypeError, NameError): - pass # Çoklu bir şekilde hataları kontrol edebilirsiniz, tabi gerekirse. -else: # İsteğe bağlı bir kısım. Eğer hiçbir hata kontrol mekanizması desteklemiyorsa bu blok çalışacaktır - print("Her şey iyi!") # IndexError, TypeError ve NameError harici bir hatada bu blok çalıştı - -# Temel Soyutlandırma, bir objenin işlenmiş halidir. -# Aşağıdaki örnekte; Obje, range fonksiyonuna temel soyutlandırma gönderdi. - -dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} -temel_soyut = dolu_sozl.keys() -print(temel_soyut) #=> range(1,10). Bu obje temel soyutlandırma arayüzü ile oluşturuldu - -# Temel Soyutlandırılmış objeyi döngüye sokabiliriz. -for i in temel_soyut: - print(i) # Çıktısı: bir, iki, uc - -# Fakat, elementin anahtarına değerine. -temel_soyut[1] # TypeError hatası! - -# 'iterable' bir objenin nasıl temel soyutlandırıldığıdır. -iterator = iter(temel_soyut) - -# 'iterator' o obje üzerinde yaptığımız değişiklikleri hatırlayacaktır -# Bir sonraki objeyi almak için __next__ fonksiyonunu kullanabilirsiniz. -iterator.__next__() #=> "bir" - -# Bir önceki __next__ fonksiyonumuzu hatırlayıp bir sonraki kullanımda bu sefer ondan bir sonraki objeyi döndürecektir -iterator.__next__() #=> "iki" -iterator.__next__() #=> "uc" - -# Bütün nesneleri aldıktan sonra bir daha __next__ kullanımınızda, StopIterator hatası oluşturacaktır. -iterator.__next__() # StopIteration hatası - -# iterator'deki tüm nesneleri almak için list() kullanabilirsiniz. -list(dolu_sozl.keys()) #=> Returns ["bir", "iki", "uc"] - - -#################################################### -## 4. Fonksiyonlar -#################################################### - -# "def" ile yeni fonksiyonlar oluşturabilirsiniz -def topla(x, y): - print("x = {} ve y = {}".format(x, y)) - return x + y # Değer döndürmek için 'return' kullanmalısınız - -# Fonksiyonu parametleri ile çağırıyoruz -topla(5, 6) # => çıktı "x = 5 ve y = 6" ve değer olarak 11 döndürür - -# Bir diğer fonksiyon çağırma yöntemi de anahtar değerleri ile belirtmek -topla(y=6, x=5) # Anahtar değeri belirttiğiniz için parametre sıralaması önemsiz. - -# Sınırsız sayıda argüman da alabilirsiniz -def argumanlar(*argumanlar): - return argumanlar - -argumanlar(1, 2, 3) # => (1, 2, 3) - -# Parametrelerin anahtar değerlerini almak isterseniz -def anahtar_par(**anahtarlar): - return anahtar - -# Çalıştırdığımızda -anahtar_par(anah1="deg1", anah2="deg2") # => {"anah1": "deg1", "anah2": "deg2"} - - -# İsterseniz, bu ikisini birden kullanabilirsiniz -def tum_argumanlar(*argumanlar, **anahtarla): - print(argumanlar) - print(anahtarla) -""" -tum_argumanlar(1, 2, a=3, b=4) çıktı: - (1, 2) - {"a": 3, "b": 4} -""" - -# Fonksiyonu çağırırken de aynısını kullanabilirsiniz -argumanlar = (1, 2, 3, 4) -anahtarla = {"a": 3, "b": 4} -tum_argumanlar(*argumanlar) # = foo(1, 2, 3, 4) -tum_argumanlar(**anahtarla) # = foo(a=3, b=4) -tum_argumanlar(*argumanlar, **anahtarla) # = foo(1, 2, 3, 4, a=3, b=4) - - -# Fonksiyonlarda kullanacağımız bir değişken oluşturalım -x = 5 - -def belirleX(sayi): - # Fonksiyon içerisindeki x ile global tanımladığımız x aynı değil - x = sayi # => 43 - print (x) # => 43 - -def globalBelirleX(sayi): - global x - print (x) # => 5 - x = sayi # global olan x değişkeni artık 6 - print (x) # => 6 - -belirleX(43) -globalBelirleX(6) - - -# Sınıf fonksiyonları oluşturma -def toplama_olustur(x): - def topla(y): - return x + y - return topla - -ekle_10 = toplama_olustur(10) -ekle_10(3) # => 13 - -# Bilinmeyen fonksiyon -(lambda x: x > 2)(3) # => True - -# TODO - Fix for iterables -# Belirli sayıdan yükseğini alma fonksiyonu -map(ekle_10, [1, 2, 3]) # => [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# Filtreleme işlemi için liste comprehensions da kullanabiliriz -[ekle_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -#################################################### -## 5. Sınıflar -#################################################### - - -# Sınıf oluşturmak için objeden alt sınıf oluşturacağız. -class Insan(object): - - # Sınıf değeri. Sınıfın tüm nesneleri tarafından kullanılabilir - tur = "H. sapiens" - - # Basit başlatıcı, Sınıf çağrıldığında tetiklenecektir. - # Dikkat edin, iki adet alt çizgi(_) bulunmakta. Bunlar - # python tarafından tanımlanan isimlerdir. - # Kendinize ait bir fonksiyon oluştururken __fonksiyon__ kullanmayınız! - def __init__(self, isim): - # Parametreyi sınıfın değerine atayalım - self.isim = isim - - # Bir metot. Bütün metotlar ilk parametre olarak "self "alır. - def soyle(self, mesaj): - return "{isim}: {mesaj}".format(isim=self.isim, mesaj=mesaj) - - # Bir sınıf metotu bütün nesnelere paylaştırılır - # İlk parametre olarak sınıf alırlar - @classmethod - def getir_tur(snf): - return snf.tur - - # Bir statik metot, sınıf ve nesnesiz çağrılır - @staticmethod - def grunt(): - return "*grunt*" - - -# Sınıfı çağıralım -i = Insan(isim="Ahmet") -print(i.soyle("merhaba")) # çıktı "Ahmet: merhaba" - -j = Insan("Ali") -print(j.soyle("selam")) # çıktı "Ali: selam" - -# Sınıf metodumuzu çağıraim -i.getir_tur() # => "H. sapiens" - -# Paylaşılan değeri değiştirelim -Insan.tur = "H. neanderthalensis" -i.getir_tur() # => "H. neanderthalensis" -j.getir_tur() # => "H. neanderthalensis" - -# Statik metodumuzu çağıralım -Insan.grunt() # => "*grunt*" - - -#################################################### -## 6. Moduller -#################################################### - -# Modülleri içe aktarabilirsiniz -import math -print(math.sqrt(16)) # => 4.0 - -# Modülden belirli bir fonksiyonları alabilirsiniz -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Modüldeki tüm fonksiyonları içe aktarabilirsiniz -# Dikkat: bunu yapmanızı önermem. -from math import * - -# Modül isimlerini değiştirebilirsiniz. -# Not: Modül ismini kısaltmanız çok daha iyi olacaktır -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Python modulleri aslında birer python dosyalarıdır. -# İsterseniz siz de yazabilir ve içe aktarabilirsiniz Modulün -# ismi ile dosyanın ismi aynı olacaktır. - -# Moduldeki fonksiyon ve değerleri öğrenebilirsiniz. -import math -dir(math) - - -#################################################### -## 7. Gelişmiş -#################################################### - -# Oluşturucular uzun uzun kod yazmamanızı sağlayacak ve yardımcı olacaktır -def kare_sayilar(nesne): - for i in nesne: - yield i + i - -# Bir oluşturucu(generator) değerleri anında oluşturur. -# Bir seferde tüm değerleri oluşturup göndermek yerine teker teker her oluşumdan -# sonra geri döndürür. Bu demektir ki, kare_sayilar fonksiyonumuzda 15'ten büyük -# değerler işlenmeyecektir. -# Not: range() da bir oluşturucu(generator)dur. 1-900000000 arası bir liste yapmaya çalıştığınızda -# çok fazla vakit alacaktır. -# Python tarafından belirlenen anahtar kelimelerden kaçınmak için basitçe alt çizgi(_) kullanılabilir. -range_ = range(1, 900000000) -# kare_sayilar'dan dönen değer 30'a ulaştığında durduralım -for i in kare_sayilar(range_): - print(i) - if i >= 30: - break - - -# Dekoratörler -# Bu örnekte, -# Eğer lutfen_soyle True ise dönen değer değişecektir. -from functools import wraps - - -def yalvar(hedef_fonksiyon): - @wraps(hedef_fonksiyon) - def metot(*args, **kwargs): - msj, lutfen_soyle = hedef_fonksiyon(*args, **kwargs) - if lutfen_soyle: - return "{} {}".format(msj, "Lütfen! Artık dayanamıyorum :(") - return msj - - return metot - - -@yalvar -def soyle(lutfen_soyle=False): - msj = "Bana soda alır mısın?" - return msj, lutfen_soyle - - -print(soyle()) # Bana soda alır mısın? -print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayanamıyorum :( -``` - -## Daha Fazlasına Hazır Mısınız? - -### Ücretsiz Online - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) -* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) - -### Kitaplar - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/vi-vn/python-vi.html.markdown b/vi-vn/python-vi.html.markdown new file mode 100644 index 00000000..f6cce1a3 --- /dev/null +++ b/vi-vn/python-vi.html.markdown @@ -0,0 +1,914 @@ +--- +language: python3 +filename: learnpython3-vi.py +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] +translators: + - ["Xuan (Sean) Luong, https://github.com/xuanluong"] +lang: vi-vn + +--- + +Python được tạo ra bởi Guido van Rossum vào đầu những năm 90s. Ngày nay nó là một trong những ngôn ngữ phổ biến +nhất còn tồn tại. Tôi thích Python vì sự rõ ràng, trong sáng về mặt cú pháp. Về cơ bản, Python có thể coi +như một loại mã giả (pseudocode) có thể thực thi được. + +Mọi phản hồi đều sẽ được tích cực ghi nhận! Bạn có thể liên lạc với tôi qua Twitter [@louiedinh](http://twitter.com/louiedinh) hoặc louiedinh [at] [google's email service] + +Lưu ý: Bài viết này áp dụng riêng cho Python 3. Truy cập [vào đây](http://learnxinyminutes.com/docs/python/) nếu bạn muốn học phiên bản cũ Python 2.7 + +```python + +# Dòng bình luận (comment) bắt đầu bằng dấu thăng (#) + +""" Những chuỗi ký tự (string) nằm trên nhiều dòng + có thể được viết bằng cách dùng 3 dấu nháy " và thường + được dùng trong quá trình viết tài liệu (documentation). +""" + +#################################################### +## 1. Các kiểu dữ liệu cơ bản và Các phép toán +#################################################### + +# Bạn có những con số +3 # => 3 + +# Tính toán với những con số là những điều có thể bạn sẽ làm +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# Kết quả của phép chia số nguyên sẽ được làm tròn xuống cho cả số dương và số âm +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # phép chia số nguyên cũng áp dụng được cho kiểu dữ liệu float biểu diễn số thực +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Kết quả của phép chia luôn là số thực +10.0 / 3 # => 3.3333333333333335 + +# Phép toán lấy phần dư (modulo) +7 % 3 # => 1 + +# Phép lũy thừa (x**y, x lũy thừa y) +2**3 # => 8 + +# Áp đặt thứ tự tính toán bằng dấu ngoặc +(1 + 3) * 2 # => 8 + +# Kiểu Boolean cũng là một kiểu dữ liệu cơ bản (Lưu ý: ký tự đầu tiên viết hoa) +True +False + +# Phủ định bằng từ khóa 'not' +not True # => False +not False # => True + +# Các phép toán với kiểu Boolean +# Lưu ý từ khóa "and" và "or" là case-sensitive +True and False # => False +False or True # => True + +# Lưu ý khi sử dụng các phép toán của kiểu Boolean với số nguyên 'int' +# False là 0 và True là 1 +# Đừng nhầm lẫn các phép toán Boolean cho số nguyên và các phép toán and/or trên bit (& và |) +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True +-5 != False != True #=> True + +# So sánh bằng với == +1 == 1 # => True +2 == 1 # => False + +# So sánh không bằng với != +1 != 1 # => False +2 != 1 # => True + +# Các phép so sánh khác +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Các phép so sánh có thể xâu chuỗi với nhau! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) từ khóa is kiểm tra xem 2 biến có cùng tham chiếu một đối tượng, còn == kiếm tra +# xem hai đối tượng có cùng giá trị hay không. +a = [1, 2, 3, 4] # a trỏ tới một danh sách (list) mới, [1, 2, 3, 4] +b = a # b trỏ tới nơi mà a cũng đang trỏ tới +b is a # => True, a và b cùng trỏ tới một đối tượng +b == a # => True, đối tượng mà a và b trỏ tới có cùng giá trị +b = [1, 2, 3, 4] # b trỏ tới một danh sách mới, [1, 2, 3, 4] +b is a # => False, a và b không cùng trỏ tới một đối tượng +b == a # => True, đối tượng mà a và b trỏ tới không có cùng giá trị + +# Chuỗi ký tự được tạo ra bằng dấu nháy kép " hoặc nháy đơn ' +"Đây là một chuỗi ký tự." +'Đây cũng là một chuỗi ký tự.' + +# Chuỗi ký tự có thể được cộng với nhau can be added too! Tuy nhiên nên tránh làm như vậy +"Xin " + "chào!" # => "Xin chào!" +# Các chuỗi ký tự không phải là biến (literals) có thể được nối với nhau mà không cần dùng phép cộng '+' +"Xin " "chào!" # => "Xin chào!" + +# Một chuỗi ký tự có thể xem như một danh sách (list) các ký tự +"Đây là một chuỗi ký tự"[0] # => 'Đ' + +# Bạn có thể tìm chiều dài một chuỗi +len("Đây là một chuỗi") # => 16 + +# .format có thể được dùng để định dạng chuỗi, ví dụ như: +"{} có thể được {}".format("Chuỗi ký tự", "định dạng") # => "Chuỗi ký tự có thể được định dạng" + +# Bạn có thể lặp lại đối số (arguments) khi định dạnh để không phải gõ nhiều lần +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# Bạn có thể dùng từ khóa nếu bạn không muốn đếm +"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" + +# Nếu code Python 3 của bạn cần phải chạy với Python 2.5 hoặc các bản cũ hơn, bạn cũng có thể +# dùng cách định dạng cũ: +"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" + + +# None là một đối tượng +None # => None + +# Đừng dùng so sánh bằng "==" để so sánh đối tượng với None +# Thay vào đó dùng is. Nó sẽ kiểm tra xem một đối tượng có đồng nhất với None hay không. +"etc" is None # => False +None is None # => True + +# None, 0, và chuỗi/danh sách (list)/từ điển (dict)/tuple rỗng khi chuyển về kiểu Boolean đều có giá trị là False. +# Tất cả những giá trị khác đều là True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +## 2. Biến và Các kiểu dữ liệu gộp (Collections) +#################################################### + +# Hàm print trong Python +print("Tôi là Python. Rất hân hạnh được làm quen!") # => Tôi là Python. Rất hân hạnh được làm quen! + +# Hàm print mặc định in thêm ký tự xuống dòng +# Dùng đối số tùy chọn (optional argument) để thay đổi cách kết thúc chuỗi. +print("Hello, World", end="!") # => Hello, World! + +# Một cách đơn giản để lấy dữ liệu vào từ bàn phím +input_string_var = input("Nhập dữ liệu: ") # Trả về dữ liệu vào là một chuỗi +# Lưu ý: Trong những phiên bản cũ của Python input() có tên là raw_input() + +# Không cần phải khai báo biến mà chỉ có gán giá trị cho biến. +# Quy ước là sử dụng chữ_viết_thường_có_dấu_gạch_dưới +some_var = 5 +some_var # => 5 + +# Truy cập một biến chưa được gán trước đó sẽ tạo ra biệt lệ (exception). +# Đọc mục Luồng điều khiển để hiểu thêm về việc giải quyết các biệt lệ (exception handling) +some_unknown_var # Sinh ra một biệt lệ kiểu NameError + +# if có thể dùng như một biểu thức +# Tương đương với phép toán ba ngôi trong C: '?:' +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Kiểu danh sách (list) lưu trữ chuỗi đối tượng tuần tự +li = [] +# Bạn có thể bắt đầu với một danh sách đã có sãn các phần tử +other_li = [4, 5, 6] + +# Thêm phần tử vào cuối danh sách bằng phương thức append +li.append(1) # li bây giờ là [1] +li.append(2) # li bây giờ là [1, 2] +li.append(4) # li bây giờ là [1, 2, 4] +li.append(3) # li bây giờ là [1, 2, 4, 3] +# Xóa phần tử cuối cùng bằng phương thức pop +li.pop() # => 3 and li is now [1, 2, 4] +# Sau đó ta có thể đưa đối tượng trở lại danh sách +li.append(3) # li trở lại là [1, 2, 4, 3]. + +# Truy cập một danh sách như bạn làm với một mảng (array) +li[0] # => 1 +# Truy cập phần tử cuối cùng +li[-1] # => 3 + +# Truy cập ngoài giới hạn sẽ tạo ra biệt lệ IndexError +li[4] # Sinh ra một biệt lệ kiểu IndexError + +# Bạn có thể truy cập một đoạn bằng phép cắt (slice). +# Chỉ mục bắt đầu được tính làm điểm bắt đầu còn chỉ mục kết thúc thì không, mà là chỉ mục của phần tử tiếp theo phần tử kết thúc +# (Về mặt toán học thì đây là một đoạn đóng/mở, hay nửa đoạn) +li[1:3] # => [2, 4] +# Lấy từ vị trí thứ 3 đến hết +li[2:] # => [4, 3] +# Lấy từ đầu đến vị trí thứ 3 +li[:3] # => [1, 2, 4] +# Lấy những phần tử có chỉ mục chẵn +li[::2] # =>[1, 4] +# Trả về bản sao của danh sách bị đảo ngược +li[::-1] # => [3, 4, 2, 1] +# Kết hợp 3 tham số để làm những phép cắt phức tạp hơn +# li[start:end:step] + +# Tạo ra một bản sao sâu (deep copy) bằng phép cắt +li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. + +# Xóa phần tử nào đó của danh sách bằng "del" +del li[2] # li is now [1, 2, 3] + +# Xóa đi phần tử đầu tiên mang một giá trị nhất định +li.remove(2) # li bây giờ là [1, 3] +li.remove(2) # Sinh ra biệt lệ kiểu ValueError vì 2 không tồn tại trong danh sách + +# Chèn một phần tử vào một vị trí cụ thể +li.insert(1, 2) # li bây giờ lại là [1, 2, 3] + +# Tìm chỉ mục của của phần tử đầu tiên mang một giá trị nhất định +li.index(2) # => 1 +li.index(4) # Sinh ra biệt lệ a ValueError as 4 is not in the list + +# Bạn có thể cộng dồn các danh sách +# Lưu ý: giá trị của li và other_li không đổi +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Nối danh sách bằng "extend()" +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# Kiểm tra sự tồn tại của một phần tử trong danh sách bằng "in" +1 in li # => True + +# Xác định độ dài bằng "len()" +len(li) # => 6 + + +# Tuple cũng giống như danh sách nhưng không thể thay đổi giá trị được (immutable) +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Sinh ra biệt lệ kiểu TypeError + +# Lưu ý rằng tuple có độ dài là 1 phải có dấu phẩy theo sau phần tử cuối +# nhưng tuples có độ dài khác, ngay cả tuple rỗng, thì không cần như vậy +type((1)) # => +type((1,)) # => +type(()) # => + +# Hầu hết các phép toán của danh sách đều áp dụng được cho tuples +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Bạn có thể gán giá trị cho nhiều biến một lúc bằng tuple (tuple unpacking) +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +# Sau đây là unpacking kiểu mở rộng +a, *b, c = (1, 2, 3, 4) # a bây giờ là 1, b là [2, 3] và c là 4 +# Tuple được tự động tạo ra nếu bạn không để dấu ngoặc đơn +d, e, f = 4, 5, 6 +# Hoán đổi hai biến trở nên dễ dàng +e, d = d, e # d bây giờ là 5 và e là 4 + + +# Kiểu dữ liệu từ điển (dictionaries) lưu trữ ánh xạ từ các khóa (keys) đến các giá trị (values) +empty_dict = {} +# Sau đây là một từ điển có sẵn phần tử +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Lưu ý rằng khóa của từ điển phải có kiểu dữ liệu thuộc loại immutable. Điều này để bảo đảm rằng +# khóa đó luôn được chuyển hóa thành một giá trị băm (hash value) duy nhất khi tìm kiếm trong từ điển +# Những kiểu immutable bao gồm số nguyên (int), số thực (float), chuỗi ký tự (string), hay tuple +invalid_dict = {[1,2,3]: "123"} # => Sinh ra biệt lệ kiểu TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Tuy nhiên, giá trị có thể thuộc bất kỳ kiểu gì + +# Truy cập giá trị của một từ khóa bằng dấu [] +filled_dict["one"] # => 1 + +# Tất cả khóa trong một từ điển có thể được chuyển thành một đối tượng khả lặp (iterable). +# Chúng ta cần phải gọi hàm list() để chuyển một iterable thành một danh sách. +# Chúng ta sẽ bàn về vấn đề này sau. Lưu ý - Thứ tự của khóa trong từ điển sẽ không được đảm bảo. +# Những gì bạn thấy khi chạy dòng code dưới đây có thể sẽ không hoàn toàn giống như vậy. +list(filled_dict.keys()) # => ["three", "two", "one"] + + +# Tất cả các giá trị có thể chuyển thành một đối tượng khả lặp bằng cách gọi hàm "values()". +# Chúng ta cũng vẫn phải gọi hàm list() nếu muốn chuyển nó thành một danh sách. Lưu ý - thứ +# tự của giá trị cũng không được đảm bảo +list(filled_dict.values()) # => [3, 2, 1] + + +# Sự tồn tại của khóa trong từ điển có thể kiểm tra được thông qua từ khóa "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# Truy xuất giá trị của một khóa không tồn tại trong từ điển sẽ tạo ra biệt lệ KeyError +filled_dict["four"] # KeyError + +# Dừng phương thức "get()" để tránh tạo ra biệt lệ KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# Phương thức get hỗ trợ một đối số mặt định khi không thể tìm thấy giá trị ứng với từ khóa +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" chèn một giá trị ứng với khóa nếu khóa đó không có sẵn trong từ điển +filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 + +# Thêm khóa và giá trị vào từ điển +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict["four"] = 4 # another way to add to dict + +# Xóa một khóa ra khỏi từ điển bằng từ khóa del +del filled_dict["one"] # Removes the key "one" from filled dict + +# Bắt đầu từ Python 3.5 bạn có thể unpack từ điển trong một từ điển khác +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + + +# Kiểu tập hợp (set) lưu trữ ... tập hợp +empty_set = set() +# Khởi tạo giá trị một tập hợp với nhiều giá tri. Vâng, nhìn nó khá giống từ điển. +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# Tương tự như khóa của từ điển, phần tử của một tập hợp cũng phải là immutable +invalid_set = {[1], 1} # => Sinh ra biệt lệ TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Thêm một phần tử vào tập hợp +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Thực hiện phép giao hai tập hợp bằng phép toán & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Thực hiện phép hợp bằng phép toán | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Lấy hiệu của hai tập hơp bằng phép toán - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Lấy hiệu đối xứng bằng phép toán ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Kiểm tra tập hợp bên trái là tập cha của bên phải +{1, 2} >= {1, 2, 3} # => False + +# Kiểm tra xem tập hợp bên trái có phải là tập con của tập hợp bên phải +{1, 2} <= {1, 2, 3} # => True + +# Kiểm tra sự tồn tại của một phần tử trong tập hợp bằng từ khóa in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Luồng điều khiển và kiểu khả lặp +#################################################### + +# Đầu tiên hãy tạo ra một biến +some_var = 5 + +# Sau đây là một câu lệnh if. Khoảng cách lề rất quan trọng trong Python +# Quy ước chung là dùng khoảng trắng chứ không phải ký tự tab +# Chuỗi sau sẽ được in ra "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # Phần elif là tùy chọn. + print("some_var is smaller than 10.") +else: # else cũng là tùy chọn. + print("some_var is indeed 10.") + + +""" +Lặp qua một danh sách bằng for +in ra: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # Bạn có thể dùng format() để gán một giá trị vào giữa chuỗi (string interpolation) + print("{} is a mammal".format(animal)) + +""" +"range(number)" trả về một đối tượng khả lặp kiểu số +từ 0 đến giá trị của number +in ra: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(lower, upper)" trả về một đối tượng khả lặp kiểu số +từ giá trị lower đến giá trị upper +in ra: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(lower, upper, step)" trả về một đối tượng khả lặp kiểu số +từ giá trị lower đến giá trị upper, tăng dần theo giá trị +của step. Nếu không có giá trị của step thì mặc định là 1. +in ra: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +Vòng lặp while tiếp tục lặp khi điều kiện còn được thỏa mãn +in ra: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # cách viết ngán cho x = x + 1 + +# Handle exceptions with a try/except block +# Đối phó với biệt lệ bằng khối lệnh try/except +try: + # Dùng "raise" để ném ra một biệt lệ + raise IndexError("This is an index error") +except IndexError as e: + pass # pass có nghĩa là không làm gì cả. Thông thường đây là nơi để khắc phụ vấn đề làm xảy ra biệt lệ +except (TypeError, NameError): + pass # Nhiều biệt lệ có thể được đối phó cùng một lúc nếu cần +else: # Không bắt buộc phải sử dụng else nhưng nếu dùng thì nó phải sau tất cả các khối except + print("All good!") # Chỉ thực thi nếu không có biệt lệ phát sinh +finally: # Luôn thực thi trong mọi hoàn cảnh + print("We can clean up resources here") + +# Thay vì dùng try/finally để thu hồi tài nguyên (resources) ta có thể dùng with +with open("myfile.txt") as f: + for line in f: + print(line) + +# Python hỗ trợ kiểu dữ liệu khả lặp (iterable). +# Một đối tượng khả lặp có thể được xem như là một chuỗi các đối tượng tuần tự (sequence) +# Đối tượng trả về bởi hàm range là một khả lặp. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['one', 'two', 'three']). Đây là một đối tượng khả lặp + +# Ta có thể lặp qua đối tượng +for i in our_iterable: + print(i) # In ra một, hai, ba + +# Tuy nhiên chúng ta không thể truy cập phần tử bằng chỉ mục +our_iterable[1] # Sinh ra biệt lệ TypeError + +# Một đối tượng khả lặp là đối tượng có thể tạo ra một iterator +our_iterator = iter(our_iterable) + +# iterator là một đối tượng ghi nhớ được trạng thái trong quá trình nó được duyệt qua +# đối tượng kế tiếp có thể truy cập được bằng hàm next +next(our_iterator) # => "one" + +# Nó ghi nhớ trạng thái trong quá trình lặp +next(our_iterator) # => "two" +next(our_iterator) # => "three" + +# Sau khi iterator đã trả về tất cả dữ liệu, nó sẽ sinh ra biệt lệ kiểu StopIteration +next(our_iterator) # Sinh ra biệt lệ StopIteration + +# Ta có thể lấy tất cả phần tử của một iterator bằng cách gọi hàm list với nó +list(filled_dict.keys()) # => Returns ["one", "two", "three"] + + +#################################################### +## 4. Hàm +#################################################### + +# Dùng từ khóa def để định nghĩa hàm +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # từ khóa return để trả về một giá trị + +# Gọi một hàm với đối số +add(5, 6) # => In ra "x is 5 and y is 6" và trả về 11 + +# Một cách khác để gọi hàm là dùng đối số có từ khóa (keyword arguments) +add(y=6, x=5) # Đối số có từ khóa có thể xuất hiện với thứ tự bất kỳ + +# Bạn có thể định nghĩa hàm có số lượng đối số vị trí (positional arguments) không biết trước +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Số lượng tham số từ khóa cũng có thể không cần biết trước +def keyword_args(**kwargs): + return kwargs + +# Thử gọi hàm để xem điều gì xảy ra +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# Có thể định nghĩa hàm dùng cả hai loại đối số +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) in ra: + (1, 2) + {"a": 3, "b": 4} +""" + +# Khi gọi hàm, bạn có thể làm ngược với khi định nghĩa +# Dùng dấu * để lấy giá trị từ args và ** với giá trị từ kwargs +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # tương đương với foo(1, 2, 3, 4) +all_the_args(**kwargs) # tương đương với foo(a=3, b=4) +all_the_args(*args, **kwargs) # tương đương với foo(1, 2, 3, 4, a=3, b=4) + +# Trả về nhiều giá trị (gán vào một tuple) +def swap(x, y): + return y, x # Trả về nhiều giá trị dưới dạng một tuple mà không cần dấu ngoặc. + # (Lưu ý là dấu ngoặc đơn đã được bỏ đi những vẫn có thể được thêm vào) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # dấu ngoặc đơn đã được bỏ đi những vẫn có thể được thêm vào + +# Tầm vực của hàm +x = 5 + +def set_x(num): + # Biến cục bộ x không đồng nhất với biến toàn cục x + x = num # => 43 + print(x) # => 43 + +def set_global_x(num): + global x + print(x) # => 5 + x = num # biến toàn cục x được gán giá trị là 6 + print(x) # => 6 + +set_x(43) +set_global_x(6) + + +# Hàm trong Python cũng là đối tượng +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Có những hàm không tên +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Có những hàm cấp cao được hỗ trọ sẵn +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# list comprehension có thể dùng để hay thế map và filter +# list comprehension lưu giá trị xuất vào một danh sách mà bản thân nó có thể lồng trong danh sách khác +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# Tập hơp và từ điển cũng có thể được tao ra thông qua set comprehension và dict comprehension +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Mô đun +#################################################### + +# Bạn có thể import một mô đun +import math +print(math.sqrt(16)) # => 4.0 + +# Bạn có thể lấy một hàm cụ thể từ một mô đun +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Hoặc import tất cả hàm từ một mô đun +# Cảnh báo: đây không phải là một cách hay +from math import * + +# Có thể làm tên của module ngắn lại +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Mô đun trong Python chỉ là những tập tin Python bình thường. Bạn +# có thể viết mô đun của mình và import chúng. Tên của mô đun +# cũng là tên của tập tin. + +# You can find out which functions and attributes +# are defined in a module. +# Bạn có thể liệt kê những hàm và thuộc tính +# được định nghĩa trong một mô đun +import math +dir(math) + +# Nếu bạn có một tập tin code Python gọi là math.py ở cùng +# thư mục với tập tin hiện tai, tập tin math.py sẽ +# được nạp vào thay vì mô đun được cung cấp sẵn (built-in) trong Python. +# Điều này xảy ra vì thư mục hiện tại có ưu tiên +# hơn những thư viện cung cấp sẵn. + + +#################################################### +## 6. Lớp (classes) +#################################################### + +# Ta dùng từ khóa "class" đề định nghĩa một lớp +class Human: + + # Một thuộc tính của lớp được chia sẽ bởi tất cả đối tượng của lớp này + species = "H. sapiens" + + # Hàm khởi tạo cơ bản sẽ được goi khi một đối tượng được tạo ra. + # Lưu ý 2 dấu gạch dưới ở đầu và cuối ám chỉ đối tượng + # hoặc thuộc tính dùng bở Python những tồn tại trong không gian tên + # do người dùng kiểm soát. Phương thức (hoặc thuộc tính) như: __init__, __str__, + # __repr__ v.v.. là những phương thức đặc biệt. + # Bạn không nên tự đặt những tên như vậy. + def __init__(self, name): + # Gán đối số vào thuộc tính name của đối tượng + self.name = name + + # Khởi tạo thuộc tính + self._age = 0 + + # Một phương thức trên đối tượng. Tất cả đều có đối số đầu tiên là "self" + def say(self, msg): + print ("{name}: {message}".format(name=self.name, message=msg)) + + # Một phương thức trên đối tượng khác + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # Một phương thức trên lớp được chia sẻ với mọi đối tượng + # Lớp đó cũng là đối số thứ nhất của phương thức đó + @classmethod + def get_species(cls): + return cls.species + + # Một phương thức tĩnh được gọi mà không có lớp hay đối tượng đi kèm + @staticmethod + def grunt(): + return "*grunt*" + + # Một thuộc tính chỉ giống như một hàm truy xuất. + # Nó biến phương thức age() thành một thuộc tính chỉ đọc cùng tên. + # Tuy nhiên trong Python không nhất thiết phải viết những hàm đọc và ghi quá đơn giản + @property + def age(self): + return self._age + + # Đây là hàm để ghi giá trị cho thuộc tính + @age.setter + def age(self, age): + self._age = age + + # Đây là hàm để xóa thuộc tính + @age.deleter + def age(self): + del self._age + + +# Khi trình thông dịch Python đọc một tập tin mã nguồn, nó thực thi tất cả code trong đó. +# Kiểm tra giá trị của __name__ bảo đảm rằng đoạn mã bên dưới chỉ thực thi khi +# mô đun này là chương trình chính +if __name__ == '__main__': + # Khởi tạo một đối tượng + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i và j là thực thể của kiểu Human, nói cách khác: chúng là những đối tượng Human + + # Gọi những phương thức trên lớp + i.say(i.get_species()) # "Ian: H. sapiens" + # Thay đổi thuộc tính chung + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Gọi phương thức tĩnh + print(Human.grunt()) # => "*grunt*" + + # Không thể gọi phương thức tĩnh với một thực thể/đối tượng + # bởi vì i.grunt() sẽ tự động đặt "self" (tức là đối tượng i) làm đối số thứ nhất + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # Thay đổi thuộc tính của đối tượng + i.age = 42 + # Truy cập thuộc tính + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # Xóa thuộc tính + del i.age + # i.age # => dòng nãy sẽ tạo ra biệt lệ AttributeError + + +#################################################### +## 6.1 Đa thừa kế +#################################################### + +# Một định nghĩa lớp khác +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # Lớp này có phương thức say + def say(self, msg): + msg = '... ... ...' + return msg + + # Và một phương thức khác + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + +# Để tận dụng việc mô đun hóa thành từng tập tin, bạn có thể đặt những lớp định nghĩa ở trên vào các tập tin riêng, +# ví dụ như human.py và bat.py + +# Để import hàm từ tập tin khác dừng cấu trúc sau +# from "filename-without-extension" import "function-or-class" + +# superhero.py +from human import Human +from bat import Bat + +# Batman thừa kế từ lớp Human và Bat +class Batman(Human, Bat): + + # Batman có giá trị riêng cho thuộc tính trên lớp species + species = 'Superhero' + + def __init__(self, *args, **kwargs): + # Cách điển hình để thừa kế thuộc tính là gọi super + # super(Batman, self).__init__(*args, **kwargs) + # Tuy nhiên với đa thừa kế, super() sẽ chỉ gọi lớp cơ sở tiếp theo trong danh sách MRO. + # Vì thế, ta sẽ gọi cụ thể hàm __init__ của các lớp chả. + # Sử dụng *args và **kwargs cho phép việc truyền đối số gọn gàng hơn, + # trong đó mỗi lớp cha sẽ chịu trách nhiệm cho những phần thuộc về nó + Human.__init__(self, 'anonymous', *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # ghi đè giá trị của thuộc tính name + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # Kiểm tra kiểu đối tượng + if isinstance(sup, Human): + print('I am human') + if isinstance(sup, Bat): + print('I am bat') + if type(sup) is Batman: + print('I am Batman') + + # Truy xuất thứ tự phương thức của các lớp cha (Method Resolution search Order), vốn được dùng bởi cả getattr() và super9) + # Thuộc tính này động và có thể được cập nhật + print(Batman.__mro__) # => (, , , ) + + # Gọi phương thức của lớp cha nhưng dùng thuộc tính trên chính lớp hiện tại + print(sup.get_species()) # => Superhero + + # Gọi phương thức được nạp chồng + print(sup.sing()) # => nan nan nan nan nan batman! + + # Gọi phương thức của Human, bởi vì thứ tự thừa kế ảnh hưởng đến phương thức được gọi + sup.say('I agree') # => Sad Affleck: I agree + + # Gọi phương thức chỉ tồn tại ở lớp cha thứ 2 + print(sup.sonar()) # => ))) ... ((( + + # Thuộc tính cấp lớp được thừa kế + sup.age = 100 + print(sup.age) + + # Thuộc tính thừa kế từ lớp cha thứ 2 có giá trị mặc định đã bị ghi đè + print('Can I fly? ' + str(sup.fly)) + + + +#################################################### +## 7. Phần nâng cao +#################################################### + +# Generator giúp ta viết những đoạn code lười biếng (áp dụng nguyên tắc lazy evaluation) +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Generators tiết kiệm bộ nhớ vì nó chỉ tải dữ liệu khi cần +# xử lý giá trị kế tiếp của một đối tượng khả lặp. Điều này cho phép generator thực hiện +# những thao tác mà bình thường không làm được trên những khoảng giá trị lớn +# Lưu ý: `range` thay thế `xrange` trong Python3. + +for i in double_numbers(range(1, 900000000)): # `range` là một generator. + print(i) + if i >= 30: + break + +# Cũng như danh sách có list comprehension, generator cũng có generator +# comprehension +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # in -1 -2 -3 -4 -5 ra màn hình dòng lệnh + +# Một generator cũng có thể bị ép kiểu thành danh sách +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# Decorators +# Trong ví dụ này hàm `beg` 'phủ lên' hàm `say`. Nếu say_please là True thì nó +# sẽ thay đội giá trị trả về +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Làm ơn! Tui rất nghèo :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Mua bia cho tui nhé?" + return msg, say_please + + +print(say()) # Mua bia cho tui nhé? +print(say(say_please=True)) # Mua bia cho tui nhé? Làm ơn! Tui rất nghèo :( +``` + +## Sẵn sàng để học nhiều hơn? + +### Miễn phí trên mạng + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/vi-vn/python3-vi.html.markdown b/vi-vn/python3-vi.html.markdown deleted file mode 100644 index f6cce1a3..00000000 --- a/vi-vn/python3-vi.html.markdown +++ /dev/null @@ -1,914 +0,0 @@ ---- -language: python3 -filename: learnpython3-vi.py -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["evuez", "http://github.com/evuez"] -translators: - - ["Xuan (Sean) Luong, https://github.com/xuanluong"] -lang: vi-vn - ---- - -Python được tạo ra bởi Guido van Rossum vào đầu những năm 90s. Ngày nay nó là một trong những ngôn ngữ phổ biến -nhất còn tồn tại. Tôi thích Python vì sự rõ ràng, trong sáng về mặt cú pháp. Về cơ bản, Python có thể coi -như một loại mã giả (pseudocode) có thể thực thi được. - -Mọi phản hồi đều sẽ được tích cực ghi nhận! Bạn có thể liên lạc với tôi qua Twitter [@louiedinh](http://twitter.com/louiedinh) hoặc louiedinh [at] [google's email service] - -Lưu ý: Bài viết này áp dụng riêng cho Python 3. Truy cập [vào đây](http://learnxinyminutes.com/docs/python/) nếu bạn muốn học phiên bản cũ Python 2.7 - -```python - -# Dòng bình luận (comment) bắt đầu bằng dấu thăng (#) - -""" Những chuỗi ký tự (string) nằm trên nhiều dòng - có thể được viết bằng cách dùng 3 dấu nháy " và thường - được dùng trong quá trình viết tài liệu (documentation). -""" - -#################################################### -## 1. Các kiểu dữ liệu cơ bản và Các phép toán -#################################################### - -# Bạn có những con số -3 # => 3 - -# Tính toán với những con số là những điều có thể bạn sẽ làm -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 - -# Kết quả của phép chia số nguyên sẽ được làm tròn xuống cho cả số dương và số âm -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # phép chia số nguyên cũng áp dụng được cho kiểu dữ liệu float biểu diễn số thực --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# Kết quả của phép chia luôn là số thực -10.0 / 3 # => 3.3333333333333335 - -# Phép toán lấy phần dư (modulo) -7 % 3 # => 1 - -# Phép lũy thừa (x**y, x lũy thừa y) -2**3 # => 8 - -# Áp đặt thứ tự tính toán bằng dấu ngoặc -(1 + 3) * 2 # => 8 - -# Kiểu Boolean cũng là một kiểu dữ liệu cơ bản (Lưu ý: ký tự đầu tiên viết hoa) -True -False - -# Phủ định bằng từ khóa 'not' -not True # => False -not False # => True - -# Các phép toán với kiểu Boolean -# Lưu ý từ khóa "and" và "or" là case-sensitive -True and False # => False -False or True # => True - -# Lưu ý khi sử dụng các phép toán của kiểu Boolean với số nguyên 'int' -# False là 0 và True là 1 -# Đừng nhầm lẫn các phép toán Boolean cho số nguyên và các phép toán and/or trên bit (& và |) -0 and 2 # => 0 --5 or 0 # => -5 -0 == False # => True -2 == True # => False -1 == True # => True --5 != False != True #=> True - -# So sánh bằng với == -1 == 1 # => True -2 == 1 # => False - -# So sánh không bằng với != -1 != 1 # => False -2 != 1 # => True - -# Các phép so sánh khác -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# Các phép so sánh có thể xâu chuỗi với nhau! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# (is vs. ==) từ khóa is kiểm tra xem 2 biến có cùng tham chiếu một đối tượng, còn == kiếm tra -# xem hai đối tượng có cùng giá trị hay không. -a = [1, 2, 3, 4] # a trỏ tới một danh sách (list) mới, [1, 2, 3, 4] -b = a # b trỏ tới nơi mà a cũng đang trỏ tới -b is a # => True, a và b cùng trỏ tới một đối tượng -b == a # => True, đối tượng mà a và b trỏ tới có cùng giá trị -b = [1, 2, 3, 4] # b trỏ tới một danh sách mới, [1, 2, 3, 4] -b is a # => False, a và b không cùng trỏ tới một đối tượng -b == a # => True, đối tượng mà a và b trỏ tới không có cùng giá trị - -# Chuỗi ký tự được tạo ra bằng dấu nháy kép " hoặc nháy đơn ' -"Đây là một chuỗi ký tự." -'Đây cũng là một chuỗi ký tự.' - -# Chuỗi ký tự có thể được cộng với nhau can be added too! Tuy nhiên nên tránh làm như vậy -"Xin " + "chào!" # => "Xin chào!" -# Các chuỗi ký tự không phải là biến (literals) có thể được nối với nhau mà không cần dùng phép cộng '+' -"Xin " "chào!" # => "Xin chào!" - -# Một chuỗi ký tự có thể xem như một danh sách (list) các ký tự -"Đây là một chuỗi ký tự"[0] # => 'Đ' - -# Bạn có thể tìm chiều dài một chuỗi -len("Đây là một chuỗi") # => 16 - -# .format có thể được dùng để định dạng chuỗi, ví dụ như: -"{} có thể được {}".format("Chuỗi ký tự", "định dạng") # => "Chuỗi ký tự có thể được định dạng" - -# Bạn có thể lặp lại đối số (arguments) khi định dạnh để không phải gõ nhiều lần -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# Bạn có thể dùng từ khóa nếu bạn không muốn đếm -"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" - -# Nếu code Python 3 của bạn cần phải chạy với Python 2.5 hoặc các bản cũ hơn, bạn cũng có thể -# dùng cách định dạng cũ: -"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" - - -# None là một đối tượng -None # => None - -# Đừng dùng so sánh bằng "==" để so sánh đối tượng với None -# Thay vào đó dùng is. Nó sẽ kiểm tra xem một đối tượng có đồng nhất với None hay không. -"etc" is None # => False -None is None # => True - -# None, 0, và chuỗi/danh sách (list)/từ điển (dict)/tuple rỗng khi chuyển về kiểu Boolean đều có giá trị là False. -# Tất cả những giá trị khác đều là True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False - -#################################################### -## 2. Biến và Các kiểu dữ liệu gộp (Collections) -#################################################### - -# Hàm print trong Python -print("Tôi là Python. Rất hân hạnh được làm quen!") # => Tôi là Python. Rất hân hạnh được làm quen! - -# Hàm print mặc định in thêm ký tự xuống dòng -# Dùng đối số tùy chọn (optional argument) để thay đổi cách kết thúc chuỗi. -print("Hello, World", end="!") # => Hello, World! - -# Một cách đơn giản để lấy dữ liệu vào từ bàn phím -input_string_var = input("Nhập dữ liệu: ") # Trả về dữ liệu vào là một chuỗi -# Lưu ý: Trong những phiên bản cũ của Python input() có tên là raw_input() - -# Không cần phải khai báo biến mà chỉ có gán giá trị cho biến. -# Quy ước là sử dụng chữ_viết_thường_có_dấu_gạch_dưới -some_var = 5 -some_var # => 5 - -# Truy cập một biến chưa được gán trước đó sẽ tạo ra biệt lệ (exception). -# Đọc mục Luồng điều khiển để hiểu thêm về việc giải quyết các biệt lệ (exception handling) -some_unknown_var # Sinh ra một biệt lệ kiểu NameError - -# if có thể dùng như một biểu thức -# Tương đương với phép toán ba ngôi trong C: '?:' -"yahoo!" if 3 > 2 else 2 # => "yahoo!" - -# Kiểu danh sách (list) lưu trữ chuỗi đối tượng tuần tự -li = [] -# Bạn có thể bắt đầu với một danh sách đã có sãn các phần tử -other_li = [4, 5, 6] - -# Thêm phần tử vào cuối danh sách bằng phương thức append -li.append(1) # li bây giờ là [1] -li.append(2) # li bây giờ là [1, 2] -li.append(4) # li bây giờ là [1, 2, 4] -li.append(3) # li bây giờ là [1, 2, 4, 3] -# Xóa phần tử cuối cùng bằng phương thức pop -li.pop() # => 3 and li is now [1, 2, 4] -# Sau đó ta có thể đưa đối tượng trở lại danh sách -li.append(3) # li trở lại là [1, 2, 4, 3]. - -# Truy cập một danh sách như bạn làm với một mảng (array) -li[0] # => 1 -# Truy cập phần tử cuối cùng -li[-1] # => 3 - -# Truy cập ngoài giới hạn sẽ tạo ra biệt lệ IndexError -li[4] # Sinh ra một biệt lệ kiểu IndexError - -# Bạn có thể truy cập một đoạn bằng phép cắt (slice). -# Chỉ mục bắt đầu được tính làm điểm bắt đầu còn chỉ mục kết thúc thì không, mà là chỉ mục của phần tử tiếp theo phần tử kết thúc -# (Về mặt toán học thì đây là một đoạn đóng/mở, hay nửa đoạn) -li[1:3] # => [2, 4] -# Lấy từ vị trí thứ 3 đến hết -li[2:] # => [4, 3] -# Lấy từ đầu đến vị trí thứ 3 -li[:3] # => [1, 2, 4] -# Lấy những phần tử có chỉ mục chẵn -li[::2] # =>[1, 4] -# Trả về bản sao của danh sách bị đảo ngược -li[::-1] # => [3, 4, 2, 1] -# Kết hợp 3 tham số để làm những phép cắt phức tạp hơn -# li[start:end:step] - -# Tạo ra một bản sao sâu (deep copy) bằng phép cắt -li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. - -# Xóa phần tử nào đó của danh sách bằng "del" -del li[2] # li is now [1, 2, 3] - -# Xóa đi phần tử đầu tiên mang một giá trị nhất định -li.remove(2) # li bây giờ là [1, 3] -li.remove(2) # Sinh ra biệt lệ kiểu ValueError vì 2 không tồn tại trong danh sách - -# Chèn một phần tử vào một vị trí cụ thể -li.insert(1, 2) # li bây giờ lại là [1, 2, 3] - -# Tìm chỉ mục của của phần tử đầu tiên mang một giá trị nhất định -li.index(2) # => 1 -li.index(4) # Sinh ra biệt lệ a ValueError as 4 is not in the list - -# Bạn có thể cộng dồn các danh sách -# Lưu ý: giá trị của li và other_li không đổi -li + other_li # => [1, 2, 3, 4, 5, 6] - -# Nối danh sách bằng "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] - -# Kiểm tra sự tồn tại của một phần tử trong danh sách bằng "in" -1 in li # => True - -# Xác định độ dài bằng "len()" -len(li) # => 6 - - -# Tuple cũng giống như danh sách nhưng không thể thay đổi giá trị được (immutable) -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # Sinh ra biệt lệ kiểu TypeError - -# Lưu ý rằng tuple có độ dài là 1 phải có dấu phẩy theo sau phần tử cuối -# nhưng tuples có độ dài khác, ngay cả tuple rỗng, thì không cần như vậy -type((1)) # => -type((1,)) # => -type(()) # => - -# Hầu hết các phép toán của danh sách đều áp dụng được cho tuples -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# Bạn có thể gán giá trị cho nhiều biến một lúc bằng tuple (tuple unpacking) -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 -# Sau đây là unpacking kiểu mở rộng -a, *b, c = (1, 2, 3, 4) # a bây giờ là 1, b là [2, 3] và c là 4 -# Tuple được tự động tạo ra nếu bạn không để dấu ngoặc đơn -d, e, f = 4, 5, 6 -# Hoán đổi hai biến trở nên dễ dàng -e, d = d, e # d bây giờ là 5 và e là 4 - - -# Kiểu dữ liệu từ điển (dictionaries) lưu trữ ánh xạ từ các khóa (keys) đến các giá trị (values) -empty_dict = {} -# Sau đây là một từ điển có sẵn phần tử -filled_dict = {"one": 1, "two": 2, "three": 3} - -# Lưu ý rằng khóa của từ điển phải có kiểu dữ liệu thuộc loại immutable. Điều này để bảo đảm rằng -# khóa đó luôn được chuyển hóa thành một giá trị băm (hash value) duy nhất khi tìm kiếm trong từ điển -# Những kiểu immutable bao gồm số nguyên (int), số thực (float), chuỗi ký tự (string), hay tuple -invalid_dict = {[1,2,3]: "123"} # => Sinh ra biệt lệ kiểu TypeError: unhashable type: 'list' -valid_dict = {(1,2,3):[1,2,3]} # Tuy nhiên, giá trị có thể thuộc bất kỳ kiểu gì - -# Truy cập giá trị của một từ khóa bằng dấu [] -filled_dict["one"] # => 1 - -# Tất cả khóa trong một từ điển có thể được chuyển thành một đối tượng khả lặp (iterable). -# Chúng ta cần phải gọi hàm list() để chuyển một iterable thành một danh sách. -# Chúng ta sẽ bàn về vấn đề này sau. Lưu ý - Thứ tự của khóa trong từ điển sẽ không được đảm bảo. -# Những gì bạn thấy khi chạy dòng code dưới đây có thể sẽ không hoàn toàn giống như vậy. -list(filled_dict.keys()) # => ["three", "two", "one"] - - -# Tất cả các giá trị có thể chuyển thành một đối tượng khả lặp bằng cách gọi hàm "values()". -# Chúng ta cũng vẫn phải gọi hàm list() nếu muốn chuyển nó thành một danh sách. Lưu ý - thứ -# tự của giá trị cũng không được đảm bảo -list(filled_dict.values()) # => [3, 2, 1] - - -# Sự tồn tại của khóa trong từ điển có thể kiểm tra được thông qua từ khóa "in" -"one" in filled_dict # => True -1 in filled_dict # => False - -# Truy xuất giá trị của một khóa không tồn tại trong từ điển sẽ tạo ra biệt lệ KeyError -filled_dict["four"] # KeyError - -# Dừng phương thức "get()" để tránh tạo ra biệt lệ KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# Phương thức get hỗ trợ một đối số mặt định khi không thể tìm thấy giá trị ứng với từ khóa -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# "setdefault()" chèn một giá trị ứng với khóa nếu khóa đó không có sẵn trong từ điển -filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 - -# Thêm khóa và giá trị vào từ điển -filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -filled_dict["four"] = 4 # another way to add to dict - -# Xóa một khóa ra khỏi từ điển bằng từ khóa del -del filled_dict["one"] # Removes the key "one" from filled dict - -# Bắt đầu từ Python 3.5 bạn có thể unpack từ điển trong một từ điển khác -{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} -{'a': 1, **{'a': 2}} # => {'a': 2} - - - -# Kiểu tập hợp (set) lưu trữ ... tập hợp -empty_set = set() -# Khởi tạo giá trị một tập hợp với nhiều giá tri. Vâng, nhìn nó khá giống từ điển. -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} - -# Tương tự như khóa của từ điển, phần tử của một tập hợp cũng phải là immutable -invalid_set = {[1], 1} # => Sinh ra biệt lệ TypeError: unhashable type: 'list' -valid_set = {(1,), 1} - -# Thêm một phần tử vào tập hợp -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} - -# Thực hiện phép giao hai tập hợp bằng phép toán & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# Thực hiện phép hợp bằng phép toán | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# Lấy hiệu của hai tập hơp bằng phép toán - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# Lấy hiệu đối xứng bằng phép toán ^ -{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} - -# Kiểm tra tập hợp bên trái là tập cha của bên phải -{1, 2} >= {1, 2, 3} # => False - -# Kiểm tra xem tập hợp bên trái có phải là tập con của tập hợp bên phải -{1, 2} <= {1, 2, 3} # => True - -# Kiểm tra sự tồn tại của một phần tử trong tập hợp bằng từ khóa in -2 in filled_set # => True -10 in filled_set # => False - - - -#################################################### -## 3. Luồng điều khiển và kiểu khả lặp -#################################################### - -# Đầu tiên hãy tạo ra một biến -some_var = 5 - -# Sau đây là một câu lệnh if. Khoảng cách lề rất quan trọng trong Python -# Quy ước chung là dùng khoảng trắng chứ không phải ký tự tab -# Chuỗi sau sẽ được in ra "some_var is smaller than 10" -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # Phần elif là tùy chọn. - print("some_var is smaller than 10.") -else: # else cũng là tùy chọn. - print("some_var is indeed 10.") - - -""" -Lặp qua một danh sách bằng for -in ra: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # Bạn có thể dùng format() để gán một giá trị vào giữa chuỗi (string interpolation) - print("{} is a mammal".format(animal)) - -""" -"range(number)" trả về một đối tượng khả lặp kiểu số -từ 0 đến giá trị của number -in ra: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -"range(lower, upper)" trả về một đối tượng khả lặp kiểu số -từ giá trị lower đến giá trị upper -in ra: - 4 - 5 - 6 - 7 -""" -for i in range(4, 8): - print(i) - -""" -"range(lower, upper, step)" trả về một đối tượng khả lặp kiểu số -từ giá trị lower đến giá trị upper, tăng dần theo giá trị -của step. Nếu không có giá trị của step thì mặc định là 1. -in ra: - 4 - 6 -""" -for i in range(4, 8, 2): - print(i) -""" - -Vòng lặp while tiếp tục lặp khi điều kiện còn được thỏa mãn -in ra: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # cách viết ngán cho x = x + 1 - -# Handle exceptions with a try/except block -# Đối phó với biệt lệ bằng khối lệnh try/except -try: - # Dùng "raise" để ném ra một biệt lệ - raise IndexError("This is an index error") -except IndexError as e: - pass # pass có nghĩa là không làm gì cả. Thông thường đây là nơi để khắc phụ vấn đề làm xảy ra biệt lệ -except (TypeError, NameError): - pass # Nhiều biệt lệ có thể được đối phó cùng một lúc nếu cần -else: # Không bắt buộc phải sử dụng else nhưng nếu dùng thì nó phải sau tất cả các khối except - print("All good!") # Chỉ thực thi nếu không có biệt lệ phát sinh -finally: # Luôn thực thi trong mọi hoàn cảnh - print("We can clean up resources here") - -# Thay vì dùng try/finally để thu hồi tài nguyên (resources) ta có thể dùng with -with open("myfile.txt") as f: - for line in f: - print(line) - -# Python hỗ trợ kiểu dữ liệu khả lặp (iterable). -# Một đối tượng khả lặp có thể được xem như là một chuỗi các đối tượng tuần tự (sequence) -# Đối tượng trả về bởi hàm range là một khả lặp. - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']). Đây là một đối tượng khả lặp - -# Ta có thể lặp qua đối tượng -for i in our_iterable: - print(i) # In ra một, hai, ba - -# Tuy nhiên chúng ta không thể truy cập phần tử bằng chỉ mục -our_iterable[1] # Sinh ra biệt lệ TypeError - -# Một đối tượng khả lặp là đối tượng có thể tạo ra một iterator -our_iterator = iter(our_iterable) - -# iterator là một đối tượng ghi nhớ được trạng thái trong quá trình nó được duyệt qua -# đối tượng kế tiếp có thể truy cập được bằng hàm next -next(our_iterator) # => "one" - -# Nó ghi nhớ trạng thái trong quá trình lặp -next(our_iterator) # => "two" -next(our_iterator) # => "three" - -# Sau khi iterator đã trả về tất cả dữ liệu, nó sẽ sinh ra biệt lệ kiểu StopIteration -next(our_iterator) # Sinh ra biệt lệ StopIteration - -# Ta có thể lấy tất cả phần tử của một iterator bằng cách gọi hàm list với nó -list(filled_dict.keys()) # => Returns ["one", "two", "three"] - - -#################################################### -## 4. Hàm -#################################################### - -# Dùng từ khóa def để định nghĩa hàm -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # từ khóa return để trả về một giá trị - -# Gọi một hàm với đối số -add(5, 6) # => In ra "x is 5 and y is 6" và trả về 11 - -# Một cách khác để gọi hàm là dùng đối số có từ khóa (keyword arguments) -add(y=6, x=5) # Đối số có từ khóa có thể xuất hiện với thứ tự bất kỳ - -# Bạn có thể định nghĩa hàm có số lượng đối số vị trí (positional arguments) không biết trước -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - -# Số lượng tham số từ khóa cũng có thể không cần biết trước -def keyword_args(**kwargs): - return kwargs - -# Thử gọi hàm để xem điều gì xảy ra -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# Có thể định nghĩa hàm dùng cả hai loại đối số -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) in ra: - (1, 2) - {"a": 3, "b": 4} -""" - -# Khi gọi hàm, bạn có thể làm ngược với khi định nghĩa -# Dùng dấu * để lấy giá trị từ args và ** với giá trị từ kwargs -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # tương đương với foo(1, 2, 3, 4) -all_the_args(**kwargs) # tương đương với foo(a=3, b=4) -all_the_args(*args, **kwargs) # tương đương với foo(1, 2, 3, 4, a=3, b=4) - -# Trả về nhiều giá trị (gán vào một tuple) -def swap(x, y): - return y, x # Trả về nhiều giá trị dưới dạng một tuple mà không cần dấu ngoặc. - # (Lưu ý là dấu ngoặc đơn đã được bỏ đi những vẫn có thể được thêm vào) - -x = 1 -y = 2 -x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # dấu ngoặc đơn đã được bỏ đi những vẫn có thể được thêm vào - -# Tầm vực của hàm -x = 5 - -def set_x(num): - # Biến cục bộ x không đồng nhất với biến toàn cục x - x = num # => 43 - print(x) # => 43 - -def set_global_x(num): - global x - print(x) # => 5 - x = num # biến toàn cục x được gán giá trị là 6 - print(x) # => 6 - -set_x(43) -set_global_x(6) - - -# Hàm trong Python cũng là đối tượng -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# Có những hàm không tên -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 - -# Có những hàm cấp cao được hỗ trọ sẵn -list(map(add_10, [1, 2, 3])) # => [11, 12, 13] -list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] - -list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] - -# list comprehension có thể dùng để hay thế map và filter -# list comprehension lưu giá trị xuất vào một danh sách mà bản thân nó có thể lồng trong danh sách khác -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -# Tập hơp và từ điển cũng có thể được tao ra thông qua set comprehension và dict comprehension -{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} -{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - - -#################################################### -## 5. Mô đun -#################################################### - -# Bạn có thể import một mô đun -import math -print(math.sqrt(16)) # => 4.0 - -# Bạn có thể lấy một hàm cụ thể từ một mô đun -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# Hoặc import tất cả hàm từ một mô đun -# Cảnh báo: đây không phải là một cách hay -from math import * - -# Có thể làm tên của module ngắn lại -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Mô đun trong Python chỉ là những tập tin Python bình thường. Bạn -# có thể viết mô đun của mình và import chúng. Tên của mô đun -# cũng là tên của tập tin. - -# You can find out which functions and attributes -# are defined in a module. -# Bạn có thể liệt kê những hàm và thuộc tính -# được định nghĩa trong một mô đun -import math -dir(math) - -# Nếu bạn có một tập tin code Python gọi là math.py ở cùng -# thư mục với tập tin hiện tai, tập tin math.py sẽ -# được nạp vào thay vì mô đun được cung cấp sẵn (built-in) trong Python. -# Điều này xảy ra vì thư mục hiện tại có ưu tiên -# hơn những thư viện cung cấp sẵn. - - -#################################################### -## 6. Lớp (classes) -#################################################### - -# Ta dùng từ khóa "class" đề định nghĩa một lớp -class Human: - - # Một thuộc tính của lớp được chia sẽ bởi tất cả đối tượng của lớp này - species = "H. sapiens" - - # Hàm khởi tạo cơ bản sẽ được goi khi một đối tượng được tạo ra. - # Lưu ý 2 dấu gạch dưới ở đầu và cuối ám chỉ đối tượng - # hoặc thuộc tính dùng bở Python những tồn tại trong không gian tên - # do người dùng kiểm soát. Phương thức (hoặc thuộc tính) như: __init__, __str__, - # __repr__ v.v.. là những phương thức đặc biệt. - # Bạn không nên tự đặt những tên như vậy. - def __init__(self, name): - # Gán đối số vào thuộc tính name của đối tượng - self.name = name - - # Khởi tạo thuộc tính - self._age = 0 - - # Một phương thức trên đối tượng. Tất cả đều có đối số đầu tiên là "self" - def say(self, msg): - print ("{name}: {message}".format(name=self.name, message=msg)) - - # Một phương thức trên đối tượng khác - def sing(self): - return 'yo... yo... microphone check... one two... one two...' - - # Một phương thức trên lớp được chia sẻ với mọi đối tượng - # Lớp đó cũng là đối số thứ nhất của phương thức đó - @classmethod - def get_species(cls): - return cls.species - - # Một phương thức tĩnh được gọi mà không có lớp hay đối tượng đi kèm - @staticmethod - def grunt(): - return "*grunt*" - - # Một thuộc tính chỉ giống như một hàm truy xuất. - # Nó biến phương thức age() thành một thuộc tính chỉ đọc cùng tên. - # Tuy nhiên trong Python không nhất thiết phải viết những hàm đọc và ghi quá đơn giản - @property - def age(self): - return self._age - - # Đây là hàm để ghi giá trị cho thuộc tính - @age.setter - def age(self, age): - self._age = age - - # Đây là hàm để xóa thuộc tính - @age.deleter - def age(self): - del self._age - - -# Khi trình thông dịch Python đọc một tập tin mã nguồn, nó thực thi tất cả code trong đó. -# Kiểm tra giá trị của __name__ bảo đảm rằng đoạn mã bên dưới chỉ thực thi khi -# mô đun này là chương trình chính -if __name__ == '__main__': - # Khởi tạo một đối tượng - i = Human(name="Ian") - i.say("hi") # "Ian: hi" - j = Human("Joel") - j.say("hello") # "Joel: hello" - # i và j là thực thể của kiểu Human, nói cách khác: chúng là những đối tượng Human - - # Gọi những phương thức trên lớp - i.say(i.get_species()) # "Ian: H. sapiens" - # Thay đổi thuộc tính chung - Human.species = "H. neanderthalensis" - i.say(i.get_species()) # => "Ian: H. neanderthalensis" - j.say(j.get_species()) # => "Joel: H. neanderthalensis" - - # Gọi phương thức tĩnh - print(Human.grunt()) # => "*grunt*" - - # Không thể gọi phương thức tĩnh với một thực thể/đối tượng - # bởi vì i.grunt() sẽ tự động đặt "self" (tức là đối tượng i) làm đối số thứ nhất - print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given - - # Thay đổi thuộc tính của đối tượng - i.age = 42 - # Truy cập thuộc tính - i.say(i.age) # => "Ian: 42" - j.say(j.age) # => "Joel: 0" - # Xóa thuộc tính - del i.age - # i.age # => dòng nãy sẽ tạo ra biệt lệ AttributeError - - -#################################################### -## 6.1 Đa thừa kế -#################################################### - -# Một định nghĩa lớp khác -class Bat: - - species = 'Baty' - - def __init__(self, can_fly=True): - self.fly = can_fly - - # Lớp này có phương thức say - def say(self, msg): - msg = '... ... ...' - return msg - - # Và một phương thức khác - def sonar(self): - return '))) ... (((' - -if __name__ == '__main__': - b = Bat() - print(b.say('hello')) - print(b.fly) - -# Để tận dụng việc mô đun hóa thành từng tập tin, bạn có thể đặt những lớp định nghĩa ở trên vào các tập tin riêng, -# ví dụ như human.py và bat.py - -# Để import hàm từ tập tin khác dừng cấu trúc sau -# from "filename-without-extension" import "function-or-class" - -# superhero.py -from human import Human -from bat import Bat - -# Batman thừa kế từ lớp Human và Bat -class Batman(Human, Bat): - - # Batman có giá trị riêng cho thuộc tính trên lớp species - species = 'Superhero' - - def __init__(self, *args, **kwargs): - # Cách điển hình để thừa kế thuộc tính là gọi super - # super(Batman, self).__init__(*args, **kwargs) - # Tuy nhiên với đa thừa kế, super() sẽ chỉ gọi lớp cơ sở tiếp theo trong danh sách MRO. - # Vì thế, ta sẽ gọi cụ thể hàm __init__ của các lớp chả. - # Sử dụng *args và **kwargs cho phép việc truyền đối số gọn gàng hơn, - # trong đó mỗi lớp cha sẽ chịu trách nhiệm cho những phần thuộc về nó - Human.__init__(self, 'anonymous', *args, **kwargs) - Bat.__init__(self, *args, can_fly=False, **kwargs) - # ghi đè giá trị của thuộc tính name - self.name = 'Sad Affleck' - - def sing(self): - return 'nan nan nan nan nan batman!' - - -if __name__ == '__main__': - sup = Batman() - - # Kiểm tra kiểu đối tượng - if isinstance(sup, Human): - print('I am human') - if isinstance(sup, Bat): - print('I am bat') - if type(sup) is Batman: - print('I am Batman') - - # Truy xuất thứ tự phương thức của các lớp cha (Method Resolution search Order), vốn được dùng bởi cả getattr() và super9) - # Thuộc tính này động và có thể được cập nhật - print(Batman.__mro__) # => (, , , ) - - # Gọi phương thức của lớp cha nhưng dùng thuộc tính trên chính lớp hiện tại - print(sup.get_species()) # => Superhero - - # Gọi phương thức được nạp chồng - print(sup.sing()) # => nan nan nan nan nan batman! - - # Gọi phương thức của Human, bởi vì thứ tự thừa kế ảnh hưởng đến phương thức được gọi - sup.say('I agree') # => Sad Affleck: I agree - - # Gọi phương thức chỉ tồn tại ở lớp cha thứ 2 - print(sup.sonar()) # => ))) ... ((( - - # Thuộc tính cấp lớp được thừa kế - sup.age = 100 - print(sup.age) - - # Thuộc tính thừa kế từ lớp cha thứ 2 có giá trị mặc định đã bị ghi đè - print('Can I fly? ' + str(sup.fly)) - - - -#################################################### -## 7. Phần nâng cao -#################################################### - -# Generator giúp ta viết những đoạn code lười biếng (áp dụng nguyên tắc lazy evaluation) -def double_numbers(iterable): - for i in iterable: - yield i + i - -# Generators tiết kiệm bộ nhớ vì nó chỉ tải dữ liệu khi cần -# xử lý giá trị kế tiếp của một đối tượng khả lặp. Điều này cho phép generator thực hiện -# những thao tác mà bình thường không làm được trên những khoảng giá trị lớn -# Lưu ý: `range` thay thế `xrange` trong Python3. - -for i in double_numbers(range(1, 900000000)): # `range` là một generator. - print(i) - if i >= 30: - break - -# Cũng như danh sách có list comprehension, generator cũng có generator -# comprehension -values = (-x for x in [1,2,3,4,5]) -for x in values: - print(x) # in -1 -2 -3 -4 -5 ra màn hình dòng lệnh - -# Một generator cũng có thể bị ép kiểu thành danh sách -values = (-x for x in [1,2,3,4,5]) -gen_to_list = list(values) -print(gen_to_list) # => [-1, -2, -3, -4, -5] - - -# Decorators -# Trong ví dụ này hàm `beg` 'phủ lên' hàm `say`. Nếu say_please là True thì nó -# sẽ thay đội giá trị trả về -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Làm ơn! Tui rất nghèo :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Mua bia cho tui nhé?" - return msg, say_please - - -print(say()) # Mua bia cho tui nhé? -print(say(say_please=True)) # Mua bia cho tui nhé? Làm ơn! Tui rất nghèo :( -``` - -## Sẵn sàng để học nhiều hơn? - -### Miễn phí trên mạng - -* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Course](http://www.python-course.eu/index.php) -* [First Steps With Python](https://realpython.com/learn/python-first-steps/) -* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) -* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) -* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) -* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) -* [Dive Into Python 3](http://www.diveintopython3.net/index.html) -* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown new file mode 100644 index 00000000..fd962305 --- /dev/null +++ b/zh-cn/python-cn.html.markdown @@ -0,0 +1,632 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Geoff Liu", "http://geoffliu.me"] +filename: learnpython3-cn.py +lang: zh-cn +--- + +Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。 +它是如今最常用的编程语言之一。它的语法简洁且优美,几乎就是可执行的伪代码。 + +欢迎大家斧正。英文版原作 Louie Dinh [@louiedinh](http://twitter.com/louiedinh) +邮箱 louiedinh [at] [谷歌的信箱服务]。中文翻译 Geoff Liu。 + +注意:这篇教程是基于 Python 3 写的。如果你想学旧版 Python 2,我们特别有[另一篇教程](http://learnxinyminutes.com/docs/python/)。 + +```python + +# 用井字符开头的是单行注释 + +""" 多行字符串用三个引号 + 包裹,也常被用来做多 + 行注释 +""" + +#################################################### +## 1. 原始数据类型和运算符 +#################################################### + +# 整数 +3 # => 3 + +# 算术没有什么出乎意料的 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# 但是除法例外,会自动转换成浮点数 +35 / 5 # => 7.0 +5 / 3 # => 1.6666666666666667 + +# 整数除法的结果都是向下取整 +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # 浮点数也可以 +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# 浮点数的运算结果也是浮点数 +3 * 2.0 # => 6.0 + +# 模除 +7 % 3 # => 1 + +# x的y次方 +2**4 # => 16 + +# 用括号决定优先级 +(1 + 3) * 2 # => 8 + +# 布尔值 +True +False + +# 用not取非 +not True # => False +not False # => True + +# 逻辑运算符,注意and和or都是小写 +True and False # => False +False or True # => True + +# 整数也可以当作布尔值 +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# 用==判断相等 +1 == 1 # => True +2 == 1 # => False + +# 用!=判断不等 +1 != 1 # => False +2 != 1 # => True + +# 比较大小 +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# 大小比较可以连起来! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# 字符串用单引双引都可以 +"这是个字符串" +'这也是个字符串' + +# 用加号连接字符串 +"Hello " + "world!" # => "Hello world!" + +# 字符串可以被当作字符列表 +"This is a string"[0] # => 'T' + +# 用.format来格式化字符串 +"{} can be {}".format("strings", "interpolated") + +# 可以重复参数以节省时间 +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# 如果不想数参数,可以用关键字 +"{name} wants to eat {food}".format(name="Bob", food="lasagna") +# => "Bob wants to eat lasagna" + +# 如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法 +"%s can be %s the %s way" % ("strings", "interpolated", "old") + +# None是一个对象 +None # => None + +# 当与None进行比较时不要用 ==,要用is。is是用来比较两个变量是否指向同一个对象。 +"etc" is None # => False +None is None # => True + +# None,0,空字符串,空列表,空字典都算是False +# 所有其他值都是True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False + + +#################################################### +## 2. 变量和集合 +#################################################### + +# print是内置的打印函数 +print("I'm Python. Nice to meet you!") + +# 在给变量赋值前不用提前声明 +# 传统的变量命名是小写,用下划线分隔单词 +some_var = 5 +some_var # => 5 + +# 访问未赋值的变量会抛出异常 +# 参考流程控制一段来学习异常处理 +some_unknown_var # 抛出NameError + +# 用列表(list)储存序列 +li = [] +# 创建列表时也可以同时赋给元素 +other_li = [4, 5, 6] + +# 用append在列表最后追加元素 +li.append(1) # li现在是[1] +li.append(2) # li现在是[1, 2] +li.append(4) # li现在是[1, 2, 4] +li.append(3) # li现在是[1, 2, 4, 3] +# 用pop从列表尾部删除 +li.pop() # => 3 且li现在是[1, 2, 4] +# 把3再放回去 +li.append(3) # li变回[1, 2, 4, 3] + +# 列表存取跟数组一样 +li[0] # => 1 +# 取出最后一个元素 +li[-1] # => 3 + +# 越界存取会造成IndexError +li[4] # 抛出IndexError + +# 列表有切割语法 +li[1:3] # => [2, 4] +# 取尾 +li[2:] # => [4, 3] +# 取头 +li[:3] # => [1, 2, 4] +# 隔一个取一个 +li[::2] # =>[1, 4] +# 倒排列表 +li[::-1] # => [3, 4, 2, 1] +# 可以用三个参数的任何组合来构建切割 +# li[始:终:步伐] + +# 用del删除任何一个元素 +del li[2] # li is now [1, 2, 3] + +# 列表可以相加 +# 注意:li和other_li的值都不变 +li + other_li # => [1, 2, 3, 4, 5, 6] + +# 用extend拼接列表 +li.extend(other_li) # li现在是[1, 2, 3, 4, 5, 6] + +# 用in测试列表是否包含值 +1 in li # => True + +# 用len取列表长度 +len(li) # => 6 + + +# 元组是不可改变的序列 +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # 抛出TypeError + +# 列表允许的操作元组大都可以 +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# 可以把元组合列表解包,赋值给变量 +a, b, c = (1, 2, 3) # 现在a是1,b是2,c是3 +# 元组周围的括号是可以省略的 +d, e, f = 4, 5, 6 +# 交换两个变量的值就这么简单 +e, d = d, e # 现在d是5,e是4 + + +# 用字典表达映射关系 +empty_dict = {} +# 初始化的字典 +filled_dict = {"one": 1, "two": 2, "three": 3} + +# 用[]取值 +filled_dict["one"] # => 1 + + +# 用 keys 获得所有的键。 +# 因为 keys 返回一个可迭代对象,所以在这里把结果包在 list 里。我们下面会详细介绍可迭代。 +# 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。 +list(filled_dict.keys()) # => ["three", "two", "one"] + + +# 用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。 +list(filled_dict.values()) # => [3, 2, 1] + + +# 用in测试一个字典是否包含一个键 +"one" in filled_dict # => True +1 in filled_dict # => False + +# 访问不存在的键会导致KeyError +filled_dict["four"] # KeyError + +# 用get来避免KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# 当键不存在的时候get方法可以返回默认值 +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# setdefault方法只有当键不存在的时候插入新值 +filled_dict.setdefault("five", 5) # filled_dict["five"]设为5 +filled_dict.setdefault("five", 6) # filled_dict["five"]还是5 + +# 字典赋值 +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict["four"] = 4 # 另一种赋值方法 + +# 用del删除 +del filled_dict["one"] # 从filled_dict中把one删除 + + +# 用set表达集合 +empty_set = set() +# 初始化一个集合,语法跟字典相似。 +some_set = {1, 1, 2, 2, 3, 4} # some_set现在是{1, 2, 3, 4} + +# 可以把集合赋值于变量 +filled_set = some_set + +# 为集合添加元素 +filled_set.add(5) # filled_set现在是{1, 2, 3, 4, 5} + +# & 取交集 +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# | 取并集 +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# - 取补集 +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# in 测试集合是否包含元素 +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. 流程控制和迭代器 +#################################################### + +# 先随便定义一个变量 +some_var = 5 + +# 这是个if语句。注意缩进在Python里是有意义的 +# 印出"some_var比10小" +if some_var > 10: + print("some_var比10大") +elif some_var < 10: # elif句是可选的 + print("some_var比10小") +else: # else也是可选的 + print("some_var就是10") + + +""" +用for循环语句遍历列表 +打印: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + print("{} is a mammal".format(animal)) + +""" +"range(number)"返回数字列表从0到给的数字 +打印: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +while循环直到条件不满足 +打印: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # x = x + 1 的简写 + +# 用try/except块处理异常状况 +try: + # 用raise抛出异常 + raise IndexError("This is an index error") +except IndexError as e: + pass # pass是无操作,但是应该在这里处理错误 +except (TypeError, NameError): + pass # 可以同时处理不同类的错误 +else: # else语句是可选的,必须在所有的except之后 + print("All good!") # 只有当try运行完没有错误的时候这句才会运行 + + +# Python提供一个叫做可迭代(iterable)的基本抽象。一个可迭代对象是可以被当作序列 +# 的对象。比如说上面range返回的对象就是可迭代的。 + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['one', 'two', 'three']),是一个实现可迭代接口的对象 + +# 可迭代对象可以遍历 +for i in our_iterable: + print(i) # 打印 one, two, three + +# 但是不可以随机访问 +our_iterable[1] # 抛出TypeError + +# 可迭代对象知道怎么生成迭代器 +our_iterator = iter(our_iterable) + +# 迭代器是一个可以记住遍历的位置的对象 +# 用__next__可以取得下一个元素 +our_iterator.__next__() # => "one" + +# 再一次调取__next__时会记得位置 +our_iterator.__next__() # => "two" +our_iterator.__next__() # => "three" + +# 当迭代器所有元素都取出后,会抛出StopIteration +our_iterator.__next__() # 抛出StopIteration + +# 可以用list一次取出迭代器所有的元素 +list(filled_dict.keys()) # => Returns ["one", "two", "three"] + + + +#################################################### +## 4. 函数 +#################################################### + +# 用def定义新函数 +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # 用return语句返回 + +# 调用函数 +add(5, 6) # => 印出"x is 5 and y is 6"并且返回11 + +# 也可以用关键字参数来调用函数 +add(y=6, x=5) # 关键字参数可以用任何顺序 + + +# 我们可以定义一个可变参数函数 +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# 我们也可以定义一个关键字可变参数函数 +def keyword_args(**kwargs): + return kwargs + +# 我们来看看结果是什么: +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# 这两种可变参数可以混着用 +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# 调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。 +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # 相当于 foo(1, 2, 3, 4) +all_the_args(**kwargs) # 相当于 foo(a=3, b=4) +all_the_args(*args, **kwargs) # 相当于 foo(1, 2, 3, 4, a=3, b=4) + + +# 函数作用域 +x = 5 + +def setX(num): + # 局部作用域的x和全局域的x是不同的 + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # 现在全局域的x被赋值 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# 函数在Python是一等公民 +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# 也有匿名函数 +(lambda x: x > 2)(3) # => True + +# 内置的高阶函数 +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# 用列表推导式可以简化映射和过滤。列表推导式的返回值是另一个列表。 +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. 类 +#################################################### + + +# 定义一个继承object的类 +class Human(object): + + # 类属性,被所有此类的实例共用。 + species = "H. sapiens" + + # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属 + # 性或方法对Python有特殊意义,但是允许用户自行定义。你自己取名时不应该用这 + # 种格式。 + def __init__(self, name): + # Assign the argument to the instance's name attribute + self.name = name + + # 实例方法,第一个参数总是self,就是这个实例对象 + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # 类方法,被所有此类的实例共用。第一个参数是这个类对象。 + @classmethod + def get_species(cls): + return cls.species + + # 静态方法。调用时没有实例或类的绑定。 + @staticmethod + def grunt(): + return "*grunt*" + + +# 构造一个实例 +i = Human(name="Ian") +print(i.say("hi")) # 印出 "Ian: hi" + +j = Human("Joel") +print(j.say("hello")) # 印出 "Joel: hello" + +# 调用一个类方法 +i.get_species() # => "H. sapiens" + +# 改一个共用的类属性 +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# 调用静态方法 +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. 模块 +#################################################### + +# 用import导入模块 +import math +print(math.sqrt(16)) # => 4.0 + +# 也可以从模块中导入个别值 +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# 可以导入一个模块中所有值 +# 警告:不建议这么做 +from math import * + +# 如此缩写模块名字 +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python模块其实就是普通的Python文件。你可以自己写,然后导入, +# 模块的名字就是文件的名字。 + +# 你可以这样列出一个模块里所有的值 +import math +dir(math) + + +#################################################### +## 7. 高级用法 +#################################################### + +# 用生成器(generators)方便地写惰性运算 +def double_numbers(iterable): + for i in iterable: + yield i + i + +# 生成器只有在需要时才计算下一个值。它们每一次循环只生成一个值,而不是把所有的 +# 值全部算好。 +# +# range的返回值也是一个生成器,不然一个1到900000000的列表会花很多时间和内存。 +# +# 如果你想用一个Python的关键字当作变量名,可以加一个下划线来区分。 +range_ = range(1, 900000000) +# 当找到一个 >=30 的结果就会停 +# 这意味着 `double_numbers` 不会生成大于30的数。 +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# 装饰器(decorators) +# 这个例子中,beg装饰say +# beg会先调用say。如果返回的say_please为真,beg会改变返回的字符串。 +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +``` + +## 想继续学吗? + +### 线上免费材料(英文) + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) + +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/3/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### 书籍(也是英文) + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown deleted file mode 100644 index fd962305..00000000 --- a/zh-cn/python3-cn.html.markdown +++ /dev/null @@ -1,632 +0,0 @@ ---- -language: python3 -contributors: - - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Steven Basart", "http://github.com/xksteven"] - - ["Andre Polykanine", "https://github.com/Oire"] -translators: - - ["Geoff Liu", "http://geoffliu.me"] -filename: learnpython3-cn.py -lang: zh-cn ---- - -Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。 -它是如今最常用的编程语言之一。它的语法简洁且优美,几乎就是可执行的伪代码。 - -欢迎大家斧正。英文版原作 Louie Dinh [@louiedinh](http://twitter.com/louiedinh) -邮箱 louiedinh [at] [谷歌的信箱服务]。中文翻译 Geoff Liu。 - -注意:这篇教程是基于 Python 3 写的。如果你想学旧版 Python 2,我们特别有[另一篇教程](http://learnxinyminutes.com/docs/python/)。 - -```python - -# 用井字符开头的是单行注释 - -""" 多行字符串用三个引号 - 包裹,也常被用来做多 - 行注释 -""" - -#################################################### -## 1. 原始数据类型和运算符 -#################################################### - -# 整数 -3 # => 3 - -# 算术没有什么出乎意料的 -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 - -# 但是除法例外,会自动转换成浮点数 -35 / 5 # => 7.0 -5 / 3 # => 1.6666666666666667 - -# 整数除法的结果都是向下取整 -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # 浮点数也可以 --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 - -# 浮点数的运算结果也是浮点数 -3 * 2.0 # => 6.0 - -# 模除 -7 % 3 # => 1 - -# x的y次方 -2**4 # => 16 - -# 用括号决定优先级 -(1 + 3) * 2 # => 8 - -# 布尔值 -True -False - -# 用not取非 -not True # => False -not False # => True - -# 逻辑运算符,注意and和or都是小写 -True and False # => False -False or True # => True - -# 整数也可以当作布尔值 -0 and 2 # => 0 --5 or 0 # => -5 -0 == False # => True -2 == True # => False -1 == True # => True - -# 用==判断相等 -1 == 1 # => True -2 == 1 # => False - -# 用!=判断不等 -1 != 1 # => False -2 != 1 # => True - -# 比较大小 -1 < 10 # => True -1 > 10 # => False -2 <= 2 # => True -2 >= 2 # => True - -# 大小比较可以连起来! -1 < 2 < 3 # => True -2 < 3 < 2 # => False - -# 字符串用单引双引都可以 -"这是个字符串" -'这也是个字符串' - -# 用加号连接字符串 -"Hello " + "world!" # => "Hello world!" - -# 字符串可以被当作字符列表 -"This is a string"[0] # => 'T' - -# 用.format来格式化字符串 -"{} can be {}".format("strings", "interpolated") - -# 可以重复参数以节省时间 -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" - -# 如果不想数参数,可以用关键字 -"{name} wants to eat {food}".format(name="Bob", food="lasagna") -# => "Bob wants to eat lasagna" - -# 如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法 -"%s can be %s the %s way" % ("strings", "interpolated", "old") - -# None是一个对象 -None # => None - -# 当与None进行比较时不要用 ==,要用is。is是用来比较两个变量是否指向同一个对象。 -"etc" is None # => False -None is None # => True - -# None,0,空字符串,空列表,空字典都算是False -# 所有其他值都是True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False - - -#################################################### -## 2. 变量和集合 -#################################################### - -# print是内置的打印函数 -print("I'm Python. Nice to meet you!") - -# 在给变量赋值前不用提前声明 -# 传统的变量命名是小写,用下划线分隔单词 -some_var = 5 -some_var # => 5 - -# 访问未赋值的变量会抛出异常 -# 参考流程控制一段来学习异常处理 -some_unknown_var # 抛出NameError - -# 用列表(list)储存序列 -li = [] -# 创建列表时也可以同时赋给元素 -other_li = [4, 5, 6] - -# 用append在列表最后追加元素 -li.append(1) # li现在是[1] -li.append(2) # li现在是[1, 2] -li.append(4) # li现在是[1, 2, 4] -li.append(3) # li现在是[1, 2, 4, 3] -# 用pop从列表尾部删除 -li.pop() # => 3 且li现在是[1, 2, 4] -# 把3再放回去 -li.append(3) # li变回[1, 2, 4, 3] - -# 列表存取跟数组一样 -li[0] # => 1 -# 取出最后一个元素 -li[-1] # => 3 - -# 越界存取会造成IndexError -li[4] # 抛出IndexError - -# 列表有切割语法 -li[1:3] # => [2, 4] -# 取尾 -li[2:] # => [4, 3] -# 取头 -li[:3] # => [1, 2, 4] -# 隔一个取一个 -li[::2] # =>[1, 4] -# 倒排列表 -li[::-1] # => [3, 4, 2, 1] -# 可以用三个参数的任何组合来构建切割 -# li[始:终:步伐] - -# 用del删除任何一个元素 -del li[2] # li is now [1, 2, 3] - -# 列表可以相加 -# 注意:li和other_li的值都不变 -li + other_li # => [1, 2, 3, 4, 5, 6] - -# 用extend拼接列表 -li.extend(other_li) # li现在是[1, 2, 3, 4, 5, 6] - -# 用in测试列表是否包含值 -1 in li # => True - -# 用len取列表长度 -len(li) # => 6 - - -# 元组是不可改变的序列 -tup = (1, 2, 3) -tup[0] # => 1 -tup[0] = 3 # 抛出TypeError - -# 列表允许的操作元组大都可以 -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True - -# 可以把元组合列表解包,赋值给变量 -a, b, c = (1, 2, 3) # 现在a是1,b是2,c是3 -# 元组周围的括号是可以省略的 -d, e, f = 4, 5, 6 -# 交换两个变量的值就这么简单 -e, d = d, e # 现在d是5,e是4 - - -# 用字典表达映射关系 -empty_dict = {} -# 初始化的字典 -filled_dict = {"one": 1, "two": 2, "three": 3} - -# 用[]取值 -filled_dict["one"] # => 1 - - -# 用 keys 获得所有的键。 -# 因为 keys 返回一个可迭代对象,所以在这里把结果包在 list 里。我们下面会详细介绍可迭代。 -# 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。 -list(filled_dict.keys()) # => ["three", "two", "one"] - - -# 用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。 -list(filled_dict.values()) # => [3, 2, 1] - - -# 用in测试一个字典是否包含一个键 -"one" in filled_dict # => True -1 in filled_dict # => False - -# 访问不存在的键会导致KeyError -filled_dict["four"] # KeyError - -# 用get来避免KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# 当键不存在的时候get方法可以返回默认值 -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 - -# setdefault方法只有当键不存在的时候插入新值 -filled_dict.setdefault("five", 5) # filled_dict["five"]设为5 -filled_dict.setdefault("five", 6) # filled_dict["five"]还是5 - -# 字典赋值 -filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -filled_dict["four"] = 4 # 另一种赋值方法 - -# 用del删除 -del filled_dict["one"] # 从filled_dict中把one删除 - - -# 用set表达集合 -empty_set = set() -# 初始化一个集合,语法跟字典相似。 -some_set = {1, 1, 2, 2, 3, 4} # some_set现在是{1, 2, 3, 4} - -# 可以把集合赋值于变量 -filled_set = some_set - -# 为集合添加元素 -filled_set.add(5) # filled_set现在是{1, 2, 3, 4, 5} - -# & 取交集 -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} - -# | 取并集 -filled_set | other_set # => {1, 2, 3, 4, 5, 6} - -# - 取补集 -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} - -# in 测试集合是否包含元素 -2 in filled_set # => True -10 in filled_set # => False - - -#################################################### -## 3. 流程控制和迭代器 -#################################################### - -# 先随便定义一个变量 -some_var = 5 - -# 这是个if语句。注意缩进在Python里是有意义的 -# 印出"some_var比10小" -if some_var > 10: - print("some_var比10大") -elif some_var < 10: # elif句是可选的 - print("some_var比10小") -else: # else也是可选的 - print("some_var就是10") - - -""" -用for循环语句遍历列表 -打印: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - print("{} is a mammal".format(animal)) - -""" -"range(number)"返回数字列表从0到给的数字 -打印: - 0 - 1 - 2 - 3 -""" -for i in range(4): - print(i) - -""" -while循环直到条件不满足 -打印: - 0 - 1 - 2 - 3 -""" -x = 0 -while x < 4: - print(x) - x += 1 # x = x + 1 的简写 - -# 用try/except块处理异常状况 -try: - # 用raise抛出异常 - raise IndexError("This is an index error") -except IndexError as e: - pass # pass是无操作,但是应该在这里处理错误 -except (TypeError, NameError): - pass # 可以同时处理不同类的错误 -else: # else语句是可选的,必须在所有的except之后 - print("All good!") # 只有当try运行完没有错误的时候这句才会运行 - - -# Python提供一个叫做可迭代(iterable)的基本抽象。一个可迭代对象是可以被当作序列 -# 的对象。比如说上面range返回的对象就是可迭代的。 - -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']),是一个实现可迭代接口的对象 - -# 可迭代对象可以遍历 -for i in our_iterable: - print(i) # 打印 one, two, three - -# 但是不可以随机访问 -our_iterable[1] # 抛出TypeError - -# 可迭代对象知道怎么生成迭代器 -our_iterator = iter(our_iterable) - -# 迭代器是一个可以记住遍历的位置的对象 -# 用__next__可以取得下一个元素 -our_iterator.__next__() # => "one" - -# 再一次调取__next__时会记得位置 -our_iterator.__next__() # => "two" -our_iterator.__next__() # => "three" - -# 当迭代器所有元素都取出后,会抛出StopIteration -our_iterator.__next__() # 抛出StopIteration - -# 可以用list一次取出迭代器所有的元素 -list(filled_dict.keys()) # => Returns ["one", "two", "three"] - - - -#################################################### -## 4. 函数 -#################################################### - -# 用def定义新函数 -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # 用return语句返回 - -# 调用函数 -add(5, 6) # => 印出"x is 5 and y is 6"并且返回11 - -# 也可以用关键字参数来调用函数 -add(y=6, x=5) # 关键字参数可以用任何顺序 - - -# 我们可以定义一个可变参数函数 -def varargs(*args): - return args - -varargs(1, 2, 3) # => (1, 2, 3) - - -# 我们也可以定义一个关键字可变参数函数 -def keyword_args(**kwargs): - return kwargs - -# 我们来看看结果是什么: -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} - - -# 这两种可变参数可以混着用 -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) -""" -all_the_args(1, 2, a=3, b=4) prints: - (1, 2) - {"a": 3, "b": 4} -""" - -# 调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。 -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # 相当于 foo(1, 2, 3, 4) -all_the_args(**kwargs) # 相当于 foo(a=3, b=4) -all_the_args(*args, **kwargs) # 相当于 foo(1, 2, 3, 4, a=3, b=4) - - -# 函数作用域 -x = 5 - -def setX(num): - # 局部作用域的x和全局域的x是不同的 - x = num # => 43 - print (x) # => 43 - -def setGlobalX(num): - global x - print (x) # => 5 - x = num # 现在全局域的x被赋值 - print (x) # => 6 - -setX(43) -setGlobalX(6) - - -# 函数在Python是一等公民 -def create_adder(x): - def adder(y): - return x + y - return adder - -add_10 = create_adder(10) -add_10(3) # => 13 - -# 也有匿名函数 -(lambda x: x > 2)(3) # => True - -# 内置的高阶函数 -map(add_10, [1, 2, 3]) # => [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] - -# 用列表推导式可以简化映射和过滤。列表推导式的返回值是另一个列表。 -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] - -#################################################### -## 5. 类 -#################################################### - - -# 定义一个继承object的类 -class Human(object): - - # 类属性,被所有此类的实例共用。 - species = "H. sapiens" - - # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属 - # 性或方法对Python有特殊意义,但是允许用户自行定义。你自己取名时不应该用这 - # 种格式。 - def __init__(self, name): - # Assign the argument to the instance's name attribute - self.name = name - - # 实例方法,第一个参数总是self,就是这个实例对象 - def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) - - # 类方法,被所有此类的实例共用。第一个参数是这个类对象。 - @classmethod - def get_species(cls): - return cls.species - - # 静态方法。调用时没有实例或类的绑定。 - @staticmethod - def grunt(): - return "*grunt*" - - -# 构造一个实例 -i = Human(name="Ian") -print(i.say("hi")) # 印出 "Ian: hi" - -j = Human("Joel") -print(j.say("hello")) # 印出 "Joel: hello" - -# 调用一个类方法 -i.get_species() # => "H. sapiens" - -# 改一个共用的类属性 -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" - -# 调用静态方法 -Human.grunt() # => "*grunt*" - - -#################################################### -## 6. 模块 -#################################################### - -# 用import导入模块 -import math -print(math.sqrt(16)) # => 4.0 - -# 也可以从模块中导入个别值 -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 - -# 可以导入一个模块中所有值 -# 警告:不建议这么做 -from math import * - -# 如此缩写模块名字 -import math as m -math.sqrt(16) == m.sqrt(16) # => True - -# Python模块其实就是普通的Python文件。你可以自己写,然后导入, -# 模块的名字就是文件的名字。 - -# 你可以这样列出一个模块里所有的值 -import math -dir(math) - - -#################################################### -## 7. 高级用法 -#################################################### - -# 用生成器(generators)方便地写惰性运算 -def double_numbers(iterable): - for i in iterable: - yield i + i - -# 生成器只有在需要时才计算下一个值。它们每一次循环只生成一个值,而不是把所有的 -# 值全部算好。 -# -# range的返回值也是一个生成器,不然一个1到900000000的列表会花很多时间和内存。 -# -# 如果你想用一个Python的关键字当作变量名,可以加一个下划线来区分。 -range_ = range(1, 900000000) -# 当找到一个 >=30 的结果就会停 -# 这意味着 `double_numbers` 不会生成大于30的数。 -for i in double_numbers(range_): - print(i) - if i >= 30: - break - - -# 装饰器(decorators) -# 这个例子中,beg装饰say -# beg会先调用say。如果返回的say_please为真,beg会改变返回的字符串。 -from functools import wraps - - -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - - return wrapper - - -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please - - -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( -``` - -## 想继续学吗? - -### 线上免费材料(英文) - -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) - -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/3/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) - -### 书籍(也是英文) - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - -- cgit v1.2.3 From efe00fd06e2908f547ed8d47bd818301f96c4620 Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Wed, 12 Feb 2020 05:03:08 +0100 Subject: Switch links: 'python3 <-> python' and 'python <-> pythonlegacy' The list of references is exhausted by running 'ack docs/python'. --- ar-ar/python-ar.html.markdown | 2 +- cs-cz/python.html.markdown | 2 +- de-de/python-de.html.markdown | 2 +- el-gr/python-gr.html.markdown | 2 +- hu-hu/pythonlegacy-hu.html.markdown | 2 +- it-it/pythonlegacy-it.html.markdown | 2 +- ja-jp/python-jp.html.markdown | 2 +- python.html.markdown | 2 +- pythonlegacy.html.markdown | 2 +- tr-tr/python-tr.html.markdown | 2 +- vi-vn/python-vi.html.markdown | 2 +- zh-cn/python-cn.html.markdown | 2 +- zh-tw/pythonlegacy-tw.html.markdown | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/ar-ar/python-ar.html.markdown b/ar-ar/python-ar.html.markdown index e1a12690..1b75b596 100644 --- a/ar-ar/python-ar.html.markdown +++ b/ar-ar/python-ar.html.markdown @@ -19,7 +19,7 @@ filename: learnpython3-ar.py ردود أفعالكم عن المقال مُقدرة بشدة. يمكنكم التواصل مع الكاتب الاساسي من خلال [@louiedinh](http://twitter.com/louiedinh) أو louiedinh [at] [google's email service] -ملحوظة: هذا المقال يُطبق على بايثون 3 فقط. راجع المقال [هنا](http://learnxinyminutes.com/docs/python/) إذا أردت تعلم لغة البايثون نسخة 2.7 الأقدم +ملحوظة: هذا المقال يُطبق على بايثون 3 فقط. راجع المقال [هنا](http://learnxinyminutes.com/docs/pythonlegacy/) إذا أردت تعلم لغة البايثون نسخة 2.7 الأقدم ```python diff --git a/cs-cz/python.html.markdown b/cs-cz/python.html.markdown index bd3690a8..7086ec5f 100644 --- a/cs-cz/python.html.markdown +++ b/cs-cz/python.html.markdown @@ -17,7 +17,7 @@ Zamiloval jsem si Python pro jeho syntaktickou čistotu - je to vlastně spustit Vaše zpětná vazba je vítána! Můžete mě zastihnout na [@louiedinh](http://twitter.com/louiedinh) nebo louiedinh [at] [email od googlu] anglicky, autora českého překladu pak na [@tbedrich](http://twitter.com/tbedrich) nebo ja [at] tbedrich.cz -Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit starší Python 2.7](http://learnxinyminutes.com/docs/python/). +Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit starší Python 2.7](http://learnxinyminutes.com/docs/pythonlegacy/). ```python diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown index 4ef997a1..2c1e9ae0 100644 --- a/de-de/python-de.html.markdown +++ b/de-de/python-de.html.markdown @@ -14,7 +14,7 @@ Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist he Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service]. -Hinweis: Dieser Beitrag bezieht sich implizit auf Python 3. Falls du lieber Python 2.7 lernen möchtest, schau [hier](http://learnxinyminutes.com/docs/python/) weiter. +Hinweis: Dieser Beitrag bezieht sich implizit auf Python 3. Falls du lieber Python 2.7 lernen möchtest, schau [hier](http://learnxinyminutes.com/docs/pythonlegacy/) weiter. ```python diff --git a/el-gr/python-gr.html.markdown b/el-gr/python-gr.html.markdown index 445b85ba..2ae9cc75 100644 --- a/el-gr/python-gr.html.markdown +++ b/el-gr/python-gr.html.markdown @@ -20,7 +20,7 @@ lang: el-gr ή τον αρχικό συγγραφέα στο [@louiedinh](http://twitter.com/louiedinh) ή στο louiedinh [at] [google's email service] -Σημείωση: Το παρόν άρθρο ασχολείται μόνο με την Python 3. Δείτε [εδώ](http://learnxinyminutes.com/docs/python/) αν θέλετε να μάθετε την παλιά Python 2.7 +Σημείωση: Το παρόν άρθρο ασχολείται μόνο με την Python 3. Δείτε [εδώ](http://learnxinyminutes.com/docs/pythonlegacy/) αν θέλετε να μάθετε την παλιά Python 2.7 ```python diff --git a/hu-hu/pythonlegacy-hu.html.markdown b/hu-hu/pythonlegacy-hu.html.markdown index 01f1c414..ff2a3b3b 100644 --- a/hu-hu/pythonlegacy-hu.html.markdown +++ b/hu-hu/pythonlegacy-hu.html.markdown @@ -23,7 +23,7 @@ vagy pedig a louiedinh [kukac] [google email szolgáltatása] címen. Figyelem: ez a leírás a Python 2.7 verziójára vonatkozok, illetve általánosságban a 2.x verziókra. A Python 2.7 azonban már csak 2020-ig lesz támogatva, ezért kezdőknek ajánlott, hogy a Python 3-mal kezdjék az -ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python3/) +ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python/) ajánlott. Lehetséges olyan Python kódot írni, ami egyszerre kompatibilis a 2.7 és a 3.x diff --git a/it-it/pythonlegacy-it.html.markdown b/it-it/pythonlegacy-it.html.markdown index 794e7a70..0a8147b3 100644 --- a/it-it/pythonlegacy-it.html.markdown +++ b/it-it/pythonlegacy-it.html.markdown @@ -20,7 +20,7 @@ Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://tw Nota: questo articolo è riferito a Python 2.7 in modo specifico, ma dovrebbe andar bene anche per Python 2.x. Python 2.7 sta raggiungendo il "fine vita", ovvero non sarà più supportato nel 2020. Quindi è consigliato imparare Python utilizzando Python 3. -Per maggiori informazioni su Python 3.x, dai un'occhiata al [tutorial di Python 3](http://learnxinyminutes.com/docs/python3/). +Per maggiori informazioni su Python 3.x, dai un'occhiata al [tutorial di Python 3](http://learnxinyminutes.com/docs/python/). E' possibile anche scrivere codice compatibile sia con Python 2.7 che con Python 3.x, utilizzando [il modulo `__future__`](https://docs.python.org/2/library/__future__.html) di Python. diff --git a/ja-jp/python-jp.html.markdown b/ja-jp/python-jp.html.markdown index b9731411..3e01bfcd 100644 --- a/ja-jp/python-jp.html.markdown +++ b/ja-jp/python-jp.html.markdown @@ -21,7 +21,7 @@ lang: ja-jp フィードバッグは大歓迎です! [@louiedinh](http://twitter.com/louiedinh) または louiedinh [at] [google's email service] にご連絡下さい! -Note: この記事はPython 3に内容を絞っています。もし古いPython 2.7を学習したいなら、 [こちら](http://learnxinyminutes.com/docs/python/) をご確認下さい。 +Note: この記事はPython 3に内容を絞っています。もし古いPython 2.7を学習したいなら、 [こちら](http://learnxinyminutes.com/docs/pythonlegacy/) をご確認下さい。 ```python # 1行のコメントは番号記号(#)から始まります。 diff --git a/python.html.markdown b/python.html.markdown index f69ffb14..aac04469 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -16,7 +16,7 @@ Python was created by Guido van Rossum in the early 90s. It is now one of the mo languages in existence. I fell in love with Python for its syntactic clarity. It's basically executable pseudocode. -Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/python/) if you want to learn the old Python 2.7 +Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/pythonlegacy/) if you want to learn the old Python 2.7 ```python diff --git a/pythonlegacy.html.markdown b/pythonlegacy.html.markdown index 0cc33a80..61b19105 100644 --- a/pythonlegacy.html.markdown +++ b/pythonlegacy.html.markdown @@ -21,7 +21,7 @@ or louiedinh [at] [google's email service] Note: This article applies to Python 2.7 specifically, but should be applicable to Python 2.x. Python 2.7 is reaching end of life and will stop being maintained in 2020, it is though recommended to start learning Python with -Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). +Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python/). It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time, using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports diff --git a/tr-tr/python-tr.html.markdown b/tr-tr/python-tr.html.markdown index b78d517f..bba3d3ac 100644 --- a/tr-tr/python-tr.html.markdown +++ b/tr-tr/python-tr.html.markdown @@ -13,7 +13,7 @@ filename: learnpython3-tr.py Python,90ların başlarında Guido Van Rossum tarafından oluşturulmuştur. En popüler olan dillerden biridir. Beni Python'a aşık eden sebep onun syntax beraklığı. Çok basit bir çalıştırılabilir söz koddur. -Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [burayı](http://learnxinyminutes.com/docs/python/) kontrol edebilirsiniz. +Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [burayı](http://learnxinyminutes.com/docs/pythonlegacy/) kontrol edebilirsiniz. ```python diff --git a/vi-vn/python-vi.html.markdown b/vi-vn/python-vi.html.markdown index f6cce1a3..8c373d53 100644 --- a/vi-vn/python-vi.html.markdown +++ b/vi-vn/python-vi.html.markdown @@ -19,7 +19,7 @@ như một loại mã giả (pseudocode) có thể thực thi được. Mọi phản hồi đều sẽ được tích cực ghi nhận! Bạn có thể liên lạc với tôi qua Twitter [@louiedinh](http://twitter.com/louiedinh) hoặc louiedinh [at] [google's email service] -Lưu ý: Bài viết này áp dụng riêng cho Python 3. Truy cập [vào đây](http://learnxinyminutes.com/docs/python/) nếu bạn muốn học phiên bản cũ Python 2.7 +Lưu ý: Bài viết này áp dụng riêng cho Python 3. Truy cập [vào đây](http://learnxinyminutes.com/docs/pythonlegacy/) nếu bạn muốn học phiên bản cũ Python 2.7 ```python diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown index fd962305..0e11e12f 100644 --- a/zh-cn/python-cn.html.markdown +++ b/zh-cn/python-cn.html.markdown @@ -16,7 +16,7 @@ Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。 欢迎大家斧正。英文版原作 Louie Dinh [@louiedinh](http://twitter.com/louiedinh) 邮箱 louiedinh [at] [谷歌的信箱服务]。中文翻译 Geoff Liu。 -注意:这篇教程是基于 Python 3 写的。如果你想学旧版 Python 2,我们特别有[另一篇教程](http://learnxinyminutes.com/docs/python/)。 +注意:这篇教程是基于 Python 3 写的。如果你想学旧版 Python 2,我们特别有[另一篇教程](http://learnxinyminutes.com/docs/pythonlegacy/)。 ```python diff --git a/zh-tw/pythonlegacy-tw.html.markdown b/zh-tw/pythonlegacy-tw.html.markdown index cd7481d7..9b07a5ac 100644 --- a/zh-tw/pythonlegacy-tw.html.markdown +++ b/zh-tw/pythonlegacy-tw.html.markdown @@ -16,7 +16,7 @@ Python是在1990年代早期由Guido Van Rossum創建的。它是現在最流行 非常歡迎各位給我們任何回饋! 你可以在[@louiedinh](http://twitter.com/louiedinh) 或 louiedinh [at] [google's email service]聯絡到我。 註: 本篇文章適用的版本為Python 2.7,但大部分的Python 2.X版本應該都適用。 Python 2.7將會在2020年停止維護,因此建議您可以從Python 3開始學Python。 -Python 3.X可以看這篇[Python 3 教學 (英文)](http://learnxinyminutes.com/docs/python3/). +Python 3.X可以看這篇[Python 3 教學 (英文)](http://learnxinyminutes.com/docs/python/). 讓程式碼同時支援Python 2.7和3.X是可以做到的,只要引入 [`__future__` imports](https://docs.python.org/2/library/__future__.html) 模組. -- cgit v1.2.3 From 95c8b24ebf8b8e0ed02923787a9f793bdf295200 Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Wed, 12 Feb 2020 05:09:13 +0100 Subject: Python 2 'language': Python 2 (legacy) Instead of listing 'language: python' for Python 2, use language: Python 2 (legacy) ``` find . -iname "*pythonlegacy*" -exec \ sed -i 's/^language: .*/language: Python 2 (legacy)/' {} \; ``` --- de-de/pythonlegacy-de.html.markdown | 2 +- es-es/pythonlegacy-es.html.markdown | 2 +- fr-fr/pythonlegacy-fr.html.markdown | 2 +- hu-hu/pythonlegacy-hu.html.markdown | 2 +- it-it/pythonlegacy-it.html.markdown | 2 +- ko-kr/pythonlegacy-kr.html.markdown | 2 +- pl-pl/pythonlegacy-pl.html.markdown | 2 +- pt-br/pythonlegacy-pt.html.markdown | 2 +- pythonlegacy.html.markdown | 2 +- ro-ro/pythonlegacy-ro.html.markdown | 2 +- ru-ru/pythonlegacy-ru.html.markdown | 2 +- tr-tr/pythonlegacy-tr.html.markdown | 2 +- uk-ua/pythonlegacy-ua.html.markdown | 2 +- zh-cn/pythonlegacy-cn.html.markdown | 2 +- zh-tw/pythonlegacy-tw.html.markdown | 2 +- 15 files changed, 15 insertions(+), 15 deletions(-) diff --git a/de-de/pythonlegacy-de.html.markdown b/de-de/pythonlegacy-de.html.markdown index ee77683e..3f8f9783 100644 --- a/de-de/pythonlegacy-de.html.markdown +++ b/de-de/pythonlegacy-de.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: diff --git a/es-es/pythonlegacy-es.html.markdown b/es-es/pythonlegacy-es.html.markdown index 2b8f498a..db16b9bd 100644 --- a/es-es/pythonlegacy-es.html.markdown +++ b/es-es/pythonlegacy-es.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: diff --git a/fr-fr/pythonlegacy-fr.html.markdown b/fr-fr/pythonlegacy-fr.html.markdown index 0ae410de..03868580 100644 --- a/fr-fr/pythonlegacy-fr.html.markdown +++ b/fr-fr/pythonlegacy-fr.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) filename: learnpython-fr.py contributors: - ["Louie Dinh", "http://ldinh.ca"] diff --git a/hu-hu/pythonlegacy-hu.html.markdown b/hu-hu/pythonlegacy-hu.html.markdown index ff2a3b3b..3becdf34 100644 --- a/hu-hu/pythonlegacy-hu.html.markdown +++ b/hu-hu/pythonlegacy-hu.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) contributors: - ["Louie Dinh", "http://ldinh.ca"] - ["Amin Bandali", "https://aminb.org"] diff --git a/it-it/pythonlegacy-it.html.markdown b/it-it/pythonlegacy-it.html.markdown index 0a8147b3..fec0c7b7 100644 --- a/it-it/pythonlegacy-it.html.markdown +++ b/it-it/pythonlegacy-it.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) filename: learnpython-it.py contributors: - ["Louie Dinh", "http://ldinh.ca"] diff --git a/ko-kr/pythonlegacy-kr.html.markdown b/ko-kr/pythonlegacy-kr.html.markdown index 0145754d..f09bce4e 100644 --- a/ko-kr/pythonlegacy-kr.html.markdown +++ b/ko-kr/pythonlegacy-kr.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) category: language contributors: - ["Louie Dinh", "http://ldinh.ca"] diff --git a/pl-pl/pythonlegacy-pl.html.markdown b/pl-pl/pythonlegacy-pl.html.markdown index 222f753f..e620fffb 100644 --- a/pl-pl/pythonlegacy-pl.html.markdown +++ b/pl-pl/pythonlegacy-pl.html.markdown @@ -1,7 +1,7 @@ --- name: python category: language -language: python +language: Python 2 (legacy) filename: learnpython-pl.py contributors: - ["Louie Dinh", "http://ldinh.ca"] diff --git a/pt-br/pythonlegacy-pt.html.markdown b/pt-br/pythonlegacy-pt.html.markdown index 82b70117..399c193a 100644 --- a/pt-br/pythonlegacy-pt.html.markdown +++ b/pt-br/pythonlegacy-pt.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: diff --git a/pythonlegacy.html.markdown b/pythonlegacy.html.markdown index 61b19105..25c22f78 100644 --- a/pythonlegacy.html.markdown +++ b/pythonlegacy.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) contributors: - ["Louie Dinh", "http://ldinh.ca"] - ["Amin Bandali", "https://aminb.org"] diff --git a/ro-ro/pythonlegacy-ro.html.markdown b/ro-ro/pythonlegacy-ro.html.markdown index ada0c034..2badef08 100644 --- a/ro-ro/pythonlegacy-ro.html.markdown +++ b/ro-ro/pythonlegacy-ro.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: diff --git a/ru-ru/pythonlegacy-ru.html.markdown b/ru-ru/pythonlegacy-ru.html.markdown index 6087a686..21220c4d 100644 --- a/ru-ru/pythonlegacy-ru.html.markdown +++ b/ru-ru/pythonlegacy-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) lang: ru-ru contributors: - ["Louie Dinh", "http://ldinh.ca"] diff --git a/tr-tr/pythonlegacy-tr.html.markdown b/tr-tr/pythonlegacy-tr.html.markdown index 99a3eb4e..ce3c8cd7 100644 --- a/tr-tr/pythonlegacy-tr.html.markdown +++ b/tr-tr/pythonlegacy-tr.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) filename: learnpython-tr.py contributors: - ["Louie Dinh", "http://ldinh.ca"] diff --git a/uk-ua/pythonlegacy-ua.html.markdown b/uk-ua/pythonlegacy-ua.html.markdown index 4091e433..3244348c 100644 --- a/uk-ua/pythonlegacy-ua.html.markdown +++ b/uk-ua/pythonlegacy-ua.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) lang: uk-ua contributors: - ["Louie Dinh", "http://ldinh.ca"] diff --git a/zh-cn/pythonlegacy-cn.html.markdown b/zh-cn/pythonlegacy-cn.html.markdown index 65f125d1..98759857 100644 --- a/zh-cn/pythonlegacy-cn.html.markdown +++ b/zh-cn/pythonlegacy-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: diff --git a/zh-tw/pythonlegacy-tw.html.markdown b/zh-tw/pythonlegacy-tw.html.markdown index 9b07a5ac..e094f3fd 100644 --- a/zh-tw/pythonlegacy-tw.html.markdown +++ b/zh-tw/pythonlegacy-tw.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python 2 (legacy) contributors: - ["Louie Dinh", "http://ldinh.ca"] - ["Amin Bandali", "http://aminbandali.com"] -- cgit v1.2.3 From 8f5fac98958098864b86e2a09d8131d6dafaaddd Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Wed, 12 Feb 2020 05:15:29 +0100 Subject: Python 3: 'language: Python' Instead of listing 'language: python3' for Python 3, use language: Python as #3450 does. ``` find . -iname "python-*.markdown" -exec \ sed -i 's/language: python3/language: Python/' {} \; ``` --- ar-ar/python-ar.html.markdown | 2 +- de-de/python-de.html.markdown | 2 +- el-gr/python-gr.html.markdown | 2 +- es-es/python-es.html.markdown | 2 +- fr-fr/python-fr.html.markdown | 2 +- it-it/python-it.html.markdown | 2 +- ja-jp/python-jp.html.markdown | 2 +- pt-br/python-pt.html.markdown | 2 +- ru-ru/python-ru.html.markdown | 2 +- tr-tr/python-tr.html.markdown | 2 +- vi-vn/python-vi.html.markdown | 2 +- zh-cn/python-cn.html.markdown | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/ar-ar/python-ar.html.markdown b/ar-ar/python-ar.html.markdown index 1b75b596..8aa8dd37 100644 --- a/ar-ar/python-ar.html.markdown +++ b/ar-ar/python-ar.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: Python contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown index 2c1e9ae0..28a705f2 100644 --- a/de-de/python-de.html.markdown +++ b/de-de/python-de.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: Python contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: diff --git a/el-gr/python-gr.html.markdown b/el-gr/python-gr.html.markdown index 2ae9cc75..d81f4012 100644 --- a/el-gr/python-gr.html.markdown +++ b/el-gr/python-gr.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: Python contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown index 3236e73a..aa74aaf8 100644 --- a/es-es/python-es.html.markdown +++ b/es-es/python-es.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: Python contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] translators: diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown index 7112cd90..3dbec414 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: Python contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] diff --git a/it-it/python-it.html.markdown b/it-it/python-it.html.markdown index 04f78cff..abd86184 100644 --- a/it-it/python-it.html.markdown +++ b/it-it/python-it.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: Python filename: learnpython3-it.py contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] diff --git a/ja-jp/python-jp.html.markdown b/ja-jp/python-jp.html.markdown index 3e01bfcd..1f212aee 100644 --- a/ja-jp/python-jp.html.markdown +++ b/ja-jp/python-jp.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: Python contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] diff --git a/pt-br/python-pt.html.markdown b/pt-br/python-pt.html.markdown index bc5f801c..d3dfcb23 100644 --- a/pt-br/python-pt.html.markdown +++ b/pt-br/python-pt.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: Python contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index bf80fed2..179f339f 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: Python lang: ru-ru contributors: - ["Louie Dinh", "http://ldinh.ca"] diff --git a/tr-tr/python-tr.html.markdown b/tr-tr/python-tr.html.markdown index bba3d3ac..a1007f34 100644 --- a/tr-tr/python-tr.html.markdown +++ b/tr-tr/python-tr.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: Python contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] diff --git a/vi-vn/python-vi.html.markdown b/vi-vn/python-vi.html.markdown index 8c373d53..58154f35 100644 --- a/vi-vn/python-vi.html.markdown +++ b/vi-vn/python-vi.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: Python filename: learnpython3-vi.py contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown index 0e11e12f..e3804cf6 100644 --- a/zh-cn/python-cn.html.markdown +++ b/zh-cn/python-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: Python contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] -- cgit v1.2.3 From 887cbee8af080034177734b528819491e73a7a16 Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Wed, 12 Feb 2020 05:50:44 +0100 Subject: Change 'filename:' for Python 2 (legacy) Before renaming, all Python 2 filenames were 'learnpython-*.py'. This commit renames them to 'learnpythonlegacy-*.py'. To verify that the filenames were named consistently across translations prior to this commit, and to change this: ``` find . -name "pythonlegacy*.markdown" -exec ack filename: {} \; find . -name "pythonlegacy*.markdown" -exec \ sed -i 's/^filename: learnpython/filename: learnpythonlegacy/' {} \; ``` --- de-de/pythonlegacy-de.html.markdown | 2 +- es-es/pythonlegacy-es.html.markdown | 2 +- fr-fr/pythonlegacy-fr.html.markdown | 2 +- hu-hu/pythonlegacy-hu.html.markdown | 2 +- it-it/pythonlegacy-it.html.markdown | 2 +- ko-kr/pythonlegacy-kr.html.markdown | 2 +- pl-pl/pythonlegacy-pl.html.markdown | 2 +- pt-br/pythonlegacy-pt.html.markdown | 2 +- pythonlegacy.html.markdown | 2 +- ro-ro/pythonlegacy-ro.html.markdown | 2 +- ru-ru/pythonlegacy-ru.html.markdown | 2 +- tr-tr/pythonlegacy-tr.html.markdown | 2 +- uk-ua/pythonlegacy-ua.html.markdown | 2 +- zh-cn/pythonlegacy-cn.html.markdown | 2 +- zh-tw/pythonlegacy-tw.html.markdown | 2 +- 15 files changed, 15 insertions(+), 15 deletions(-) diff --git a/de-de/pythonlegacy-de.html.markdown b/de-de/pythonlegacy-de.html.markdown index 3f8f9783..d66a8551 100644 --- a/de-de/pythonlegacy-de.html.markdown +++ b/de-de/pythonlegacy-de.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: - ["kultprok", "http:/www.kulturproktologie.de"] -filename: learnpython-de.py +filename: learnpythonlegacy-de.py lang: de-de --- diff --git a/es-es/pythonlegacy-es.html.markdown b/es-es/pythonlegacy-es.html.markdown index db16b9bd..0a7304e9 100644 --- a/es-es/pythonlegacy-es.html.markdown +++ b/es-es/pythonlegacy-es.html.markdown @@ -6,7 +6,7 @@ translators: - ["Camilo Garrido", "http://www.twitter.com/hirohope"] - ["Fabio Souto", "http://fabiosouto.me"] lang: es-es -filename: learnpython-es.py +filename: learnpythonlegacy-es.py --- Python fue creado por Guido Van Rossum en el principio de los 90. Ahora es uno diff --git a/fr-fr/pythonlegacy-fr.html.markdown b/fr-fr/pythonlegacy-fr.html.markdown index 03868580..10b1a0a6 100644 --- a/fr-fr/pythonlegacy-fr.html.markdown +++ b/fr-fr/pythonlegacy-fr.html.markdown @@ -1,6 +1,6 @@ --- language: Python 2 (legacy) -filename: learnpython-fr.py +filename: learnpythonlegacy-fr.py contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: diff --git a/hu-hu/pythonlegacy-hu.html.markdown b/hu-hu/pythonlegacy-hu.html.markdown index 3becdf34..b5922766 100644 --- a/hu-hu/pythonlegacy-hu.html.markdown +++ b/hu-hu/pythonlegacy-hu.html.markdown @@ -9,7 +9,7 @@ contributors: - ["habi", "http://github.com/habi"] translators: - ["Tamás Diószegi", "https://github.com/ditam"] -filename: learnpython-hu.py +filename: learnpythonlegacy-hu.py lang: hu-hu --- diff --git a/it-it/pythonlegacy-it.html.markdown b/it-it/pythonlegacy-it.html.markdown index fec0c7b7..4c8b2a17 100644 --- a/it-it/pythonlegacy-it.html.markdown +++ b/it-it/pythonlegacy-it.html.markdown @@ -1,6 +1,6 @@ --- language: Python 2 (legacy) -filename: learnpython-it.py +filename: learnpythonlegacy-it.py contributors: - ["Louie Dinh", "http://ldinh.ca"] - ["Amin Bandali", "http://aminbandali.com"] diff --git a/ko-kr/pythonlegacy-kr.html.markdown b/ko-kr/pythonlegacy-kr.html.markdown index f09bce4e..978a9f33 100644 --- a/ko-kr/pythonlegacy-kr.html.markdown +++ b/ko-kr/pythonlegacy-kr.html.markdown @@ -3,7 +3,7 @@ language: Python 2 (legacy) category: language contributors: - ["Louie Dinh", "http://ldinh.ca"] -filename: learnpython-ko.py +filename: learnpythonlegacy-ko.py translators: - ["wikibook", "http://wikibook.co.kr"] lang: ko-kr diff --git a/pl-pl/pythonlegacy-pl.html.markdown b/pl-pl/pythonlegacy-pl.html.markdown index e620fffb..9e322658 100644 --- a/pl-pl/pythonlegacy-pl.html.markdown +++ b/pl-pl/pythonlegacy-pl.html.markdown @@ -2,7 +2,7 @@ name: python category: language language: Python 2 (legacy) -filename: learnpython-pl.py +filename: learnpythonlegacy-pl.py contributors: - ["Louie Dinh", "http://ldinh.ca"] - ["Amin Bandali", "http://aminbandali.com"] diff --git a/pt-br/pythonlegacy-pt.html.markdown b/pt-br/pythonlegacy-pt.html.markdown index 399c193a..572bb787 100644 --- a/pt-br/pythonlegacy-pt.html.markdown +++ b/pt-br/pythonlegacy-pt.html.markdown @@ -5,7 +5,7 @@ contributors: translators: - ["Vilson Vieira", "http://automata.cc"] lang: pt-br -filename: learnpython-pt.py +filename: learnpythonlegacy-pt.py --- Python foi criado por Guido Van Rossum no começo dos anos 90. Atualmente é uma diff --git a/pythonlegacy.html.markdown b/pythonlegacy.html.markdown index 25c22f78..95d6aa63 100644 --- a/pythonlegacy.html.markdown +++ b/pythonlegacy.html.markdown @@ -8,7 +8,7 @@ contributors: - ["asyne", "https://github.com/justblah"] - ["habi", "http://github.com/habi"] - ["Rommel Martinez", "https://ebzzry.io"] -filename: learnpython.py +filename: learnpythonlegacy.py --- Python was created by Guido Van Rossum in the early 90s. It is now one of the diff --git a/ro-ro/pythonlegacy-ro.html.markdown b/ro-ro/pythonlegacy-ro.html.markdown index 2badef08..a368ff99 100644 --- a/ro-ro/pythonlegacy-ro.html.markdown +++ b/ro-ro/pythonlegacy-ro.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: - ["Ovidiu Ciule", "https://github.com/ociule"] -filename: learnpython-ro.py +filename: learnpythonlegacy-ro.py lang: ro-ro --- diff --git a/ru-ru/pythonlegacy-ru.html.markdown b/ru-ru/pythonlegacy-ru.html.markdown index 21220c4d..ead2af3d 100644 --- a/ru-ru/pythonlegacy-ru.html.markdown +++ b/ru-ru/pythonlegacy-ru.html.markdown @@ -6,7 +6,7 @@ contributors: translators: - ["Yury Timofeev", "http://twitter.com/gagar1n"] - ["Andre Polykanine", "https://github.com/Oire"] -filename: learnpython-ru.py +filename: learnpythonlegacy-ru.py --- Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из diff --git a/tr-tr/pythonlegacy-tr.html.markdown b/tr-tr/pythonlegacy-tr.html.markdown index ce3c8cd7..cd757625 100644 --- a/tr-tr/pythonlegacy-tr.html.markdown +++ b/tr-tr/pythonlegacy-tr.html.markdown @@ -1,6 +1,6 @@ --- language: Python 2 (legacy) -filename: learnpython-tr.py +filename: learnpythonlegacy-tr.py contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: diff --git a/uk-ua/pythonlegacy-ua.html.markdown b/uk-ua/pythonlegacy-ua.html.markdown index 3244348c..e2a6d19e 100644 --- a/uk-ua/pythonlegacy-ua.html.markdown +++ b/uk-ua/pythonlegacy-ua.html.markdown @@ -10,7 +10,7 @@ contributors: - ["habi", "http://github.com/habi"] translators: - ["Oleh Hromiak", "https://github.com/ogroleg"] -filename: learnpython-ua.py +filename: learnpythonlegacy-ua.py --- Мову Python створив Гвідо ван Россум на початку 90-х. Наразі це одна з diff --git a/zh-cn/pythonlegacy-cn.html.markdown b/zh-cn/pythonlegacy-cn.html.markdown index 98759857..756081d6 100644 --- a/zh-cn/pythonlegacy-cn.html.markdown +++ b/zh-cn/pythonlegacy-cn.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: - ["Chenbo Li", "http://binarythink.net"] -filename: learnpython-zh.py +filename: learnpythonlegacy-zh.py lang: zh-cn --- diff --git a/zh-tw/pythonlegacy-tw.html.markdown b/zh-tw/pythonlegacy-tw.html.markdown index e094f3fd..575897e2 100644 --- a/zh-tw/pythonlegacy-tw.html.markdown +++ b/zh-tw/pythonlegacy-tw.html.markdown @@ -7,7 +7,7 @@ contributors: - ["evuez", "http://github.com/evuez"] translators: - ["Michael Yeh", "https://hinet60613.github.io/"] -filename: learnpython-tw.py +filename: learnpythonlegacy-tw.py lang: zh-tw --- -- cgit v1.2.3 From ae848c481fabaca935ffbe33293a43a43434d268 Mon Sep 17 00:00:00 2001 From: Simon Shine Date: Wed, 12 Feb 2020 06:23:31 +0100 Subject: Python 3: Use 'filename: learnpython*.py' (no '3') Before renaming, Python 3 filenames were 'learnpython3*.py'. This commit removes the '3' part from the filename. To verify that the filenames were named consistently across translations prior to this commit, and to change this: ``` ack -H 'filename:' python.html.markdown find . -name "python-*.markdown" -exec ack -H 'filename:' {} \; sed -i 's/^filename: learnpython3/filename: learnpython/' \ python.html.markdown find . -name "python-*.markdown" -exec \ sed -i 's/^filename: learnpython3/filename: learnpython/' {} \; ``` --- ar-ar/python-ar.html.markdown | 2 +- de-de/python-de.html.markdown | 2 +- el-gr/python-gr.html.markdown | 2 +- es-es/python-es.html.markdown | 2 +- fr-fr/python-fr.html.markdown | 2 +- it-it/python-it.html.markdown | 2 +- ja-jp/python-jp.html.markdown | 2 +- pt-br/python-pt.html.markdown | 2 +- python.html.markdown | 2 +- ru-ru/python-ru.html.markdown | 2 +- tr-tr/python-tr.html.markdown | 2 +- vi-vn/python-vi.html.markdown | 2 +- zh-cn/python-cn.html.markdown | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/ar-ar/python-ar.html.markdown b/ar-ar/python-ar.html.markdown index 8aa8dd37..f89c2f25 100644 --- a/ar-ar/python-ar.html.markdown +++ b/ar-ar/python-ar.html.markdown @@ -11,7 +11,7 @@ contributors: translators: - ["Ahmad Hegazy", "https://github.com/ahegazy"] lang: ar-ar -filename: learnpython3-ar.py +filename: learnpython-ar.py --- لقد أُنشئت لغة البايثون بواسطة جايدو ڤان روسم في بداية التسعينات. هي الأن أحد أشهر اللغات الموجودة. diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown index 28a705f2..9eebff41 100644 --- a/de-de/python-de.html.markdown +++ b/de-de/python-de.html.markdown @@ -5,7 +5,7 @@ contributors: translators: - ["kultprok", "http:/www.kulturproktologie.de"] - ["matthiaskern", "https://github.com/matthiaskern"] -filename: learnpython3-de.py +filename: learnpython-de.py lang: de-de --- diff --git a/el-gr/python-gr.html.markdown b/el-gr/python-gr.html.markdown index d81f4012..203c6e78 100644 --- a/el-gr/python-gr.html.markdown +++ b/el-gr/python-gr.html.markdown @@ -8,7 +8,7 @@ contributors: - ["evuez", "http://github.com/evuez"] - ["Rommel Martinez", "https://ebzzry.io"] - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] -filename: learnpython3-gr.py +filename: learnpython-gr.py lang: el-gr --- diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown index aa74aaf8..7deec286 100644 --- a/es-es/python-es.html.markdown +++ b/es-es/python-es.html.markdown @@ -5,7 +5,7 @@ contributors: translators: - ["Camilo Garrido", "http://twitter.com/hirohope"] lang: es-es -filename: learnpython3-es.py +filename: learnpython-es.py --- Python fue creado por Guido Van Rossum en el principio de los 90'. Ahora es uno diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown index 3dbec414..ca510d66 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -8,7 +8,7 @@ contributors: translators: - ["Gnomino", "https://github.com/Gnomino"] - ["Julien M'Poy", "http://github.com/groovytron"] -filename: learnpython3-fr.py +filename: learnpython-fr.py lang: fr-fr --- diff --git a/it-it/python-it.html.markdown b/it-it/python-it.html.markdown index abd86184..de7bb0ed 100644 --- a/it-it/python-it.html.markdown +++ b/it-it/python-it.html.markdown @@ -1,6 +1,6 @@ --- language: Python -filename: learnpython3-it.py +filename: learnpython-it.py contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] diff --git a/ja-jp/python-jp.html.markdown b/ja-jp/python-jp.html.markdown index 1f212aee..c80b4d4c 100644 --- a/ja-jp/python-jp.html.markdown +++ b/ja-jp/python-jp.html.markdown @@ -11,7 +11,7 @@ contributors: translators: - ["kakakaya", "https://github.com/kakakaya"] - ["Ryota Kayanuma", "https://github.com/PicoSushi"] -filename: learnpython3-jp.py +filename: learnpython-jp.py lang: ja-jp --- diff --git a/pt-br/python-pt.html.markdown b/pt-br/python-pt.html.markdown index d3dfcb23..3f9c54c1 100644 --- a/pt-br/python-pt.html.markdown +++ b/pt-br/python-pt.html.markdown @@ -9,7 +9,7 @@ translators: - ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"] - ["Monique Baptista", "https://github.com/bfmonique"] lang: pt-br -filename: learnpython3-pt.py +filename: learnpython-pt.py --- Python foi criada por Guido Van Rossum nos anos 1990. Ela é atualmente uma diff --git a/python.html.markdown b/python.html.markdown index aac04469..2e1f8c90 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -9,7 +9,7 @@ contributors: - ["Rommel Martinez", "https://ebzzry.io"] - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] - ["caminsha", "https://github.com/caminsha"] -filename: learnpython3.py +filename: learnpython.py --- Python was created by Guido van Rossum in the early 90s. It is now one of the most popular diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index 179f339f..b2c00baf 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -6,7 +6,7 @@ contributors: - ["Steven Basart", "http://github.com/xksteven"] translators: - ["Andre Polykanine", "https://github.com/Oire"] -filename: learnpython3-ru.py +filename: learnpython-ru.py --- Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из diff --git a/tr-tr/python-tr.html.markdown b/tr-tr/python-tr.html.markdown index a1007f34..6d9cdcbe 100644 --- a/tr-tr/python-tr.html.markdown +++ b/tr-tr/python-tr.html.markdown @@ -8,7 +8,7 @@ contributors: translators: - ["Eray AYDIN", "http://erayaydin.me/"] lang: tr-tr -filename: learnpython3-tr.py +filename: learnpython-tr.py --- Python,90ların başlarında Guido Van Rossum tarafından oluşturulmuştur. En popüler olan dillerden biridir. Beni Python'a aşık eden sebep onun syntax beraklığı. Çok basit bir çalıştırılabilir söz koddur. diff --git a/vi-vn/python-vi.html.markdown b/vi-vn/python-vi.html.markdown index 58154f35..89e51d5d 100644 --- a/vi-vn/python-vi.html.markdown +++ b/vi-vn/python-vi.html.markdown @@ -1,6 +1,6 @@ --- language: Python -filename: learnpython3-vi.py +filename: learnpython-vi.py contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown index e3804cf6..da13275b 100644 --- a/zh-cn/python-cn.html.markdown +++ b/zh-cn/python-cn.html.markdown @@ -6,7 +6,7 @@ contributors: - ["Andre Polykanine", "https://github.com/Oire"] translators: - ["Geoff Liu", "http://geoffliu.me"] -filename: learnpython3-cn.py +filename: learnpython-cn.py lang: zh-cn --- -- cgit v1.2.3 From 5864aba42d2cf57dfe96049568b3a9689ea6a813 Mon Sep 17 00:00:00 2001 From: Leigh Brenecki Date: Thu, 13 Feb 2020 10:38:29 +1030 Subject: Purge my deadname --- .mailmap | 1 + cs-cz/javascript.html.markdown | 2 +- de-de/javascript-de.html.markdown | 4 ++-- de-de/yaml-de.html.markdown | 2 +- es-es/javascript-es.html.markdown | 6 +++--- es-es/yaml-es.html.markdown | 2 +- fa-ir/javascript-fa.html.markdown | 6 +++--- fr-fr/javascript-fr.html.markdown | 2 +- hu-hu/yaml-hu.html.markdown | 2 +- it-it/javascript-it.html.markdown | 2 +- javascript.html.markdown | 2 +- ko-kr/javascript-kr.html.markdown | 6 +++--- ko-kr/yaml-kr.html.markdown | 2 +- ms-my/javascript-my.html.markdown | 2 +- nl-nl/yaml-nl.html.markdown | 2 +- pt-br/javascript-pt.html.markdown | 6 +++--- pt-br/yaml-pt.html.markdown | 2 +- ru-ru/javascript-ru.html.markdown | 2 +- ru-ru/yaml-ru.html.markdown | 2 +- ta_in/javascript-ta.html.markdown | 6 +++--- uk-ua/javascript-ua.html.markdown | 2 +- yaml.html.markdown | 2 +- zh-cn/javascript-cn.html.markdown | 6 +++--- zh-cn/yaml-cn.html.markdown | 2 +- 24 files changed, 37 insertions(+), 36 deletions(-) create mode 100644 .mailmap diff --git a/.mailmap b/.mailmap new file mode 100644 index 00000000..b69f76fe --- /dev/null +++ b/.mailmap @@ -0,0 +1 @@ +Leigh Brenecki diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown index c05a9138..408ddde0 100644 --- a/cs-cz/javascript.html.markdown +++ b/cs-cz/javascript.html.markdown @@ -1,7 +1,7 @@ --- language: javascript contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Leigh Brenecki", "https://leigh.net.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] translators: - ["Michal Martinek", "https://github.com/MichalMartinek"] diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index f3917506..f817ee9f 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -1,7 +1,7 @@ --- language: javascript contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Leigh Brenecki", "https://leigh.net.au"] translators: - ["ggb", "http://www.ideen-und-soehne.de"] filename: learnjavascript-de.js @@ -13,7 +13,7 @@ JavaScript wurde im Jahr 1995 von Brendan Eich bei Netscape entwickelt. Ursprün Dabei ist JavaScript inzwischen nicht mehr auf Browser beschränkt: Node.js, ein Projekt, das eine eigene Laufzeitumgebung auf Grundlage von Google Chromes V8 mitbringt, wird derzeit immer populärer. -Feedback ist herzlich Willkommen! Der ursprüngliche Autor ist unter [@adambrenecki](https://twitter.com/adambrenecki) oder [adam@brenecki.id.au](mailto:adam@brenecki.id.au) zu erreichen. Der Übersetzer unter [gregorbg@web.de](mailto:gregorbg@web.de). +Feedback ist herzlich Willkommen! Der ursprüngliche Autor ist unter [@excitedleigh](https://twitter.com/excitedleigh) oder [l@leigh.net.au](mailto:l@leigh.net.au) zu erreichen. Der Übersetzer unter [gregorbg@web.de](mailto:gregorbg@web.de). ```js // Kommentare werden wie in C gesetzt: Einzeilige Kommentare starten mit zwei diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown index ff45dc8d..0332c912 100644 --- a/de-de/yaml-de.html.markdown +++ b/de-de/yaml-de.html.markdown @@ -1,7 +1,7 @@ --- language: yaml contributors: - - ["Adam Brenecki", "https://github.com/adambrenecki"] + - ["Leigh Brenecki", "https://github.com/adambrenecki"] translators: - ["Ruben M.", "https://github.com/switchhax"] filename: learnyaml-de.yaml diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index 31512dc4..050154c7 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -1,7 +1,7 @@ --- language: javascript contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Leigh Brenecki", "https://leigh.net.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] translators: - ["Daniel Zendejas","https://github.com/DanielZendejas"] @@ -19,8 +19,8 @@ para front-end que Java. Sin embargo, JavaScript no sólo se limita a los navegadores web: Node.js, un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular. ¡La retroalimentación es bienvenida! Puedes encontrarme en: -[@adambrenecki](https://twitter.com/adambrenecki), o -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). +[@ExcitedLeigh](https://twitter.com/ExcitedLeigh), o +[l@leigh.net.au](mailto:l@leigh.net.au). ```js // Los comentarios en JavaScript son los mismos como comentarios en C. diff --git a/es-es/yaml-es.html.markdown b/es-es/yaml-es.html.markdown index cd3143fb..582fa60e 100644 --- a/es-es/yaml-es.html.markdown +++ b/es-es/yaml-es.html.markdown @@ -3,7 +3,7 @@ language: yaml lang: es-es filename: learnyaml-es.yaml contributors: - - ["Adam Brenecki", "https://github.com/adambrenecki"] + - ["Leigh Brenecki", "https://github.com/adambrenecki"] - ["Everardo Medina","https://github.com/everblut"] translators: - ["Daniel Zendejas","https://github.com/DanielZendejas"] diff --git a/fa-ir/javascript-fa.html.markdown b/fa-ir/javascript-fa.html.markdown index fe3555af..d4d3a657 100644 --- a/fa-ir/javascript-fa.html.markdown +++ b/fa-ir/javascript-fa.html.markdown @@ -1,7 +1,7 @@ --- language: javascript contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Leigh Brenecki", "https://leigh.net.au"] translators: - ["Mohammad Valipour", "https://github.com/mvalipour"] filename: javascript-fa.js @@ -17,8 +17,8 @@ lang: fa-ir قدر دان نظرات سازنده شما هستم! شما میتوانید از طریق زیر با من تماس بگیرید:

-[@adambrenecki](https://twitter.com/adambrenecki), or -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). +[@ExcitedLeigh](https://twitter.com/ExcitedLeigh), or +[l@leigh.net.au](mailto:l@leigh.net.au).

// توضیحات همانند C هستند. توضیحات یک خطی با دو خط مورب شروع میشوند., diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index faa22863..7aad2da8 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -1,7 +1,7 @@ --- language: javascript contributors: - - ['Adam Brenecki', 'http://adam.brenecki.id.au'] + - ['Leigh Brenecki', 'https://leigh.net.au'] - ['Ariel Krakowski', 'http://www.learneroo.com'] filename: javascript-fr.js translators: diff --git a/hu-hu/yaml-hu.html.markdown b/hu-hu/yaml-hu.html.markdown index 37ce4cb2..3fb8b87f 100644 --- a/hu-hu/yaml-hu.html.markdown +++ b/hu-hu/yaml-hu.html.markdown @@ -2,7 +2,7 @@ language: yaml filename: learnyaml-hu.yaml contributors: - - ["Adam Brenecki", "https://github.com/adambrenecki"] + - ["Leigh Brenecki", "https://github.com/adambrenecki"] translators: - ["Tamás Diószegi", "https://github.com/ditam"] lang: hu-hu diff --git a/it-it/javascript-it.html.markdown b/it-it/javascript-it.html.markdown index 68bf6287..1d776535 100644 --- a/it-it/javascript-it.html.markdown +++ b/it-it/javascript-it.html.markdown @@ -1,7 +1,7 @@ --- language: javascript contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Leigh Brenecki", "https://leigh.net.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] translators: - ["vinniec", "https://github.com/vinniec"] diff --git a/javascript.html.markdown b/javascript.html.markdown index ad1af76a..3c0e6d4f 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -1,7 +1,7 @@ --- language: javascript contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Leigh Brenecki", "https://leigh.net.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] filename: javascript.js --- diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown index 9561e80c..619d8104 100644 --- a/ko-kr/javascript-kr.html.markdown +++ b/ko-kr/javascript-kr.html.markdown @@ -2,7 +2,7 @@ language: javascript category: language contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Leigh Brenecki", "https://leigh.net.au"] translators: - ["wikibook", "http://wikibook.co.kr"] filename: javascript-kr.js @@ -18,8 +18,8 @@ lang: ko-kr 그렇지만 자바스크립트는 웹 브라우저에만 국한되지 않습니다. 구글 크롬의 V8 자바스크립트 엔진을 위한 독립형 런타임을 제공하는 Node.js는 점점 인기를 얻고 있습니다. -피드백 주시면 대단히 감사하겠습니다! [@adambrenecki](https://twitter.com/adambrenecki)나 -[adam@brenecki.id.au](mailto:adam@brenecki.id.au)를 통해 저와 만나실 수 있습니다. +피드백 주시면 대단히 감사하겠습니다! [@ExcitedLeigh](https://twitter.com/ExcitedLeigh)나 +[l@leigh.net.au](mailto:l@leigh.net.au)를 통해 저와 만나실 수 있습니다. ```js // 주석은 C와 비슷합니다. 한 줄짜리 주석은 두 개의 슬래시로 시작하고, diff --git a/ko-kr/yaml-kr.html.markdown b/ko-kr/yaml-kr.html.markdown index b6d1de41..4b1b29d2 100644 --- a/ko-kr/yaml-kr.html.markdown +++ b/ko-kr/yaml-kr.html.markdown @@ -2,7 +2,7 @@ language: yaml filename: learnyaml-kr.yaml contributors: - - ["Adam Brenecki", "https://github.com/adambrenecki"] + - ["Leigh Brenecki", "https://github.com/adambrenecki"] - ["Suhas SG", "https://github.com/jargnar"] translators: - ["Wooseop Kim", "https://github.com/linterpreteur"] diff --git a/ms-my/javascript-my.html.markdown b/ms-my/javascript-my.html.markdown index 90e37133..9a7a23ba 100644 --- a/ms-my/javascript-my.html.markdown +++ b/ms-my/javascript-my.html.markdown @@ -1,7 +1,7 @@ --- language: javascript contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Leigh Brenecki", "https://leigh.net.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] filename: javascript-ms.js translators: diff --git a/nl-nl/yaml-nl.html.markdown b/nl-nl/yaml-nl.html.markdown index 11af784f..7e4d37b1 100644 --- a/nl-nl/yaml-nl.html.markdown +++ b/nl-nl/yaml-nl.html.markdown @@ -2,7 +2,7 @@ language: yaml filename: learnyaml-nl.yaml contributors: - - ["Adam Brenecki", "https://github.com/adambrenecki"] + - ["Leigh Brenecki", "https://github.com/adambrenecki"] translators: - ["Niels van Velzen", "https://nielsvanvelzen.me"] - ["Sam van Kampen", "http://tehsvk.net"] diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index f12d275b..e38804f3 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -2,7 +2,7 @@ language: javascript filename: javascript-pt.js contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Leigh Brenecki", "https://leigh.net.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] translators: - ["Willian Justen", "http://willianjusten.com.br"] @@ -20,8 +20,8 @@ que é um projeto que fornece um interpretador baseado no motor V8 do Google Chrome e está se tornando cada vez mais famoso. Feedback são muito apreciados! Você me encontrar em -[@adambrenecki](https://twitter.com/adambrenecki), ou -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). +[@ExcitedLeigh](https://twitter.com/ExcitedLeigh), ou +[l@leigh.net.au](mailto:l@leigh.net.au). ```js // Comentários são como em C. Comentários de uma linha começam com duas barras, diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown index 07903325..21e9b4bb 100644 --- a/pt-br/yaml-pt.html.markdown +++ b/pt-br/yaml-pt.html.markdown @@ -1,7 +1,7 @@ --- language: yaml contributors: - - ["Adam Brenecki", "https://github.com/adambrenecki"] + - ["Leigh Brenecki", "https://github.com/adambrenecki"] translators: - ["Rodrigo Russo", "https://github.com/rodrigozrusso"] filename: learnyaml-pt.yaml diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 27874e93..c31c6994 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -1,7 +1,7 @@ --- language: javascript contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Leigh Brenecki", "https://leigh.net.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] filename: javascript-ru.js translators: diff --git a/ru-ru/yaml-ru.html.markdown b/ru-ru/yaml-ru.html.markdown index 0f805681..ddaed2b6 100644 --- a/ru-ru/yaml-ru.html.markdown +++ b/ru-ru/yaml-ru.html.markdown @@ -2,7 +2,7 @@ language: yaml filename: learnyaml-ru.yaml contributors: -- [Adam Brenecki, 'https://github.com/adambrenecki'] +- [Leigh Brenecki, 'https://github.com/adambrenecki'] - [Suhas SG, 'https://github.com/jargnar'] translators: - [Sergei Babin, 'https://github.com/serzn1'] diff --git a/ta_in/javascript-ta.html.markdown b/ta_in/javascript-ta.html.markdown index d3fe5a85..b328765f 100644 --- a/ta_in/javascript-ta.html.markdown +++ b/ta_in/javascript-ta.html.markdown @@ -1,7 +1,7 @@ --- language: javascript contributors: - - ['Adam Brenecki', 'http://adam.brenecki.id.au'] + - ['Leigh Brenecki', 'https://leigh.net.au'] - ['Ariel Krakowski', 'http://www.learneroo.com'] translators: - ["Rasendran Kirushan", "https://github.com/kirushanr"] @@ -22,8 +22,8 @@ javascript 1995 ஆம் ஆண்டு Netscape இல் பணிபுர V8 JavaScript engine Node .js உதவியுடன் இயங்குகிறது . உங்கள் கருத்துக்கள் மிகவும் வரவேற்கபடுகின்றன , என்னுடன் தொடர்புகொள்ள -[@adambrenecki](https://twitter.com/adambrenecki), or -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). +[@ExcitedLeigh](https://twitter.com/ExcitedLeigh), or +[l@leigh.net.au](mailto:l@leigh.net.au). ```js // குறிப்புக்கள் C நிரலாக்கத்தை ஒத்தது .ஒரு வரி குறிப்புக்கள் "//" குறியீடுடன் ஆரம்பமாகும் diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown index 6a64a623..2f17f586 100644 --- a/uk-ua/javascript-ua.html.markdown +++ b/uk-ua/javascript-ua.html.markdown @@ -1,7 +1,7 @@ --- language: javascript contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Leigh Brenecki", "https://leigh.net.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] - ["clearsense", "https://github.com/clearsense"] filename: javascript-uk.js diff --git a/yaml.html.markdown b/yaml.html.markdown index f1393c09..4f10a128 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -2,7 +2,7 @@ language: yaml filename: learnyaml.yaml contributors: -- [Adam Brenecki, 'https://github.com/adambrenecki'] +- [Leigh Brenecki, 'https://leigh.net.au'] - [Suhas SG, 'https://github.com/jargnar'] --- diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index 360f7c65..45e30932 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -4,7 +4,7 @@ category: language name: javascript filename: javascript-zh.js contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Leigh Brenecki", "https://leigh.net.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] translators: - ["Chenbo Li", "http://binarythink.net"] @@ -17,8 +17,8 @@ Javascript 于 1995 年由网景公司的 Brendan Eich 发明。最初它作为 不过,Javascript 不仅用于网页浏览器,一个名为 Node.js 的项目提供了面向 Google Chrome V8 引擎的独立运行时环境,它正在变得越来越流行。 很欢迎来自您的反馈,您可以通过下列方式联系到我: -[@adambrenecki](https://twitter.com/adambrenecki), 或者 -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). +[@ExcitedLeigh](https://twitter.com/ExcitedLeigh), 或者 +[l@leigh.net.au](mailto:l@leigh.net.au). ```js // 注释方式和C很像,这是单行注释 diff --git a/zh-cn/yaml-cn.html.markdown b/zh-cn/yaml-cn.html.markdown index e75fafba..7b6ff305 100644 --- a/zh-cn/yaml-cn.html.markdown +++ b/zh-cn/yaml-cn.html.markdown @@ -1,7 +1,7 @@ --- language: yaml contributors: - - ["Adam Brenecki", "https://github.com/adambrenecki"] + - ["Leigh Brenecki", "https://github.com/adambrenecki"] translators: - ["Zach Zhang", "https://github.com/checkcheckzz"] - ["Jiang Haiyun", "https://github.com/haiiiiiyun"] -- cgit v1.2.3 From f63a13765669457bfe72eb0fee43b99936331bd3 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 13 Feb 2020 22:06:16 -0800 Subject: fix en python language --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 2e1f8c90..0d438130 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: python contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] -- cgit v1.2.3 From cb55323819fa8ea937550051c2d41cb28b727630 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 13 Feb 2020 22:07:05 -0800 Subject: fix cs-cz python3 --- cs-cz/python.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cs-cz/python.html.markdown b/cs-cz/python.html.markdown index 7086ec5f..b684bd7d 100644 --- a/cs-cz/python.html.markdown +++ b/cs-cz/python.html.markdown @@ -1,5 +1,5 @@ --- -language: python3 +language: python contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] @@ -7,7 +7,7 @@ contributors: - ["Tomáš Bedřich", "http://tbedrich.cz"] translators: - ["Tomáš Bedřich", "http://tbedrich.cz"] -filename: learnpython3-cz.py +filename: learnpython-cz.py lang: cs-cz --- -- cgit v1.2.3 From 1a06a3512b4c748372d8aebfdf97ddb07dbfaa54 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 13 Feb 2020 22:09:07 -0800 Subject: fix pl pythonlegacy --- pl-pl/pythonlegacy-pl.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/pl-pl/pythonlegacy-pl.html.markdown b/pl-pl/pythonlegacy-pl.html.markdown index 9e322658..2b35ce90 100644 --- a/pl-pl/pythonlegacy-pl.html.markdown +++ b/pl-pl/pythonlegacy-pl.html.markdown @@ -1,6 +1,4 @@ --- -name: python -category: language language: Python 2 (legacy) filename: learnpythonlegacy-pl.py contributors: -- cgit v1.2.3 From 7539720f13ad86101be19b23989e260a9bc83dea Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 13 Feb 2020 22:11:29 -0800 Subject: fix en python again --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 0d438130..56cb9aac 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] -- cgit v1.2.3 From ae75b35f5f2e75396984f79c081746e6f408a072 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 13 Feb 2020 22:13:20 -0800 Subject: fix cs-cz python3 again --- cs-cz/python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cs-cz/python.html.markdown b/cs-cz/python.html.markdown index b684bd7d..0e2416d1 100644 --- a/cs-cz/python.html.markdown +++ b/cs-cz/python.html.markdown @@ -1,5 +1,5 @@ --- -language: python +language: Python contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] -- cgit v1.2.3