[关闭]
@yizai 2015-07-31T21:45:38.000000Z 字数 11738 阅读 1341

Programming Fundamentals in Python

By: Tatiana Tylosky
Approximate time ~ 2 hours

Python


Introduction

About this Guide:

This guide was created for complete beginners (i.e. with no programming or computer science experience) and will teach you programming fundamentals in a language called Python. Following a project-driven learning philosophy you will learn as you build your own project. There will be GIFs and screenshots throughout this guide to make everything as clear as possible.

As you complete this guide you'll be creating a virtual pet we'll call "Pypet" (a "Python-pet"). Remember tamagochis? (Or if you were born in the 90s then think POKEMON!) With each new Python programming concepts you learn, you will add new features to your "Pypet".

There are no software or computer requirements for this guide except that you need access to a web browser (which you obviously already have at this point). You will learn how to use a free tool called Nitrous to set up your developer environment which takes away the typical pain of setting up a coding environment. It is also cloud based so you can log in from any computer to view your code.

What is Python?

Python is a scripting programming language known for both its simplicity and wide breadth of applications. For this reason it is considered one of the best languages for beginners. Used for everything from Web Development to Scientific Computing (and SO much more), Python is referred to as a “general purpose” language by the greater programming community.

Many Python programmers (aka “Pythonistas”) love this language because it maintains a certain philosophy of best practices, described in Tim Peter’s famous “Zen of Python”. There is a large Python community both off and online that is welcoming and supportive of beginners, and you can find a plethora of additional materials in the resources section of this guide.

Setup

To get started we'll need a "development environment", aka a place to write and execute code. For this we'll use Nitrous.io, a fast and free way to get you up and running. Nitrous is a cloud-based developer environment that works well for programming in python. Since Nitrous.io is a web application it won't matter whether you have a Mac or Windows or even Linux computer to run and test your code. Follow the instructions below to set up your Nitrous.io Development Environment.

  1. Go to Nitrous.io and create an account. NOTE: You will have to check your email and activate your account before you can sign in.
  2. Once you have confirmed your email and signed in, click the "open dashboard" button on their homepage. You should be prompted to create your first Nitrous "box" aka developer environment.
  3. First choose "Python/Django" as your template. Next you can rename your box to anything you like or just leave it as is. Finally, don't worry about the optional section that says "Download a GitHub repo". Here's an example:

  4. Click "Create Box" and then click "Next" until you see your box. Click on your box and then launch your environment by clicking the orange IDE button (which just stands for Integrated Development Environment). Now you have a powerful, cloud-based development environment that comes pre-installed with Python!

  5. Let's take a quick tour:

    • In the left panel, you’ll see the File Browser. Here you can navigate the files in your home folder. At this point, you will just have the "workspace" folder and a README file introducing you to Nitrous.IO. When you have more files, you can open them in Nitrous.IO’s text editor by double clicking on them in the File Browser.
    • The middle panel is the Text Editor. This is where you can write and edit code.
    • The right panel is for chatting if you’re using Nitrous.io in collaborative mode. Close this window for now by clicking the X in the upper right hand corner so you get more screen real estate.
    • The bottom panel is your console for actually running your python file.

Running Python for the first time

Here is a GIF demonstrating how to run your first python program. Feel free to either skip down and read the steps in the text below.

  1. Create a new file containing the following code in the text editor (middle panel):

    1. print 'Welcome to Pypet!'
  2. Go ahead and save the file as “pypet.py”.

  3. Now type python pypet.py into your Nitrous console (in the bottom panel) and hit enter. By doing this you are telling your console to open the file pypet.py and execute it using the program called python. The console will output “Welcome to Pypet!”.

You’ve just written your first print statement. Celebratory dance time. The print statement is a python function which prints things in the console — it's very handy for learning Python and debugging your code.

If you're stuck, take another look at the GIF above.

Creating your Pypet

Variables

