How do I call a function in vs code using python? - python

I'll want to know how to call a function in vs code. I read the answer to similar questions, but they don't work:
def userInput(n):
return n*n
userInput(5)
And appends nothing
def Input(n):
return n*n
And in the terminal:
from file import *
from: can't read /var/mail/file
Can somebody help me?

You are doing everything correctly in the first picture. In order to call a function in python on vs code you first have to define the function, which you did by typing def userInput(n):. If you want to see the result of your function, you should not use return, you should use print instead. Return is a keyword- so when your computer reaches the return keyword it attempts to send that value from one point in your code to another. If you want to see the result of your code, typing print (n) would work better.
Your code should look like this:
def userInput(n):
print (n * n)
userInput(5)
The code would print the result 25

Your terminal is your general way to access your operating system, so you have to tell it that you want it to interpret your Python code first.
If you want to run the file you're typing in, you have to first know the location of that file. When you type ls in your terminal, does the name of your Python file show up? If not, hover over the tab in VSCode (it's close to the top of the editor) and see what path appears. Then in your terminal type cd (short for "change directory") and then the path that you saw, minus the <your filename here>.py bit. Type ls again, and you should see your Python file. Now you can type python <your filename here>.py to run it (provided you have Python installed).
You could also run the IDLE by just typing python in your terminal. This will allow you to write your code line-by-line and immediately evaluate it, but it's easier to write in VSCode and then run it with the method I described before.

Related

How to refresh/overwrite console output in python

I want to know how to refresh the console of my program as if it was just started. Let's say that my code consists of an infinite loop and it has multiple instances of the print() function within itself, I want, every time that loops returns to its start, all the new data whether there is some change or not to get outputted on the same place of the data that has been outputted the last time.
I have been reading about similar problems others have posted and the answers usually revolve around the idea of using \r, when I do that, however, it's always messy and the strings are either printed halfway or there are missing characters. On Replit there is a module called "replit" and there is a function there called clear() that basically performs what I need, but I don't seem to find it when I am using PyCharm, which means that it is perhaps something that works exclusively within the Replit environment. So I am asking, is there something similar in the standard python library that I can use? Thanks
You can use:
import os
command = 'cls' #for windows
os.system(command)
example:
print('hi')
os.system(command)
print('hi')
Output:
hi
For windows you need:
command = 'cls'
For all others it is:
command = 'clear'
To account for any OS you could use:
import os
def clearConsole():
command = 'clear'
if os.name in ('nt', 'dos'): # If computer is running windows use cls
command = 'cls'
os.system(command)
clearConsole()
There is nothing standard in Python to do it, because Python is not aware of whatever console you are using.
When you call print it is actually writing to a file called "standard output".
It can go to a console if you are running your program in a console (like windows cmd, Linux or Mac OS terminal app, or whatever PyCharm uses).
But it can also be redirected to a regular file by the user of your program.
So there is no standard way.
\r is "carriage return" character. On consoles that respect it, it will set your output position to the beginning of the current line, but will not erase any text already printed on that line (usually).
One way to print text in specific places on the screen is PyCurses.
It supports many consoles and figures out which one you are using automatically.
You can do something like this:
import curses
stdscr = curses.initscr()
stdscr.addstr(x, y, "my string")
By using the addstr isntead of print, you can choose the exact position the text will appear, with X and Y coordinates (first two parameters).
Read the documentation for more ways to manipulate text display with this library.

creating python code on IDLE then using it in macOS terminal

I'm wondering how I can utilize my code on IDLE to work within the macOS Terminal.
For example, I created a function such as:
def multiplication_by_2(x): return 2 * x
and saved the .py file in a desktop folder.
I want to use terminal to test out various cases such as multipication_by_2(100) etc, however I am unsure about which commands to enter in terminal to achieve this.
Any direction toward this would be helpful. Thank you.
Try this at the end of the code:
number = int(str(input("Enter the number you would like to multiply by 2: ")))
multiplication_by_2(number)
This way, you get user input. Then, in the terminal:
$ python3 <filename>.py
Which should produce the output:
Enter the number you would like to multiply: <your input, ex. 100>
200
Hope that solved it!
If you are asking how to send arguments to your program through the command line, python's sys library has a list named argv that holds arguments passed from the command line. Add this to your python file:
from sys import argv
for argument in argv:
print(multipication_by_2(int(argument))) # All arguments are strings by default
Then in the command line, do python file_name.py 20 50 1 and any other number you might want to try, and the program will print its double.
Note: If your command line says python doesn't exist, try python3.

