Pinterest Stumbleupon Whatsapp
Advertisement

If you’re going to learn a new language today, Python is one of the options out there 5 Reasons Why Python Programming Is Not Useless 5 Reasons Why Python Programming Is Not Useless Python -- You either love it or you hate it. You might even swing from one end to the other like a pendulum. Regardless, Python is a language that's hard to be ambivalent about. Read More . Not only is it relatively easy to learn, but it has many practical uses that can come in handy across several different tech-related careers 6 of the Best Paying Tech Careers for 2016 6 of the Best Paying Tech Careers for 2016 Investing in the right technology career requires planning and foresight. These six career options are expected to be the hottest in the next few years. Are you ready? Read More .

This article is for those who already have some programming experience and simply want to transition to Python as quickly as possible. If you have absolutely no programming experience whatsoever, we instead recommend these Python tutorial websites The 5 Best Websites To Learn Python Programming The 5 Best Websites To Learn Python Programming Over the past decade, the Python programming language has exploded in popularity amongst programmers in all areas of coding. From web developers to video game designers to in-house tool creators, many people have fallen in... Read More and these online Python courses 5 Courses That'll Take You from Python Beginner to Pro 5 Courses That'll Take You from Python Beginner to Pro These five courses will teach you all about programming in Python, one of the hottest languages out there right now. Read More .

All basic Python examples were written for Python 3.x. We cannot guarantee that they’ll work on Python 2.x, but the concepts should be transferable.

Strings

Proper string manipulation is something that every Python programmer needs to learn. Strings are involved whether you’re doing web development, game development, data analysis, and more. There’s a right way and a wrong way to deal with strings in Python.

String Formatting

Let’s say you have two strings:

>>>name = "Joel"
>>>job = "Programmer"

And let’s say you want to concatenate (“join together”) the two strings into one. Most people might be inclined to do this:

>>>title = name + " the " + job
>>>title
>"Joel the Programmer"

But this isn’t considered Pythonic. There is a faster way to manipulate strings that results in more readable code. Prefer to use the format() method:

>>>title = "{} the {}".format(name, job)
>>>title
>"Joel the Programmer"

The {} is a placeholder that gets replaced by the parameters of the format() method in sequential order. The first {} gets replaced by the name parameter and the second {} gets replaced by the job parameter. You can have as many {}s and parameters as you want as long as the count matches.

What’s nice is that the parameters don’t have to be strings. They can be anything that can be represented as strings, so you could include an integer if you wish:

>>>age = 28
>>>title = "{} the {} of {} years".format(name, job, age)
>>>title
>"Joel the Programmer of 28 years"

String Joining

Another nifty Pythonic trick is the join() method, which takes a list of strings and combines them into one string. Here’s an example:

>>>availability = ["Monday", "Wednesday", "Friday", "Saturday"]
>>>result = " - ".join(availability)
>>>result
>'Monday - Wednesday - Friday - Saturday'

The defined string is the separator that goes between each list item, and the separator is only inserted between two items (so you won’t have an extraneous one at the end). Using the join method is much faster than doing it by hand.

Conditionals

Programming would be pointless without conditional statements. Fortunately, conditionals in Python are clean and easy to wrap your head around. It almost feels like writing pseudocode. That’s how beautiful Python can be.

Boolean Values

Like in all other programming languages, comparison operators evaluate to a boolean result: either True or False. Here are all the comparison operators in Python:

>>>x = 10
>>>print(x == 10) # True
>>>print(x != 10) # False
>>>print(x <> 10) # False, same as != operator
>>>print(x > 5) # True
>>>print(x < 15) # True
>>>print(x >= 10) # True
>>>print(x <= 10) # True

The is and not Operators

The ==, !=, and <> operators above are used to compare the values of two variables. If you want to check if two variables point to the same exact object, then you’ll need to use the is operator:

>>>a = [1,2,3]
>>>b = [1,2,3]
>>>c = a
>>>print(a == b) # True
>>>print(a is b) # False
>>>print(a is c) # True

You can negate a boolean value by preceding it with the not operator:

>>>a = [1,2,3]
>>>b = [1,2,3]
>>>if a is not b:
>>>    # Do something here
>>>x = False
>>>if not x:
>>>    # Do something here

The in Operator

If you just want to check if a value exists within an iterable object, like a list or a dictionary, then the quickest way is to use the in operator:

