Accepting user input in applications is pretty standard as we would like to have the user give us some information.
In Python we can achieve this quite easily. Today, our end goal is to make a script that asks for some details and then prints these back to the user.
Using variables in Python
First of all, we must understand how we can use variables in Python, and this process is pretty simple.
animal = "cat"
print("Your favorite animal is a " + animal);
And this will print the following line:
Your favorite animal is a cat
Of course, I'm just guessing your favorite animal is a cat here and could be entirely off.
So let's fix that and allow the user to state the correct answer.
Accepting inputs in Python
We can change the variable we had to input()
, allowing us to accept user input.
print("What is your favorite animal?")
animal = input()
print("Your favorite animal is a " + animal)
Now when we run the script, the user will be prompted to give us input.
And it's really as simple as using that input()
command to capture a variable!
Thank you for reading, and let's connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter
Latest comments (3)
Glad to see you diving deeper into python. Outside of toy examples I cannot think of an application I have ever had for
input
typically I accept user input in the form of stdin, or a file. You can use parsers from the built in argparse module, or the more sophisticated click library. For super basic things, I often reach for sys.argv, its not fancy but works.Here is a super basic example.
You can get super quick and dirty by adding a
#! python
at the top ofexample.py
so that you can leave off the python part of the command. Fair warning, doing this can lead to some good "works on my machine" errors if you happen to try to share a script with this in it.Wow thanks!
Yeah I was thinking how often you might need it, perhaps if you would make some kind of console command, but not sure why you would use Python for that.
Think i'm also going to look at the visual interface so far Tkinter looks the best, what's you're take on that?
I've never done a gui interface with python. I stick to using python for backend/data things and the web for front end UI. Nothing wrong with doing UI in python, I've just not had a use case for it.