ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Learn To Program: Variables and User Input

Updated on December 31, 2013
susi10 profile image

Susan is a science geek, and if that wasn't enough, she gets all nerdy over technology too. She is also a writer too.

Learn to code with these tutorials!
Learn to code with these tutorials! | Source

Learn To Program Tutorials

For these tutorials, you will need Python. This is Tutorial 2 of this series.

Click here for Tutorial 1 where you will learn about Python, how to install Python, how to use IDLE and create your first program.

Variables

The Hello World program is good but is not very interesting. The only thing that happens is that a piece of text is printed on the screen of your computer. We need to make our programs much more interesting! But how?

Well, first of all, to make a program more interesting, we need the computer to remember something like our name or our favourite colour. We can then ask Python to say "Hello! Nice to meet you...", followed by our name. That would personalize things a lot more.

To get Python to remember something for us, we store whatever it is we want to store in a variable. A variable is a word that stores the thing we want to store. So, we might store our name within a variable, which will be used again later within our program. Variables will become very handy in our programming endeavours!

Variables Explained...

My name is stored in the variable: my_name
My name is stored in the variable: my_name

Legal Python Variable Names:

  1. The beginning of a variable name can only begin with an underscore (-) or a letter.
  2. Variable names can only contain numbers, letters and the underscore.

Let's Create A Variable

You can call a variable whatever you want, preferably a word which you will know what is stored in it when re-reading your program again. So if we want to store our name in a variable, I would call the variable my_name or myName. Think of the name you will use but keep the following rules to the right in mind.

Assigning Your Variable To A Name:

To store your name within your chosen variable name, you:

  1. Write the name of your variable
  2. Add an equal sign on the same line. This will tell Python that you want to store your chosen text or number within that variable or in other words, that variable is equal to the text or number you have stored in it.
  3. After the equal sign, add the text or number that you want to store to the line.
  4. If you want to display your code write 'print' followed by your variable which will display whatever is stored in it.

The result of following the steps above is shown in the code below. Simply type the following code into Python's New Window and press save and run it. Make sure to write your name in the "yourname" space.

Below is an example of storing the word 'Susan' in the variable 'my_name' and then printing it. Let's see what happens.


my_name = "Susan"
print (my_name)

Result...

As you can see, my name Susan is printed on the screen.
As you can see, my name Susan is printed on the screen.

Using what we have learned from this small program, let's make a more interesting program out of it. I am going to get the computer to say hello and then my name, to add a more personalized touch.

my_name = "yourname"
print('Hi there!')
print ('It is nice to meet you, ' + my_name)
print(' Bye for now, ' + my_name)

The Code Explained

The first line is known as an assignment statement. You are assigning or storing your name within that variable. Remember to put quotes around your name as it is a string!

The computer then prints a greeting and then it says that it is nice to meet you and adds your name to the sentence which is stored in the variable my_name. Notice that the string in line 3 is ended and then the variable is added on. You do not add the variable as part of the string.

Result...

The result of the code that I wrote from above.
The result of the code that I wrote from above.

User Input

Let's say that you wanted your computer to ask you for your name and then print 'Nice to meet you' followed by whatever you have typed ie: your name. To create this program, Python will be asking for user input. That input that you give to Python will be stored within a variable. Then, Python will be able to print that variable again. To ask a user for input and then store it in a variable, the following line of code is used.

user_name = input() 

Time Module and Printing Blank Spaces

Before we make a full program based on this, firstly we should learn about creating blank spaces and placing a time delay. Instead of all the text coming out in one big block, we can have each line printed separately and with a time delay.

After each line, we will have to put a print() . The brackets are empty as we only want to print a space with no text. To have a time delay, we will need to import a module. This module is called the "time module" and to import it, at the start of our program we will put "import time". Then, every time we want a time delay between the printing of each line, we add time.sleep(1) after each line. The number in the brackets is the amount of seconds that you want to elapse.