>>>availability = ["Monday", "Tuesday", "Friday"]
>>>request = "Saturday"
>>>if request in availability:
>>>    print("I'm available on that day!")

Complex Conditionals

You can combine multiple conditional statements together using the and and or operators. The and operator evaluates to True if both sides evaluate to True, otherwise False. The or operator evaluates to True if either side evaluates to True, otherwise False.

>>>legs = 8
>>>habitat = "Land"
>>>if legs == 8 and habitat == "Land":
>>>    species = "Spider"
>>>weather = "Sunny"
>>>if weather == "Rain" or weather == "Snow":
>>>    umbrella = True
>>>else:
>>>    umbrella = False

You could compact that last example even further:

>>>weather = "Sunny"
>>>umbrella = weather == "Rain" or weather == "Snow"
>>>umbrella
>False

Loops

The most basic type of loop in Python is the while loop, which keeps repeating as long as the conditional statement evaluates to True:

>>>i = 0
>>>while i < 10:
>>>    print(i)
>>>    i = i + 1

This could also be structured like so:

>>>i = 0
>>>while True:
>>>    print(i)
>>>    if i >= 10:
>>>    break

The break statement is used to immediately exit out of a loop. If you just want to skip the rest of the current loop and start the next iteration, you can use continue.

The For Loop

The more Pythonic approach is to use for loops. The for loop in Python is nothing like the for loop that you’d find in a C-related language like Java or C#. It’s much closer in design to the foreach loops in those languages.

In short, the for loop iterates over an iterable object (like a list or dictionary) using the in operator:

>>>weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
>>>for day in weekdays:
>>>    print(day)

The for loop starts at the beginning of the weekdays list, assigns the first item to the day variable, and the first loop through applies only to that variable. When the loop ends, the next item in the weekdays list gets assigned to day and loops through again. It keeps going until you reach the end of the weekdays list.

If you just want to run a loop for X amount of iterations, Python provides a range() method just for that purpose:

>>># Prints 0,1,2,3,4,5,6,7,8,9
>>>for i in range(10):
>>>    print(i)

When it only has one parameter, range() starts at zero and counts up one by one to the parameter value but stops just short of it. If you provide two parameters, range() starts at the first value and counts up one by one to the second value but stops just short of it:

>>># Prints 5,6,7,8,9
>>>for i in range(5, 10):
>>>    print(i)

If you want to count in intervals other than one by one, you can provide a third parameter. The following loop is the exact same as the previous one, except it skips by two instead of one:

>>># Prints 5,7,9
>>>for i in range(5, 10, 2):
>>>    print(i)

Enumerations

If you’re coming from another language, you might notice that looping through an iterable object doesn’t give you the index of that object in the list. Indexes are usually non-Pythonic and should be avoided, but if you really need them, you can use the enumerate() method:

>>>weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
>>>for i, day in enumerate(weekdays):
>>>    print("{} is weekday {}".format(day, i))

This would result in:

>Monday is weekday 0
>Tuesday is weekday 1
>Wednesday is weekday 2
>Thursday is weekday 3
>Friday is weekday 4

For comparison, this is NOT the way to do it:

>>>i = 0
>>>for day in weekdays:
>>>    print("{} is weekday {}".format(day, i))
>>>    i = i + 1

Dictionaries

Dictionaries (or dicts) are the most important data type to know in Python. You’re going to be using them all the time. They’re fast, they’re easy to use, and they will keep your code clean and readable 10 Tips for Writing Cleaner & Better Code 10 Tips for Writing Cleaner & Better Code Writing clean code looks easier than it actually is, but the benefits are worth it. Here's how you can start writing cleaner code today. Read More . Mastery of dicts is half the battle in learning Python.

The good news is that you’ve probably been exposed to dicts already, but you likely know them as hash tables or hash maps. It’s the exact same thing: an associative array of key-value pairs. In a list, you access the contents by using an index; in a dict, you access the contents by using a key.

How to declare an empty dict:

>>>d = {}

How to assign a dict key to a value:

>>>d = {}
>>>d["one_key"] = 10
>>>d["two_key"] = 25
>>>d["another_key"] = "Whatever you want"

The nice thing about a dict is that you can mix and match variable types. It doesn’t matter what you put in there. To make initialization of a dict easier, you can use this syntax:

>>>d = {
>>>    "one_key": 10,
>>>    "two_key": 25,
>>>    "another_key": "Whatever you want"
>>>}

