First steps with Python3
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

305 lines
8.1 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. # 1. Introduction to Python
  2. Python is a dynamic, interpreted (bytecode-compiled) language. There are no type declarations of variables, parameters, functions, or methods in source code. This makes the code short and flexible, and you lose the compile-time type checking of the source code. Python tracks the types of all values at runtime and flags code that does not make sense as it runs[^1].
  3. Actually, Python is widely used by engineers, scientists, statistics and data-science. Why should I learn Python?
  4. - Well, is a free and open source,
  5. - is versatile (multiparadign)
  6. - is portable and usable in other platforms
  7. - There are several modules to work with
  8. # Installing python
  9. **Note**: this guide only focus on GNU/Linux Ubuntu and Unix based (MacOS) operate systems (OS).
  10. ## Ubuntu
  11. To install the latest Python version, above 3.8, use the next commands in the terminal to let the _APT_ package manager to install it:
  12. ```
  13. sudo apt update
  14. sudo apt install python3
  15. ```
  16. we are going to use the Integrated Development Environment (IDLE), thus, please run the next commands to install it:
  17. ```
  18. sudo apt-get update
  19. sudo apt-get install idle3
  20. ```
  21. ## Unix-based
  22. In the MacOS system there is recommended package manager call _Homebrew_, to install it run the next command in the terminal:
  23. ```
  24. /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  25. ```
  26. then, you will have access to the `brew` command to install and manage your packages. Next, you can install Python by using:
  27. ```
  28. brew install python3 python-tk
  29. ```
  30. these both packages allow us to run the IDLE for Python.
  31. # Testing Python
  32. ## Interactive
  33. ```
  34. $ python ## Run the Python interpreter
  35. Python 3.X.X (XXX, XXX XX XXXX, 03:41:42) [XXX] on XXX
  36. Type "help", "copyright", "credits" or "license" for more information.
  37. >>> a = 6 ## set a variable in this interpreter session
  38. >>> a ## entering an expression prints its value
  39. 6
  40. >>> a + 2
  41. 8
  42. >>> a = 'hi' ## 'a' can hold a string just as well
  43. >>> a
  44. 'hi'
  45. >>> len(a) ## call the len() function on a string
  46. 2
  47. >>> a + len(a) ## try something that doesn't work
  48. Traceback (most recent call last):
  49. File "", line 1, in
  50. TypeError: can only concatenate str (not "int") to str
  51. >>> a + str(len(a)) ## probably what you really wanted
  52. 'hi2'
  53. >>> foo ## try something else that doesn't work
  54. Traceback (most recent call last):
  55. File "", line 1, in
  56. NameError: name 'foo' is not defined
  57. >>> ^D ## type CTRL-d to exit (CTRL-z in Windows/DOS terminal)
  58. ```
  59. ## module files
  60. Python source files use the ".py" extension and are called "modules." With a Python module hello.py, the easiest way to run it is with the shell command "python hello.py Alice" which calls the Python interpreter to execute the code in hello.py, passing it the command line argument "Alice"
  61. ```
  62. #!/usr/bin/env python
  63. # import modules used here -- sys is a very standard one
  64. import sys
  65. # Gather our code in a main() function
  66. def main():
  67. print('Hello there', sys.argv[1])
  68. # Command line args are in sys.argv[1], sys.argv[2] ...
  69. # sys.argv[0] is the script name itself and can be ignored
  70. # Standard boilerplate to call the main() function to begin
  71. # the program.
  72. if __name__ == '__main__':
  73. main()
  74. ```
  75. to run the code use
  76. ```
  77. $ python hello.py Guido
  78. Hello there Guido
  79. $ ./hello.py Alice ## without needing 'python' first (Unix)
  80. Hello there Alice
  81. ```
  82. # Jupyter Notebook
  83. ## Basic commands
  84. Jupyter Notebook is widely used for data analysis. The notebooks documents are documents produced by the Jupyter Notebook App, which can contain both code (e.g. Python) and rich text elements (paragraphs, equations, links, etc.).
  85. The Jupyter Notebook App is a client-server application that allows editing and running notebook documents by a browser.
  86. ### Shortcuts in both modes:
  87. - Shift + Enter run the current cell, select below
  88. - Ctrl + Enter run selected cells
  89. - Alt + Enter run the current cell, insert below
  90. - Ctrl + S save and checkpoint
  91. ### While in command mode (press Esc to activate):
  92. **Enter take you into edit mode** and then the command that you need like change the cell type to Markdown:
  93. - H show all shortcuts
  94. - Up select cell above
  95. - Down select cell below
  96. - Shift + Up extend selected cells above
  97. - Shift + Down extend selected cells below
  98. - A insert cell above
  99. - B insert cell below
  100. - X cut selected cells
  101. - C copy selected cells
  102. - V paste cells below
  103. - Shift + V paste cells above
  104. - D, D (press the key twice) delete selected cells
  105. - Z undo cell deletion
  106. - S Save and Checkpoint
  107. - Y change the cell type to Code
  108. - M change the cell type to Markdown
  109. - P open the command palette
  110. This dialog helps you run any command by name. It’s really useful if you don’t know some shortcut or when you don’t have a shortcut for the wanted command.
  111. - Shift + Space scroll notebook up
  112. - Space scroll notebook down
  113. ### While in edit mode (press Enter to activate)
  114. - Esc take you into command mode
  115. - Tab code completion or indent
  116. - Shift + Tab tooltip
  117. - Ctrl + ] indent
  118. - Ctrl + [ deindent //]
  119. - Ctrl + A select all
  120. - Ctrl + Z undo
  121. - Ctrl + Shift + Z or Ctrl + Y redo
  122. - Ctrl + Home go to cell start
  123. - Ctrl + End go to cell end
  124. - Ctrl + Left go one word left
  125. - Ctrl + Right go one word right
  126. - Ctrl + Shift + P open the command palette
  127. - Down move cursor down
  128. - Up move cursor up
  129. # Basics of Python programming language
  130. ## `if`, `for` and plot
  131. ```
  132. x = int(input("Please enter an integer: "))
  133. Please enter an integer: 42
  134. >>> if x < 0:
  135. ... x = 0
  136. ... print('Negative changed to zero')
  137. ... elif x == 0:
  138. ... print('Zero')
  139. ... elif x == 1:
  140. ... print('Single')
  141. ... else:
  142. ... print('More')
  143. ...
  144. More
  145. ```
  146. ## for statement
  147. ```
  148. words = ['cat', 'window', 'defenestrate']
  149. for w in words:
  150. print(w, len(w))
  151. ```
  152. ```
  153. for i in range(5):
  154. print(i)
  155. ```
  156. ```
  157. a = ['Mary', 'had', 'a', 'little', 'lamb']
  158. for i in range(len(a)):
  159. print(i, a[i])
  160. ```
  161. ## Numpy arrays
  162. Numpy, on the other hand, is a core Python library for scientific computation (hence the name “Numeric Python” or Numpy). The library provides methods and functions to create and work with multi-dimensional objects called arrays. Arrays are grids of values, and unlike Python lists, they are of the same data type:
  163. ```
  164. # 1-dimesional array
  165. array([1, 2, 3])
  166. # 2-dimensional array
  167. array([[1, 2],
  168. [3, 4],
  169. [5, 6]])
  170. ```
  171. ```
  172. import numpy as np
  173. a = np.array([[1,2],[3,4],[5,6]])
  174. ```
  175. ## Matplotlib
  176. Matplotlib is a 2d plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments. Matplotlib can be used in Python scripts, Python and IPython shell, Jupyter Notebook, web application servers and GUI toolkits.
  177. matplotlib.pyplot is a collection of functions that make matplotlib work like MATLAB. Majority of plotting commands in pyplot have MATLAB analogs with similar arguments. Let us take a couple of examples:
  178. ```
  179. import matplotlib.pyplot as plt
  180. plt.plot([1,2,3,4])
  181. plt.ylabel('some numbers')
  182. plt.show()
  183. ```
  184. ```
  185. import matplotlib.pyplot as plt
  186. >>> x = [21,22,23,4,5,6,77,8,9,10,31,32,33,34,35,36,37,18,49,50,100]
  187. >>> num_bins = 5
  188. >>> plt.hist(x, num_bins, facecolor='blue')
  189. >>> plt.show()
  190. ```
  191. ```
  192. # how to crate functions
  193. def myFuncion(x):
  194. y = np.sin(x)/np.cos(x)
  195. return y
  196. ```
  197. ```
  198. import matplotlib.pyplot as plt
  199. time = np.linspace(0,10)
  200. y = myFuncion(time)
  201. y2 = np.tan(time)
  202. plt.plot(time, y/2,'-g*')
  203. plt.plot(time, y2, ':m+')
  204. plt.show()
  205. ```
  206. ## Subplots
  207. A subplot for one column and three rows
  208. ```
  209. plt.subplot(3,1,1)
  210. plt.plot(time, np.sin(time),'r', label='$y_1$')
  211. plt.legend()
  212. plt.subplot(3,1,2)
  213. plt.plot(time, np.cos(time),'g',label='y2')
  214. plt.legend()
  215. plt.subplot(3,1,3)
  216. plt.plot(time, np.tan(time),'k', label='y3')
  217. plt.legend()
  218. plt.show()
  219. ```
  220. A plot for three columns and two rows
  221. ```
  222. plt.subplot(6,3,1)
  223. plt.plot(time, np.sin(time),'r', label='y_1')
  224. plt.subplot(6,3,2)
  225. plt.plot(time, np.cos(time),'g',label='y2')
  226. plt.subplot(6,3,3)
  227. plt.plot(time, np.tan(time),'k', label='y3')
  228. plt.subplot(6,3,4)
  229. plt.plot(time, np.sin(time),'r', label='$y_1$')
  230. plt.subplot(6,3,5)
  231. plt.plot(time, np.cos(time),'g',label='y2')
  232. plt.subplot(6,3,6)
  233. plt.plot(time, np.tan(time),'k', label='$y_1$')
  234. plt.show()
  235. ```
  236. # References
  237. [^1]: https://developers.google.com/edu/python/introduction