Let's make a full program out of this incorporating what we have learned.

import time
print("What's your name?")
my_name = input()
print('Hi there!')
print()
time.sleep(1)
print('It is nice to meet you, ' + my_name)
print()
time.sleep(1)
print('Bye for now, ' + my_name)

Technical Stuff: What is a Module?

A module is a file in Python's library which contains Python definitions and statements. If you created a formula and you had to use it more than a couple of times across multiple programs, you will have to create a module. You can then access that module simply by importing it.

Hubbers and Guest Users To Complete The Challenge

Here is a list of those who have completed the challenge with perfect code. Well done to all!

  • drpennypincher - He got his code in first and it was great. Well done!

Challenge

After this lesson and Lesson 1, you have learned a lot so well done! Try composing programs which ask for user input and then print these programs. But if you want an exercise, try the challenge below. If you know how to do it, just tell me in the comments and paste your code as well. Let's see how many of us can do it! Here is the challenge.

The Challenge: Your name is Mr/Ms.Jones and you have approached an ATM machine. Write a program based on how the ATM program would be. Here is an outline of what is expected.

  1. Welcome to Universal Bank!
  2. What is your name?
  3. Nice to meet you ....
  4. How much would you like to withdraw (name)?
  5. Taking (amount).... from your account.
  6. Done! Please take your ...(amount)

This program isn't the most advanced it could be but over the weeks, you will learn how to make it better and more impressive. Make sure to incorporate the time module and blank spaces. Good luck!

In The Next Tutorial...

Our next Tutorial which is the 3rd in this series, will focus on if statements, how Python makes decisions and while loops as well as making a simple game.

© 2013 Susan W

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Kasia 

      3 years ago

      I simply want to meontin I'm very new to blogging and actually loved you're blog site. Almost certainly I’m going to bookmark your blog . You really come with tremendous well written articles. Thanks for sharing your website page.

    • susi10 profile imageAUTHOR

      Susan W 

      4 years ago from The British Isles, Europe

      Hi bfilipek,

      Thanks for dropping by and for commenting. Yes, I forgot to mention that variables are stored in the memory. I'll add that in soon.

    • profile image

      bfilipek 

      4 years ago

      Good, plain and simple. I would also mention that variables are stored in the memory.

    • susi10 profile imageAUTHOR

      Susan W 

      4 years ago from The British Isles, Europe

      Hi electronician,

      Thanks for dropping by, for voting up and for your kind comments. I appreciate your visit and I'm glad you found it useful. Variables can be difficult for beginners to grasp at first but hopefully, this tutorial should make things easier.

    • electronician profile image

      Dean Walsh 

      4 years ago from Birmingham, England

      Great introduction to variables, voted up!

    • susi10 profile imageAUTHOR

      Susan W 

      4 years ago from The British Isles, Europe

      Hi Dr Penny Pincher,

      Thanks for doing the challenge and for submitting your code. Well done, your code is perfect! Hmm...I wish I could offer you a prize of some sort to say thanks for doing the challenge. I will make a list of those who completed the challenge and place it under the challenge question. You are first on the list, congrats! I'm really glad that you are learning from these tutorials and Tutorial 3 is coming in the next few days.

      Thanks again for everything, Dr Penny Pincher.

    • drpennypincher profile image

      Dr Penny Pincher 

      4 years ago from Iowa, USA

      Susi10, Below is what I came up with for the challenge. Looking forward to Tuitorial 3!

      import time

      print('Welcome to Universal Bank!')

      time.sleep(1)

      print('What is your name?')

      my_name = input()

      print('Nice to meet you...')

      time.sleep(1)

      print('How much would you like to withdraw, ' + my_name)

      withdrawl_amount=input()

      print()

      time.sleep(1)

      print('Taking $' + withdrawl_amount + ' from your account...')

      print()

      time.sleep(2)

      print('Done! Please take your $' + withdrawl_amount)

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)