Learn Python For Beginners

Python User Input

Python user input is a great way to start getting dynamic data to build more robust python software applications. The logic is simple really. Prompt a user for input in a certain scenario and store that input as data in memory. Python makes gathering user input extremely simple. Just like we did when we started this series for learning python for beginners, create a new file under the parent directory and name it user_input. Try typing something like this in the new file:

Python User Input

When you run this program it is going to behave differently than you are used to if you have been following the series at this point. The terminal will run like usual but you will notice that it waits for input to the prompt. Click next to the prompt in the terminal and enter an answer. Then hit enter and watch as the terminal will probably hold for a second as it stores the input into the variable and then print back the value you typed in.

Python User Input

Working With User Input

Let’s take what we’ve learned in python operators and python variables and write a program that adds two numbers together. Feel free to attempt to do this yourself before moving on. If you don’t want to try writing it yourself try writing something like this.

Before you run this code, take a good look at it because there is actually something wrong with it. Try to figure it out for a minute and when you’re ready run the program and respond to the prompts in the terminal. You are going to get something like this:

What happened? If you remember when we talked about the difference between strings and integers you can see that even if the user puts a number into the input function in python, it gets stored as a string. To fix this we can use another built-in function. The int function can change a string or float into an integer. Also, we can use pythons str function to convert an integer or float to a string. Let’s try this instead:

Some of you with a keen eye may be noticing a trend with how functions work. Functions have data that can be passed into them. These are known on parameters. More on that later. For now click run and make sure everything is working as expected.

Congratulations! Now you are starting to see how to write logic around user input in a python program. There is still a bit of a road ahead of you but for now I urge you to experiment with the things you have learned until this point. A good place to start would be to take a look at a list of all of pythons built-in functions. Otherwise, let’s continue to the python if statement.

Leave a Comment

Your email address will not be published. Required fields are marked *