Home > Articles > Open Source > Python

📄 Contents

  1. So, what is programming anyway?
  2. Getting Started with Python Programming
Like this article? We recommend

Getting Started with Python Programming

Let’s play with Python!

Printing and Variables

Go to your shell (the one with three angled brackets), and type the following.

print 'Hello, world!'

Press enter, and note what happens. Python should spit back ‘Hello, world!’, but without the quotes.  You’ve just written your first line of Python. print is a keyword that tells Python to print something to the screen, and the words in quotes are a string, which is just some text.

You can save for later use and reuse by storing it into a variable. You do that by typing:

>>> greeting = "Hello, world!"

Note that nothing was spit out when you hit enter. That’s because all Python did was store the value of ‘Hello, world!’ into the variable greeting.

Now that you have your value stored, you can print it!

>>> print greeting

That should print out the following (remember in this context, print means show on screen):

Hello, world!

If you want to save this code and run that (just in case you feel like greeting the world later), open up a new file in IDLE and enter the following:

greeting = "Hello, world!"
print greeting

Save it as ‘hello.py’ (File > Save), and then run it either by using the Run menu, or by pressing F5. You should see the greeting print out in the shell!

What Can You Store?

You can store all kinds of data in Python, but here are some of the most basic types:

  •     Whole numbers (integers)
  •     Decimal numbers (floats)
  •     Text (strings)
  •     Lists (just what it says — a list of things)

Let’s talk about numbers first.

Numbers

You have already seen how to store text. Let’s store a number! In your interpreter, enter the following:

>>> x = 5
>>> print x

Five should be printed out! The data type we’ve stored in x is an integer (a whole number). If you want more precision, you can store a float:

>>> y = 1.5

As soon as you add a decimal to a number, that value is now a float. You can even make a ‘whole’ number a float by adding a .0 to the end:

>>> x = 5.0

Math

Now that you know how to store variables, let’s try some math!

Math in Python looks pretty close to math in the real world.

Operation

Operator

Example

Addition

+

5 + 5

Subtraction

-

5 - 2

Multiplication

*

2 * 4

Division

/

6 / 2

Open up your interpreter and try the following:

>>> x = 5
>>> print x * x

You should get 25, because five times five is 25. Try entering the following:

>>> print "Hello " * 5

At first, you might think that wouldn’t work (it would have gotten me kicked out of algebra for certain). But you get five hellos!

Lists

To create a list, use square brackets around a series of items:

>>> ages = [5, 12, 33, 46]
>>> pets = ['Coe', 'Gizmo']

To get an item out of a list, you need to give Python the index number of the list. The index number is simply that item’s place in line. It’s important to remember that Python (and most programming languages) start counting at zero. So, the first item in the list is at index zero, the second is at index one, and so on.

Go ahead and enter the above lists into your interpreter, then try the following commands:

>>> print ages[0]
>>> print pets[1]

Note that the items in that index are printed out. What if you want to add an item to a list? You use the append method. Let’s add a pet to the list of pets. Type the following in your interpreter.

>>> pets.append('Niko')

Now, check to see what’s in the list. Enter this:

>>> pets

You now have three pets! Niko has been added to the end of the pets list.

Dictionaries

Dictionaries are a special kind of data type that can be incredibly useful when programming. A dictionary you keep on a shelf is filled with pairs of words and definitions. A dictionary in Python is filled with pairs of keys and values.

Open up a new file and enter the following code:

pets = {'Niko': 'cat',
    'Gizmo': 'dog',
    'Coe': 'fish',
    'Boxo': 'dog'}

print pets

Save the file as petdict.py and run it. Note what was printed out. You have paired each pet name with its species. The name is the key, and the species is the value.

If you want to get one value out of a dictionary, you give the dictionary the corresponding key. Try adding this line to the end of your code.

print pets['Boxo']

What was printed out? You should see this in your shell:

>>>
dog
>>>

If you want to add a value to the dictionary, give the dictionary a new key, and set the value. Change your file to look like this:

pets = {'Niko': 'cat',
    'Gizmo': 'dog',
    'Coe': 'fish',
    'Boxo': 'dog'}

pets['Ren'] = 'finch'

print pets

Save the file and run it. Note what was printed out. Now, the dictionary has a bird in it!

Note that we have two dogs in our dictionary. That’s okay! Values aren’t unique. Keys are, though. Watch what happens if we change the value of Coe to be a bit more specific:

pets = {'Niko': 'cat',
    'Gizmo': 'dog',
    'Coe': 'fish',
    'Boxo': 'dog'}

pets['Coe'] = 'betta'

print pets

The value associated with Coe was changed. We didn’t get a second entry for Coe. This is what should appear in your shell:

>>>
betta
>>>

Logic and If Statements

Storing information is all well and good, but programming also involves logic. Sometimes we want to do something only if something is true. Other times, you may want to do something a certain number of times.

Let’s say you only want a block of code to run if you have a certain number of apples. First, you’re going to need to see how many apples you have. To do this, you’re going to need to learn some new operators. These are used to compare one item against another. The following table describes the typical logic statements.

Operation

