I'm doing a project on projectile motion where I have to create a program that given some values, it will give several values. I haven't finished it yet, but I wish to test it, but I have very little knowledge on how to run my programs. I created a file on Notepad++ with some of my code, but every time I try to run it, it says:
Traceback (most recent call last):
File <"stdin">, line 1, in
ImportError: no module named py
The thing is, I don't see anywhere how to run my programs on Python using Notepad++ so I am confused as to what I have to do. I am using the command prompt to run my program.
I will post what I have so far of my project because maybe it's a problem of what I have written. This is what I have so far:
"""Mini-Project about projectile motion."""
USER = ""
USER_ID = ""
import numpy as np
#Define variables for ease of use:
g = 9.81 #gravitational constant
u = (float(raw_input("enter launch_speed: ")))#speed of launch
r = (float(raw_input("enter launch_angle_deg: "))*(np.pi)/180) #angle of launch in radians
n = (float(raw_input("enter num_samples: "))) #number of time divisions
#"t" variable of time
#"x" variable of horizontal distance
#"y" variable of vertical distance
def x(t):
"""function that gives the horizontal position "x" as a function
of time.
"""
return u*(np.cos(r))*t #formula for horizontal displacement
def y(t):
"""function that gives the vertical position "y" as a function of
time.
"""
return u*(np.sin(r))*t - (g/2)*t**2 #formula for vertical displacement
def y(x):
"""function that gives the vertical position "y" as a function of the
horizontal position "x".
"""
return x*(np.tan(r))-(g/2)*(x/(u*np.cos(r)))**2
a = np.arange(1, n+1, dtype=float)
def trajectory(launch_speed, launch_angle_deg , num_samples ):
"""This function gives the values of horizontal x-values, vertical
y-values, and time values, respectively, given the values for initial
launch speed, and the angle at which it is launched, for some given
divisions of time that the object is in the air.
"""
while t <= (u*(np.sin(r))/g): #maximum time given by this formula
t = x/(u*(np.cos(r)))
I am assuming you are on Windows, for the reference good ol' command prompt. Be sure you have Python installed, then navigate to the folder you have your Python script stored. Shift right-click on the folder and select "Open command window here". A CMD window should appear. Now just type
python name_of_your_python_file.py
And you should see the output. As for the ImportError you posted, be sure to have all dependencies installed. (Numpy)
If you are determined to use Notepad++ as your development environment, read here for more information on running those Python scripts direct from notepad++
Store the program in a file named "projectile.py"
Install Python 3 and NumPy.
Then open console, navigate to the folder containing the file
Invoke
python3 projectile.py
Related
I recently wrote a simple function that gets the present value of an asset, the function PV works properly and I have tested it. The function prints well in my pv file. However, when I run this code in the main file it does not print the output to the terminal and just closes after taking the inputs. Is there a reason for this? For reference the functions just perform some simple mathematics problems.
Below is a minimal reproduction, both files are in the same folder.
in file_x you have a function that works like this:
def func(w,x,y,z):
z1 = w/(1 + (x/100))**(y*z)
print(z1)
return 0
this function is then imported into another file which is written like so
from file_x import func
w = int(input("Future Value: "))
x = float(input("ROR: "))
y = float(input("# of periods: "))
z = float(input("# of payment per anum: "))
func(w,x,y,z)
My problem is that when I run the 2nd file it takes the inputs properly but does not print the result from the function. Hope it was explained properly
In interactive mode an unused expression (here PV(w,x,y,z) which does returns a value and that value is not used) is printed to the terminal, because it is a common way to just display expression values.
But when you run a script in a non interactive mode (python script.py) then those unused expression are just discarded. As a general rule, you should never have such an unused expression in a script, because the behaviour will depend on the interactive mode of the interpretor.
So you should be explicit:
_ = PV(w,x,y,z) # value will be discarded even in interactive mode
or
print(PV(w,x,y,z)) # value will be printed even in non interactive mode
I'm getting used to VSCode in my daily Data Science remote workflow due to LiveShare feature.
So, upon executing functions it just executes the first line of code; if I mark the whole region then it does work, but it's cumbersome way of dealing with the issue.
I tried number of extensions, but none of them seem to solve the problem.
def gini_normalized(test, pred):
"""Simple normalized Gini based on Scikit-Learn's roc_auc_score"""
gini = lambda a, p: 2 * roc_auc_score(a, p) - 1
return gini(test, pred)
Executing the beginning of the function results in error:
def gini_normalized(test, pred):...
File "", line 1
def gini_normalized(test, pred):
^
SyntaxError: unexpected EOF while parsing
There's a solution for PyCharm: Python Smart Execute - https://plugins.jetbrains.com/plugin/11945-python-smart-execute. Also Atom's Hydrogen doesn't have such issue either.
Any ideas regarding VSCode?
Thanks!
I'm a developer on the VSCode DataScience features. Just to make sure that I'm understanding correctly. You would like the shift-enter command to send the entire function to the Interactive Window if you run it on the definition of the function?
If so, then yes, we don't currently support that. Shift-enter can run line by line or run a section of code that you manually highlight. If you want, you can use #%% lines in your code to put functions into code cells. Then when you are in a cell shift-enter will run that entire cell, might be the best current approach for you.
That smart execute does look interesting, if you would like to file that as a suggestion you can use our GitHub here to get it on our backlog to look at.
https://github.com/Microsoft/vscode-python
Hi you could click the symbol before each line and turn it into > (the indented codes of the function was hidden now). Then if you select the whole line and the next line, shift+enter could run them together.
enter image description here
My python script passes changing inputs to a program called "Dymola", which in turn performs a simulation to generate outputs. Those outputs are stored as numpy arrays "out1.npy".
for i in range(0,100):
#code to initiate simulation
print(startValues, 'ParameterSet:', ParameterSet,'time:', stoptime)
np.save('out1.npy', output_data)
Unfortunately, Dymola crashes very often, which makes it necessary to rerun the loop from the time displayed in the console when it has crashed (e.g.: 50) and increase the number of the output file by 1. Otherwise the data from the first set would be overwritten.
for i in range(50,100):
#code to initiate simulation
print(startValues, 'ParameterSet:', ParameterSet,'time:', stoptime)
np.save('out2.npy', output_data)
Is there any way to read out the 'stoptime' value (e.g. 50) out of the console after Dymola has crashed?
I'm assuming dymola is a third-party entity that you cannot change.
One possibility is to use the subprocess module to start dymola and read its output from your program, either line-by-line as it runs, or all after the created process exits. You also have access to dymola's exit status.
If it's a Windows-y thing that doesn't do stream output but manipulates a window GUI-style, and if it doesn't generate a useful exit status code, your best bet might be to look at what files it has created while or after it has gone. sorted( glob.glob("somepath/*.out")) may be useful?
I assume you're using the dymola interface to simulate your model. If so, why don't you use the return value of the dymola.simulate() function and check for errors.
E.g.:
crash_counter = 1
from dymola.dymola_interface import DymolaInterface
dymola = DymolaInterface()
for i in range(0,100):
res = dymola.simulate("myModel")
if not res:
crash_counter += 1
print(startValues, 'ParameterSet:', ParameterSet,'time:', stoptime)
np.save('out%d.npy'%crash_counter, output_data)
As it is sometimes difficult to install the DymolaInterface on your machine, here is a useful link.
Taken from there:
The Dymola Python Interface comes in the form of a few modules at \Dymola 2018\Modelica\Library\python_interface. The modules are bundled within the dymola.egg file.
To install:
The recommended way to use the package is to append the \Dymola 2018\Modelica\Library\python_interface\dymola.egg file to your PYTHONPATH environment variable. You can do so from the Windows command line via set PYTHONPATH=%PYTHONPATH%;D:\Program Files (x86)\Dymola 2018\Modelica\Library\python_interface\dymola.egg.
If this does not work, append the following code before instantiating the interface:
import os
import sys
sys.path.insert(0, os.path.join('PATHTODYMOLA',
'Modelica',
'Library',
'python_interface',
'dymola.egg'))
I have tried many set and search quite some time. I'll try to summarize to my problem.
I a have a file I name script.py.
Inside this script.py I have something like this:
import math
import numpy as np
from numpy import matrix
#Inserting variables:
A=float(input("insert position 1: "))
K=float(input("insert position 2: "))
#Doing some math:
a1=A*K
a2=A/K
#Defining a funtion:
def solve(var1,var2)
#This function uses numpy and math and handles matrices.
#I am not putting it to save space and make my problem clear
#Calling the funtion:
solve(a1,a2)
print (solve)
#The values of a1 and a2 are the once I calculated previously
Then I press "run module" to run script.py, it shows:
>> insert position 1:
>> insert position 2:
I insert the values and then it shows:
<function solve at 0x000000000A0C1378>
What can I do to make the python shell display the result directly?
Currently in order to get the results I need to type in the python shell
>> solve(a1,a2)
to have my result.
I hope I was able to make my problem clear and simple. Thanks.
You are printing the function itself, not the output from the function call. To achieve this, either save the function output to a variable then print, or just print straight away.
1st Method:
ans = solve(a1,a2)
print(ans)
2nd Method:
print(solve(a1,a2))
I was able to successfully install matplotlib; however, when I run my code, I don't get an error, but instead the Python icon bouncing over and over again.
I don't know if it has anything to do with
from rcParamsSettings import *
I don't have any idea what that is, but if I try to run it with that line uncommented out, I get
ImportError: No module named rcParamsSettings
Here's the code I'm trying to run:
import pylab
#from rcParamsSettings import *
import random
def flipPlot(minExp, maxExp):
"""Assumes minExp and maxExp positive integers; minExp < maxExp
Plots results of 2**minExp to 2**maxExp coin flips"""
ratios = []
diffs = []
xAxis = []
for exp in range(minExp, maxExp + 1):
xAxis.append(2**exp)
for numFlips in xAxis:
numHeads = 0
for n in range(numFlips):
if random.random() < 0.5:
numHeads += 1
numTails = numFlips - numHeads
ratios.append(numHeads/float(numTails))
diffs.append(abs(numHeads - numTails))
pylab.title('Difference Between Heads and Tails')
pylab.xlabel('Number of Flips')
pylab.ylabel('Abs(#Heads - #Tails)')
pylab.plot(xAxis, diffs)
pylab.figure()
pylab.title('Heads/Tails Ratios')
pylab.xlabel('Number of Flips')
pylab.ylabel('#Heads/#Tails')
pylab.plot(xAxis, ratios)
random.seed(0)
flipPlot(4, 20)
What do I need to do to get the code running?
Note: My experience with programming and Python is very limited; I'm just starting out.
You need to use pylab.show() otherwise nothing will come up.
See the example here: http://matplotlib.org/examples/pylab_examples/simple_plot.html
(although you should avoid using from pylab import *, the way you import is fine.)
There are cases in MatPlotLib where you do not want to show the graph. An example I have is designing a graph on a server using data collected by an automated process. The server has no screen and is only accessed by a terminal, and therefore trying to show a graph will result in an error as there is no DISPLAY variable set (there is no screen to display to).
In this case it would be normal to save the figure somewhere using pylab.savefig(), and then maybe email it or use an ftp to send it somewhere it can be viewed.
Because of this MatPlotLib will not implicitly show a graph and must be asked to show it.
Your code works for me if I add a pylab.show().
Alternatively, you could save the plot to a file:
pylab.savefig("file.png")
This makes sense if you are updating your plot frequently.