To access a dict value by key:

>>>d["one_key"]
>10
>>>d["another_key"]
>"Whatever you want"
>>>d["one_key"] + d["two_key"]
>35

To iterate over a dict, use a for loop like so:

>>>for key in d:
>>>    print(key)

To iterate both keys and values, use the items() method:

>>>for key, value in d.items():
>>>    print(key, value)

And if you want to remove an item from a dict, use the del operator:

>>>del d["one_key"]

Again, dicts can be used for so many different things, but here’s a simple example: mapping every US state to its capital. Initialization of the dict might look like this:

>>>capitals = {
>>>    "Alabama": "Montgomery",
>>>    "Alaska": "Juneau",
>>>    "Arizona": "Phoenix",
>>>    ...
>>>}

And whenever you need the capital of a state, you can access it like so:

>>>state = "Pennsylvania"
>>>capitals[state]
>"Harrisburg"

Keep Learning Python: It’s Worth It!

These are just the basic aspects of Python that set it apart from most of the other languages out there. If you understand what we covered in this article, then you’re well on your way towards mastering Python. Keep at it and you’ll get there in no time.

If you had trouble following, don’t worry. It doesn’t mean that you aren’t meant to be a programmer 6 Signs That You Are Not Meant To Be A Programmer 6 Signs That You Are Not Meant To Be A Programmer Not everyone is cut out to be a programmer. If you aren't completely sure that you're meant to be a programmer, here are some signs that may point you in the right direction. Read More ; it only means that Python doesn’t click as easily for you. If that’s the case, I recommend that you check out these tips for learning new programming languages 7 Useful Tricks for Mastering a New Programming Language 7 Useful Tricks for Mastering a New Programming Language It's okay to be overwhelmed when you are learning to code. You'll probably forget things as quickly as you learn them. These tips can help you to better retain all that new information. Read More .

Most of all, it should be challenging but it shouldn’t be stressful. If it is, check out our tips on learning to program without the stress How To Learn Programming Without All The Stress How To Learn Programming Without All The Stress Maybe you've decided to pursue programming, whether for a career or just as a hobby. Great! But maybe you're starting to feel overwhelmed. Not so great. Here's help to ease your journey. Read More .

Is there anything about Python that you don’t understand? Got any other tips to share with Python newbies? Let us know in the comments below!

Leave a Reply

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

  1. Peg
    March 14, 2017 at 6:59 pm

    I am struggling with getting Python to really "click".... what I am looking for but rarely find is a "translation" similar to what you do for the string join a little. I am looking for a literal translation into English for each word, punctuation, symbol, bracket, parenth, etc. I have gone through many, many tutorials, typing the examples, and granted I am not a 'natural' programmer, but what i constantly struggle with is what a word means - I can find what the def'n of a python term is, but, for example, the word string is often used as a generic placeholder (parameter?) - but it depends on the fx or whatever what the use of that word is. So I am looking for a BASIC basic basic tutorial that breaks down each piece of a python progrm.

  2. Brice
    December 30, 2016 at 4:19 pm

    Now that `in` has been shown, it would be better to use
    umbrella = weather in ["Rain", "Snow"]
    instead of
    umbrella = weather == "Rain" or weather == "Snow"
    don't you think?
    Or at least, more pythonic if not better...

  3. Adrian
    December 27, 2016 at 8:24 pm

    Why if I compare d = {} and e = dict() using "is" the result is False?

  4. Joseph Pollock
    December 21, 2016 at 10:15 pm

    Nice intro article. I posted a link to it on the AutoKey list https://groups.google.com/forum/#!forum/autokey-users because AutoKey macros are written in Python.

  5. Daan Timmer
    December 16, 2016 at 2:57 pm

    You are forgetting another very powerful comparison in python:
    if 1 < 2 < 3: pass

    • Joel Lee
      December 16, 2016 at 8:17 pm

      Thanks Daan, that's definitely a nice quality of life feature that many languages don't have.

  6. Ceprey
    December 16, 2016 at 10:11 am

    >>>weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
    >>>for i, day in enumerate(weekdays):
    >>> print("{} is weekday {}".format(day, i))

    Are you sure that Monday will be Weekday 1?

    • Joel Lee
      December 16, 2016 at 8:16 pm

      Thanks Ceprey, good catch. Fixed!