DEV Community

Cover image for Python - Variables
Flavio Campelo
Flavio Campelo

Posted on • Updated on

Python - Variables

📮 Contact 🇧🇷 🇺🇸 🇫🇷

Twitter
LinkedIn


Variables

Computer programs use variables to hold and work with values in memory. For this reason it's important to know a little bit more about them.

Keeping hard coded values

This sample shows how to print a calculated value to the user

myNumber = 2
print(myNumber)
Enter fullscreen mode Exit fullscreen mode

Getting value from user input

Most of the time, the program will wait or ask the user to input values. To do this with python is very simple. We'll use input() function for that.

myNumber = input("Enter a number: ")
print(myNumber)
Enter fullscreen mode Exit fullscreen mode

Breaking line

Using this code below, the program will wait for a value from the user.

myName = input("Enter your name")
print(myName)
Enter fullscreen mode Exit fullscreen mode

The issue here is that the user's response will be concatenated directly with the question.

Image 1

To solve that, we can use escape characters to insert a new line \n.

myName = input("Enter your name\n")
print(myName)
Enter fullscreen mode Exit fullscreen mode

Now, the question will be showed in one line and the answer in another one.

Image 2

Notes

You can access this code on github.

Typos or suggestions?

If you've found a typo, a sentence that could be improved or anything else that should be updated on this blog post, you can access it through a git repository and make a pull request. If you feel comfortable with github, instead of posting a comment, please go directly to https://github.com/campelo/documentation and open a new pull request with your changes.

Top comments (0)