Variables are a way of storing information in Python. Below we'll create different variables for our Pypet such as name, weight, etc. Below is a GIF that shows how you will create variables for your Pypet in this section. You can refer back to this as you follow along with the instructions below.

  1. Create a variable called name equal to 'Fluffy' (or 'Spike' or 'Sir Patrick').

    1. name = 'Fluffy'

    Using an equals sign (=) sets a variable to a given value such as name = 'Fluffy'.

    Variables can store different types of data. In this case, name is something called a string because 'Fluffy' has quotations around it. A string is just a set of characters surrounded by quotations (for example 'Bob', 'New York' or 'h4ck3r'). NOTE: Strings can use either single or double quotes in Python. A string can also include numbers, so long as it's in between quotes. Integers on the other hand do not have quotations. Let’s look at some additional data types.

  2. Create three additional variables to track age, weight and hungry.

    1. name = 'Fluffy'
    2. age = 5
    3. weight = 9.5
    4. hungry = False

    The age variable is an integer and therefore must be a whole number. The weight variable is a float. Floats are a numbers that can have values after the decimal point. The hungry variable is a a Boolean. Booleans store a value of either True or False. NOTE: Don't use quotations for these three data types, otherwise they'd all be considered strings

  3. Choose your Pypet's "photo". We've included a few options you can use below, but feel free to customize it.
    NOTE: Keep your Pypet's "photo" to just one line as it will make the initial steps easier to follow.


    Pycat

    (=^o.o^=)__

    Pymouse

    <:3 )~~~~

    Pyfish

    <`)))><

    Py? You choose!

    (^‘0M0’^)


  4. Now add another variable that is a string containing this photo variable of our pet.

    1. name = 'Fluffy'
    2. age = 5
    3. weight = 9.5
    4. hungry = False
    5. photo = '(=^o.o^=)__'
  5. Add some print statements to your code so you can see your Pypet in the console.

    1. name = 'Fluffy'
    2. age = 5
    3. weight = 9.5
    4. hungry = False
    5. photo = '(=^o.o^=)__'
    6. print 'Hello ' + name
    7. print photo

    By writing print 'Hello ' + name we just concatenated (aka linked together) the string 'Hello ' with the variable name so that the console will print out Hello Fluffy. Don't forget to type python pypet.py in the console (bottom window) and hit enter after you save to see this happen. Your console should look like:

Dictionaries

We need a way to tell Python that all of these variables represent one cat (or dog, fish, creature, etc). One way to do this is to use a Python dictionary. Dictionaries are a way of storing multiple variables that contain different values. Here is another GIF that you can refer back to as you follow along with the instructions below.

  1. Place your variables in a dictionary. Try using different values than the ones we have here.

    1. cat = {
    2. 'name': 'Fluffy',
    3. 'hungry': True,
    4. 'weight': 9.5,
    5. 'age': 5,
    6. 'photo': '(=^o.o^=)__',
    7. }

    Here we’ve created a dictionary called cat. Each line contains a different cat attribute. Attributes have both a key (ex. 'name', 'weight', 'age' etc) as well as a value (ex. 'Fluffy', True, 9.6 etc). Unlike assigning variables, which use an equals sign (name = 'Fluffy'), dictionary attributes use a colon and need to include a comma , after each value ('name':'Fluffy',)

  2. Add a print statement to view your new Pypet dictionary in the console.

    1. cat = {
    2. 'name': 'Fluffy',
    3. 'hungry': True,
    4. 'weight': 9.5,
    5. 'age': 5,
    6. 'photo': '(=^o.o^=)__',
    7. }
    8. print cat
  3. Print your Pypet's name and photo. You can access variables in an array by using the format dictionary['attribute'] such as cat['name'].

    1. cat = {
    2. 'name': 'Fluffy',
    3. 'hungry': True,
    4. 'weight': 9.5,
    5. 'age': 5,
    6. 'photo': '(=^o.o^=)__',
    7. }
    8. print 'Hello ' + cat['name']
    9. print cat['photo']
    10. print cat

    Don't forget to first save your file and then run your file in the console by typing python pypet.py and pressing enter.

Make sure to take another look at the GIF above if you get stuck.

Feeding your Pypet - Functions

Let's “feed” our pypet using a Python function. A function is a block of organized, reusable code that is used to perform a single action. First, we must define our function — feed — which changes our pypet’s hungry attribute to False to show that it is no longer hungry.

  1. Create this simple function by writing the following below your other code.

    1. def feed(pet):
    2. pet['hungry'] = False

    There are a couple of things to take note of here. By writing def feed(pet): you defining a function called feed that accepts one variable pet. You'll also notice we indent the next line pet['hungry'] = False. NOTE: In python the contents of a function must be indented.

  2. Add feed(cat) below your function to use the feed function on your Pypet, in this case cat.

    1. def feed(pet):
    2. pet['hungry'] = False
    3. feed(cat)

    By calling feed(cat) we are passing the variable cat into the function in place of pet. pet acts as a placeholder for whatever variable we decide to pass into the function.

    We should also increase the Pypet’s weight a bit since it has eaten.

  3. Add cat['weight'] = cat['weight'] + 1 to your feed function.

    1. def feed(cat):
    2. cat['hungry'] = False
    3. cat['weight'] = cat['weight'] + 1

    Use this notation to increase floats and integers.

  4. Try setting your original Pypet’s hungry variable to True and include a print cat statement after feed(cat) to see if your Pypet's hungry variable changed to False and their weight variable incrased.

    1. print 'Welome to Pypet!'
    2. cat = {
    3. 'name': 'Fluffy',
    4. 'hungry': True,
    5. 'weight': 9.5,
    6. 'age': 5,
    7. 'photo': '(=^o.o^=)__',
    8. }
    9. def feed(pet):
    10. pet['hungry'] = False
    11. pet['weight'] = pet['weight'] + 1
    12. print cat
    13. feed(cat)
    14. print cat

    When the cat is printed out the second time his weight attribute will have increased. Don't forget to save and then run your python file from the console.

If Statements

But what if our Pypet is not hungry? We need to take into account whether or not the hungry variable is set to True or False. In order to know whether our Pypet is hungry, we are going to use an if statement. In Python, if statements check to see whether a specific condition (such as whether or not hungry = True). Take a look at the GIF below to get an idea of what this looks like.

If the Pypet is hungry the program will set his hungry variable to False and increase his weight. If the Pypet is not hungry then it will print The Pypet is not hungry! in the console.

  1. Add an if statement inside of your function.

    1. def feed(pet):
    2. if pet['hungry'] == True:
    3. pet['hungry'] = False
    4. pet['weight'] = pet['weight'] + 1
    5. else:
    6. print 'The Pypet is not hungry!'
    7. print cat
    8. feed(cat)
    9. print cat

    Notice that we use two equals sign (==) to check a condition (for example pet['hungry'] == True). Only if the condition is not met the code beneath the else: will execute. Remember, one equal sign is used to assigned a value to a variable (pet['hungry'] = True makes our Pypet hungry), two equal signs are used to check if a condition is true (pet['hungry'] == True checks whether our Pypet is hungry).

  2. Add another feed(cat) below your function and try feeding the cat twice to see if the function worked!

    1. def feed(pet):
    2. if pet['hungry'] == True:
    3. pet['hungry'] = False
    4. pet['weight'] = pet['weight'] + 1
    5. else:
    6. print 'The Pypet is not hungry!'
    7. print cat
    8. feed(cat)
    9. print cat
    10. feed(cat)

If you get stuck don't forget to look back at the GIF above!

Friends for your Pypet - Lists

  1. Let’s create another Pypet using a dictionary. Add (or customize) the code below under your previous Pypet dictionary.

    1. mouse = {
    2. 'name': 'Mouse',
    3. 'age': 6,
    4. 'weight': 1.5,
    5. 'hungry': False,
    6. 'photo': '<:3 )~~~~',
    7. }

    NOTE: Make sure to place this new Pypet above your function (use the GIF as reference if you are confused)

  2. Create a list to hold both of your Pypets using pets = [cat, mouse].

    1. pets = [cat, mouse]

    Now that we have more than one Pypet we can store them in a Python list. A list is another data type; lists stores variables in order. If python isn't the first programming language you are learning, you may have heard of this same concept in other programming languages as an array.

For loops

What if we want to feed all the pets in our list? If we want to run a function on each variable in a list we can use something in Python called a loop. The for loop in Python has the ability to iterate over the items of any sequence, such as a list.

  1. for pet in pets:
  2. feed(pet)
  3. print pet

Take a screenshot of your Pypets and tweet them @Thinkful so I can share your creation with the world!

BONUS:

Once you have completed the steps above, you should feel free to add additional features that you design yourself! Here are some ideas to get you started:

Conclusion & Resources

Congrats for reaching the end of this guide! For your convenience we've placed a final version of our Pypet on GitHub, if you would like to take a look at the code. If you are stuck tweet @Thinkful and we'd love to help. Feel free to customize any or all of your project and try new things.

This guide is just the beginning of what you can do with Python. If you enjoyed the work you’ve done here, go through any of the additional resources below.

Free Resources:

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注