Python script writing results to text file

Today I managed to run my first Python script ever. I'm a newb, on Windows 7 machine.
When I run python.exe and enter following (Python is installed in C:/Python27)
import os
os.chdir('C:\\Pye\\')
from decoder import *
decode("12345")
I get the desired result in the python command prompt window so the code works fine. Then I tried to output those results to a text file, just so I don't have to copy-paste it all manually in the prompt window. After a bit of Googling (again, I'm kinda guessing what I'm doing here) I came up with this;
I wrote "a.py" script in the C:/Pye directory, and it looked like this;
from decoder import *
decode("12345")
And then I wrote a 01.py file that looked like this;
import subprocess
with open("result.txt", "w+") as output:
subprocess.call(["python", "c:/Pye/a.py"], stdout=output);
I see the result.txt gets created in the directory, but 0 bytes. Same happens if I already make an empty result.txt and execute the 01.py (I use Python Launcher).
Any ideas where am I screwing things up?
You didn't print anything in a.py. Change it to this:
from decoder import *
print(decode("12345"))
In the Python shell, it prints it automatically; but the Python shell is just a helper. In a file, you have to tell it explicitly.
When you run python and enter commands, it prints to standard out (the console by default) because you're using the shell. What is printed in the python shell is just a representation of what object is returned by that line of code. It's not actually equivalent to explicitly calling print.
When you run python with a file argument, it executes that script, line by line, without printing any variables to stdout unless you explicitly call "print()" or write directly to stdout.
Consider changing your script to use the print statement.:
print(decode("12345"))

Create and run Python program with a Python program

This is my first time using Python and I'm trying to create a program that can:
Create a new Python program in IDLE
Make the new program contain the print command - print('Hello, world!')
Save the program and run it
Exit IDLE
This is the code I have so far. It doesn't seem to be creating the file, and I might have made some other mistakes that I don't know about.
import sys
name = input('C:\\MyFolder\\program.py')
//Create program containing print command
file = open(name, 'w')
file.write("print('Hello, world!')")
file.close()
//Run program (and possibly save it?)
os.system('C:\\MyFolder\\program.py')
//Exit IDLE
sys.exit(0)
How do I create, write to and run the new program?
Although it isn't entirely clear from your question, I think I know what your problem is.
First, when you do input('C:\\MyFolder\\program.py'), that C:\\MyFolder\\program.py is just the prompt that gets displayed to the user. It's not a default value. So, if the user just hits return, name is going to be empty, and you're not going to successfully create a file.
Second, even if the user does type something, unless what he types is exactly C:\\MyFolder\\program.py, you're creating a file with one name, then trying to run a file with a different name, which isn't going to work.
So, you probably want something like this:
default_name = 'C:\\MyFolder\\program.py'
name = input(default_name)
if not name:
name = default_name
# ... your existing code to create the file
os.system(name)
There are a lot of ways you could improve this (use subprocess.check_call with sys.executable, add a shbang line to the file, use a with statement instead of explicit close, make the prompt look something like Filename (default C:\MyFolder\program.py)? instead of just the default value, …). But this should be enough to get it working.

Running Python script from .BAT file, taking .BAT Filename as input

I got a Python script (test1.py) I need to run with a bat file (render.bat).
Question 1:
First, I had a definition in my test1.py and it always failed to run, nothing happened. Can someone kindly explain why?
import os
def test01 :
os.system('explorer')
and in the bat file:
python c:/test01.py
but as soon as I removed the def it worked. I just want to learn why this happened.
Question 2:
How can I take "render" string from render.bat as a string input for my python script so I can run something like :
import os
def test1(input) :
os.system("explorer " + input)
So the "input" is taken from the .BAT filename?
Functions don't actually do anything unless you call them. Try putting test01() at the end of the script.
%0 will give you the full name of the batch file called, including the .bat. Stripping it will probably be easier in Python than in the batch file.
Question1: Keyword def in python defines a function. However, to use a function you have to explicitly call it, i.e.
import os
def test01(): # do not forget ()
os.system('explorer')
test01() # call the function
1) You have to actually call the functions to achieve your task.
2) %0 refers to the running script. Therefor create a test.bat file like
# echo off
echo %0
Output = test.bat
You can strip the .bat extension from the output.

Categories