Python functions in VSCode - python

I need help with running a python file in VSCode. At the moment I can right-click the file and choose "Run Python File in Terminal" and it works for the simple things like:
v = "Hello World"
print(v)
However, I want to run a function with user input and I just can't get it to work. Can someone tell me how it's done? Example of a function:
def userInput():
v = input("What do you want to print? ")
print(v)

Alright, based on what I've read in the comments this should fix things:
# yourfile.py
def userInput():
v = input("What do you want to print? ")
print(v)
userInput()
The final line actually calls the function, as opposed to just defining it. If this still gives you trouble, let me know and we can keep working through things!

Related

Python 3 input() function not allowing input

I haven't really ran into many issues with python but I'm working on a side project and the input() function wasn't working. I created a new file to test out a simple input() function and the same thing happened, the program doesn't take any input and it instead seems to take in the pyenv version or something? Anyone know how to fix this?
# Taking input from the user
name = input("Enter your name")
# Print input
print("Hello", name)
Pasted output from terminal:
Enter your namepyenv shell 2.7.18
Hello pyenv shell 2.7.18

How do I call a function in vs code using 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.

Python IDE PyCharm won't print last line of code

I'm a complete newbie when it comes to coding, so I'm probably making a stupid mistake here. What I'm doing is following along with a Python For Beginners textbook and writing the 'Hello World' exercise. I added the variable 'name' to the code and called the variable in the very next line. However, the
print('Hello', name) line of code I wrote would not print, even though my first line print('Hello, world') did print. Here's a screenshot of the code run on the Python console There are no error codes, so I'm guessing I just incorrectly defined the variable, but I'm not sure.
You need to hit Enter after Python prints 'Keenan' to print the last line.
When you call input(str), str is the prompt. Once python prints the prompt, it's waiting for an input and then Enter.
So logically speaking your code should be:
name = input("What's your name?:")
print('Hello', name)
Which will print:
What's your name?:
where you can type:
What's your name?: Keenan
followed by Enter

Script Parameters with PyCharm - Learn Python the Hard way

I started to learn Python with learn Python the Hard Way and I am facing some issues with ex13. I would like to now if it is a mistake of mine or because of the way PyCharm works.
Basically to make the script work as the exercise suggests I saw I have to manually enter the parameters names in PyCharm with run>edit configuration
I put "first" "second" and "third"
But I would like to combine raw_input and argv so I can let the user choose the name of the parameters. Here's what I wrote:
from sys import argv
first = raw_input("First argument: ")
second = raw_input("Second argument: ")
third = raw_input("Third argument: ")
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
It runs but it returns:
ValueError: need more than 1 value to unpack
It seems that in PyCharm I have to enter manually all the script parameters ? There is no way to combine it with raw input ?
Thanks for your help.
note check out Joran's answer which shows a good combination of using command line args and prompting for user inputs. Below is a break down of what is going on:
This is expected behaviour in PyCharm to specify the parameters you want PyCharm to execute your script with. Think of it like PyCharm doing something like this:
python my_script.py
However, PyCharm does not know the arguments you want to pass, you need to provide this, so it knows how to run your script. If you look near the bottom of your PyCharm window, there is a Terminal tab. You can use that to quickly execute your script and provide args.
Secondly, the reason why you are getting the error you are getting is because you are not handling your script inputs properly when trying to use argv.
You are mixing up using raw_input, which takes in user input when your Python script is running, as opposed to argv which takes parameters in to your Python script when you run it.
So, what you are looking to actually do here, is not use raw_input, but simply argv. Here is a small demo to clarify all this:
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
Now, go in to your command prompt and do this:
python my_script one two three
You will get:
The script is called: my_script.py
Your first variable is: one
Your second variable is: two
Your third variable is: three
This is a very simplified example, and you're probably going to need to add some handling of your inputs, or you're going to get a lot of errors with different inputs to your script. With that, I suggest maybe looking at argparse instead
Im not sure i understand the question ... but the code below will use the command line arguments if there are 3(or more) ... otherwise it will prompt and split the same way as the shell splits command line arguments
import shlex # shlex.split will split the string the same way that the shell would for command line args
if len(sys.argv) < 3:
args = (list(sys.argv) + shlex.split(raw_input("Enter Args:")))[:3]
else:
args = sys.argv[:3]
print "Using Args:",args
one,two,three = args

Python - I have previously defined variables yet they do not work in one function

At the very beginning of the Python Script, I have defined a lot of variables. For instance:
cmd_attack = "attack"
cmd_protect = "protect"
cmd_help = "help"
cmd_help works in a user menu function shown here:
def usermenu():
um_in=raw_input('Menu :: ')
#Help Command
if um_in.lower()==cmd_help.lower():
print(helplist)
usermenu()
That is successful - it prints the help list and then returns to the raw input. However, when I do something similar involving cmd_help in another function...
def tf_elf_battle_merc():
battleinput==raw_input('Elf :: ')
global cmd_help
global cmd_attack
global cmd_protect
if battleinput.lower()==cmd_attack.lower():
attack_merc()
elif battleinput.lower()==cmd_help.lower():
print(tf_elf_help)
That does nothing, prints no errors, and returns to the shell line - without printing anything or going anywhere. I used global commands because I was testing out possible solutions to the problem.
The order that these are put in is the CMD functions at the top, the tf_elf_battle_merc() in the middle, and the usermenu() last. I have tried a few things and the related questions haven't helped... any thoughts? I'm kind of new to Python. If you're curious, it is script where you can log in and play text-type games.
The full script is here on Pastebin.
Thank you in advance!
Edit: If you download and run the script - use "Guest" (case-sensitive) as a username and you'll be let into it
Your code (with some edits, seen below) worked fine for me after changing battleinput==raw_input('Elf :: ') to battleinput=raw_input('Elf ::'), you don't want to compare them, you want to define battleinput.
However, it should raise an error of that, since battleinput is not defined, yet you're trying to comparing it: if battleinput.lower() == ....
Also you're mixing Python 3 and Python 2? Using raw_input() from Python 2, yet print("asd") from Python 3, instead of Python 2's print "asd"?
Everything looks like your code is never reached, the problem is elsewhere.
Here's the code for Python 3, which works fine:
cmd_attack = "attack"
cmd_protect = "protect"
cmd_help = "help"
def tf_elf_battle_merc():
battleinput=input('Elf :: ') # Use raw_input() for Python 2
# You don't need the globals here
if battleinput.lower()==cmd_attack.lower():
print("attack")
elif battleinput.lower()==cmd_help.lower():
print("help")
tf_elf_battle_merc()

Categories