Difference between revisions of "Python"

From Rasmapedia
Jump to navigation Jump to search
(Miscellaneous)
 
(26 intermediate revisions by 2 users not shown)
Line 5: Line 5:
 
   
 
   
 
I should make this into a  how to learn python file.  C:\Users\erasmuse\Dropbox\PYTHON\optical-mark-recognition
 
I should make this into a  how to learn python file.  C:\Users\erasmuse\Dropbox\PYTHON\optical-mark-recognition
---
+
==Newly learned commands, not in the old MS Word file==
 +
 
 +
===Mathematical Computations===
 +
*[https://realpython.com/python-rounding/  A RealPython article on rounding, in Python and computers generally]
 +
 
 +
===Operating System Commands===
 +
<pre>
 +
import os
 +
getcwd()  #This print the current working directory
 +
# slashes become double slashes as python control characters
 +
</pre>
 +
 
 +
===Making a Graphic Interface in Windows or Unix--tkinter package===
 +
tkinter is the package for making apps.  A very good intro is at [https://realpython.com/python-gui-tkinter/ Realpython].  Really, Javascript is better than Python, though, and very easy to learn. 
 +
<pre>
 +
import tkinter as tk
 +
window1 = tk.Tk() #Creates a blank window on your desktop.
 +
inside = tk.Label(text = "Here is my text in the window.") #Creates some text to use.
 +
inside.pack()    #Put the text into the window and resize to barely fit it.
 +
window1.mainloop() #This does nothing here, but if there are multilpe windows, it makes them come up at the proper time.
 +
</pre>
 +
 
 +
From ChatGPT, adapted, I got this number squarer:
 +
<pre>
 +
import tkinter as tk
 +
from tkinter import messagebox
 +
 
 +
# Function to square the number
 +
def square_number():
 +
        num = float(entry.get())  # Get the number from the entry widget
 +
        result = num ** 2        # Square the number
 +
        result_label.config(text=f"Squared: {result}")  # Display the result
 +
 
 +
# Create the main window
 +
root = tk.Tk()
 +
 
 +
# Create and place the widgets
 +
entry_label = tk.Label(root, text="Enter a number:")
 +
entry_label.pack(pady=5)
 +
 
 +
entry = tk.Entry(root)
 +
entry.pack(pady=5)
 +
 
 +
square_button = tk.Button(root, text="Square", command=square_number)
 +
square_button.pack(pady=10)
 +
 
 +
result_label = tk.Label(root, text=f"Squared, the number becomes: ")
 +
result_label.pack(pady=10)
 +
 
 +
# Start the Tkinter event loop
 +
root.mainloop()
 +
</pre>
 +
 
 +
===Loops===
 +
<pre>
 +
for item in range(1,11): 
 +
  print(f"Item {item} is {item}." )
 +
#I always forget the range command.
 +
</pre>
 +
 +
*[https://entrian.com/goto/ How to code a GOTO statement]
 +
 
 +
===Printing===
 +
<pre>
 +
print(f"The value of variable var1 is {var1}.")
 +
print(f"The value of variable var1 is {var1:0.2f}.")
 +
#New and beest formatting method, and to 2 decimals.
 +
</pre>
 +
 +
area = 24<br>
 +
print("The area is "+ str(area)+  ".") <br>
 +
print ("The area is ", area, ".", sep="")<br>
 +
print ("The area is 24.")<br>
 +
\#Allof these print commands will print "The area is 24." They solve the problem of having a space before the period.
 +
 
 +
==Old MS Word file==
 +
Use the Anaconda terminal for python, not the regular Windows terminal. Really, Spyder is best, or the web app at [https://www.codabrainy.com/en/python-compiler/ https://www.codabrainy.com/en/python-compiler/ Codabrainy].<br>
 
import sys ;  sys.exit();exit(); # ENDING A SCRIPT:  (all three are needed). CTRL-C for BREAK.  
 
import sys ;  sys.exit();exit(); # ENDING A SCRIPT:  (all three are needed). CTRL-C for BREAK.  
 
If you get stuck on the console, often you just need to close a parenthesis for it to be willing to go on.  
 
If you get stuck on the console, often you just need to close a parenthesis for it to be willing to go on.  
Line 72: Line 148:
  
 
==Miscellaneous==
 
==Miscellaneous==
[[https://amypeniston.com/ditching-excel-for-python/ Ditching Excel for Python – Lessons Learned from a Legacy Industry]],
+
[https://amypeniston.com/ditching-excel-for-python/ Ditching Excel for Python – Lessons Learned from a Legacy Industry],
Published: December 30, 2020, is about how in the insurance industry Python is replacing Excel.
+
December 30, 2020, is about how in the insurance industry Python is replacing Excel.
  
https://www.w3schools.com/python/gloss_python_escape_characters.asp  include
+
==Formatting==
 +
*[https://www.w3schools.com/python/gloss_python_escape_characters.asp  Escape characters] include
 
\n for newline, \b for backspace, \t for tab, \\ for backslash, \’ for single quote
 
\n for newline, \b for backspace, \t for tab, \\ for backslash, \’ for single quote
 +
 +
*For colored fonts, use the color package. See [https://www.askpython.com/python/examples/print-colored-text-to-the-terminal-in-python https://www.askpython.com/python/examples/print-colored-text-to-the-terminal-in-python].
 +
 +
:pip install termcolor
 +
:from termcolor import  cprint
 +
cprint("Hello World.", "red")
 +
 +
This doesn't work in Codabrainy.
 
-----
 
-----

Latest revision as of 11:13, 9 September 2024

Introduction

Here I should put all my Python notes. sdffd


I should make this into a how to learn python file. C:\Users\erasmuse\Dropbox\PYTHON\optical-mark-recognition

Newly learned commands, not in the old MS Word file

Mathematical Computations

Operating System Commands

import os 
getcwd()  #This print the current working directory
# slashes become double slashes as python control characters

Making a Graphic Interface in Windows or Unix--tkinter package

tkinter is the package for making apps. A very good intro is at Realpython. Really, Javascript is better than Python, though, and very easy to learn.

import tkinter as tk
window1 = tk.Tk() #Creates a blank window on your desktop.
inside = tk.Label(text = "Here is my text in the window.") #Creates some text to use.
inside.pack()     #Put the text into the window and resize to barely fit it. 
window1.mainloop() #This does nothing here, but if there are multilpe windows, it makes them come up at the proper time.

From ChatGPT, adapted, I got this number squarer:

import tkinter as tk
from tkinter import messagebox

# Function to square the number
def square_number():
        num = float(entry.get())  # Get the number from the entry widget
        result = num ** 2         # Square the number
        result_label.config(text=f"Squared: {result}")  # Display the result

# Create the main window
root = tk.Tk()

# Create and place the widgets
entry_label = tk.Label(root, text="Enter a number:")
entry_label.pack(pady=5)

entry = tk.Entry(root)
entry.pack(pady=5)

square_button = tk.Button(root, text="Square", command=square_number)
square_button.pack(pady=10)

result_label = tk.Label(root, text=f"Squared, the number becomes: ")
result_label.pack(pady=10)

# Start the Tkinter event loop
root.mainloop()

Loops

for item in range(1,11):  
   print(f"Item {item} is {item}." )
#I always forget the range command.

Printing

print(f"The value of variable var1 is {var1}.") 
print(f"The value of variable var1 is {var1:0.2f}.")
#New and beest formatting method, and to 2 decimals. 

area = 24
print("The area is "+ str(area)+ ".")
print ("The area is ", area, ".", sep="")
print ("The area is 24.")
\#Allof these print commands will print "The area is 24." They solve the problem of having a space before the period.

Old MS Word file

Use the Anaconda terminal for python, not the regular Windows terminal. Really, Spyder is best, or the web app at https://www.codabrainy.com/en/python-compiler/ Codabrainy.
import sys ; sys.exit();exit(); # ENDING A SCRIPT: (all three are needed). CTRL-C for BREAK. If you get stuck on the console, often you just need to close a parenthesis for it to be willing to go on.

%reset -f #Type this in the IPython console (not in your batch file) to clear all variables you created. import gc; gc.collect() #This might work in a batch file. DOES NOT I think.

HERE STARTS THE ORGANIZED TOPICS


Download Anaconda, a version of Python.  When I search on my computer for Anaconda, I get an option for an Anaconda terminal. What I have below doesn’t work any more.  From the Windows Command Line, there are four  ways to run python programs: 
1. python myprogram.py April 12 2017
  This first way runs a particular python program you wrote, myprogram.py, and that program takes the words April 12, 2017 and does something to them. 

2. python

  This starts up an interactive session with this prompt 

>>>

 In this session you would enter python commands such as 

x= 2+2

This command  creates the variable x by adding 2  and 2 and on the next line 4 will appear. 

3. spyder

If you open a black command line window, then you can type ‘spyder’ and after a minute (a long time) the spyder interface will appear. One part is   a left hand big box for writing python programs in and then pressing the green arrow RUN button at the top to run them.  You could use:

x=2+2 print(x)

After pressing the green  arrow button,  you will see in the bottom right square, the console, what the output of the batch program is: 4.   For a batch program, you need the print(x), not just the creation of the variable, to see any output. You can detach the console and move it to another monitor by double clicking the window title, “IPython Console”. 
  You can also type directly into the console, which has a prompt that looks like 

In [3]:

  This will work like interactive with the >>> prompt. 

4. Karst.

  To use  the Indiana U.  karst machine, get a terminal (Putty is best) to start a session  at karst.uits.iu.edu. Load up Python 3.5, because the default python is Python 2. mpmath is already installed. invertlaplace() works. 

5. Jupyter notebooks. These work with Chrome or another browser. I have gotten it to work. on the black Lenovo. In the command prompt, type ‘jupyter notebook’. A browser window will come up with a directory and you can go find the jupyter notebook you want to use., or click New and choose Python3 to start a new one. ou cannot rename a notebook while it is running, so you’ve first got to shut it down.


==INSTALLING MODULES==

BEST: pip install sympy # to install symbolic python. In the TERMINAL. I don’t need to say “python” first.

pip install requests #This install the requests module.  

pip install antlr4-python3-runtime #This from the terminal installs the antlr4 package.

or pip install mechanize # worked fine. 

It will work then, but for it to work on a windows computer without python installed, I am told you need even more files copies into the directory with temp.exe. You need to copy C:\ProgramData\Anaconda3\Library\lib\tcl8.5\ and also the tk8.5 directory. http://sebsauvage.net/python/snyppets/index.html#tkinter_cxfreeze

To test whether a module installed, e.g. mpmath, try “mpmath.runtests()” https://conda.io/docs/user-guide/tasks/manage-pkgs.html#installing-packages conda install -c stsci imutils This is the way most packages ae installed.

import sys; import matplotlib as plt; print("plt" in sys.modules) ;#See if matplotlib really was imported.

--- to install a PACKAGE (not a module) such cx_Freeze, which turns python scripts into Windows executiable, go to Windows Command Prompt terminal and type:

MAYBE CONDA INSTALL, maybe something else. 

python -m pip cx_Freeze tehn turn: python.exe cxfreeze-postinstall

Use the script cxfreeze1.py. You insert the name such as temp.py and  any oher details you like into it. Then: 

python cxfreeze1.py build

That will create a directory called build in whcih lots of fiels are, including temp.exe, which runs when you click on it. But it will have an error unless you go into ProgramData/Anaconda3/DLLs/ and copy tcl86t.dll and tk86t.dll into the same directory as the new temp.exe. 

---

Miscellaneous

Ditching Excel for Python – Lessons Learned from a Legacy Industry, December 30, 2020, is about how in the insurance industry Python is replacing Excel.

Formatting

\n for newline, \b for backspace, \t for tab, \\ for backslash, \’ for single quote

pip install termcolor
from termcolor import cprint

cprint("Hello World.", "red")

This doesn't work in Codabrainy.