Operator

Example

Equal to

==

5 == 5

Not equal to

!=

5 != 6

Greater than

> 

6 > 2

Greater than or equal to

>=

4 >= 4

Less than

< 

4 < 7

Less than or equal to

<=

4 <= 4

Each of these expressions (some values and an operator used together) will return either True or False. Try these out in your interpreter:

>>> 5 == 6
>>> 5 != 6
>>> 4 > 4
>>> 4 <= 4

What did you get back?

You can use these expressions with an if statement so that you can have some code execute only if something is true. Open a file and enter the following:

apples = 5
if apples > 5:
    print "You have a bunch of apples!"

Save the file as apples.py.

Note the spaces before the print statement. IDLE should put those spaces in there for you, but if not, go ahead and put four spaces in before the print statement. That creates a block of code. Python will only run this block of code if you have more than five apples. If you didn't have these spaces here, Python wouldn't know what you wanted to do if you happened to have more than five apples.

Go ahead and run the file! Nothing should appear to happen. That’s because you have five apples, so nothing is printed. Try changing apples to six. Your code should look like this:

apples = 6
if apples > 5:
    print "You have a bunch of apples!"

Save the file and run it. This time, some text should be printed out!

For Loops

Sometimes, you want to run a block of code a certain number of times. The most common use case is running a block of code for every item in a list. To do this, use a for loop.

nums = [1, 3, 5, 6, 9]
for num in nums:
    print num
    print "Hi " * num

Save it as hi.py and run the file. What is printed out?

Basically, a for loop starts at the first item in a list and saves that value into a loop variable. For the loop in hi.py, that’s 'num’. Once the block of code is done, Python moves onto the next value in the list, saves that into the loop variable, and runs the block of code again.

Functions

Sometimes, you want to save a bit of functionality so you can call it later. This is when functions are useful. Open up a new file, and enter the following code:

def say_hi():
    print "Hello, there"

Save it as sayhi.py, then run it. Nothing should appear to happen, because what you need to do is call the function. Now, add a line to your file.

def say_hi():
    print "Hello, there"

say_hi()

Save it and run it. Now what happens? Python should greet you!

You can also pass values into functions. To do this, you need to add some parameters. When you add parameters, the value you send is stored in the parameter, and you can use it within the function. Let’s add one!

Open your file, and change the code like so:

def say_hi(name):
    print "Hello," name

say_hi('Joe')

Save the file and run it. This time, Joe should be greeted.

You can also give parameters a default value when you define them. Change your file to look like this:

def say_hi(name='person'):
    print "Hello," name

say_hi('Joe')
say_hi()

Now, Joe and a random person will be greeted!

User Input

Sometimes, you want to get input from the user. Let’s go over two ways to do that: input() and raw_input().

You can use input() to get a number from a user. Open up your interpreter and try the following:

>>> num = input('Give me a number: ')

You should get a prompt, asking for a number. Enter a number, then print out num:

Give me a number: 5
>>> print num

You should see your number there!

What if you don’t want a number, though? Then, you should use raw_input. This function will save whatever the user enters as a string.

>>> name = raw_input('Your name: ')
Your name: Katie
>>> print name
Katie

So, input() should be used for getting literal values, like numbers, and raw_input() should be used when you want to save exactly what the user entered as a string.

New Functionality

You can also bring new functionality into your program. Python comes with a large standard library that allows you to do so much more with your program with only a few extra lines of code.

I’ll just go over one module (that’s a part of a library) for now: random. Random is a great module for generating random numbers. To use random, you’ll need to import it. Open up your interpreter and enter the following:

>>> import random
>>> random.random()

What is printed out? It should be a float between one and zero. Go ahead and type out random.random() a few times, and see what is printed.

You can also import just the functionality you want from a module. Type this into your interpreter.

>>> from random import randint
>>> randint(10)

What was printed out? It should be a random number between zero and ten.

Random is hardly the only module available. For other available modules, check out the official documentation, or get a hold of Doug Hellmann’s book The Python Standard Library by Example.

Guessing Game, Redux

Now that you’ve been exposed to a bit of programming, let’s take another stab at our guessing game. Here’s a souped up version:

from random import randint

secret = randint(10)
guess = secret - 1

while guess != secret:
    guess = input("Give me a guess: ")
    if guess > secret:
        print "Sorry, that's too high!"
    if guess < secret:
        print "Sorry, that's too low."
    if guess == secret:
        print "That's right!"

With just a few lines of code, you have made the program much more robust! Run it, and see if you can follow what it does.

Learning More

This is just meant as an introduction to what Python and programming can do for you. However, as you can see, just knowing a few concepts can make something functional. It doesn’t take much code to make something cool, or to make your life easier.

If you’d like to learn more, I wrote a book geared towards the absolute beginner (Teach Yourself Python in 24 Hours) and a video training course as well (Python Guide for the Total Beginner LiveLessons). In it, I start at installation and go all the way up to making websites and games in Python. You should also check out Doug Hellmann’s book to learn more about the standard Python library. Finally, there is a mountain of documentation at the official Python site, including a tutorial to get you started!

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020