You are on page 1of 11

y p

PC & MOBILE LIFESTYLE

That Will Help You Learn


Fast
By Joel Lee / December 15, 2016 15-12-2016 / 9 minutes

Joel Lee
1754 articles

Joel Lee has a B.S. in Computer


Science and over six years of
Email Facebook Pinterest Twitter
professional writing experience. H
Advertisement is the Editor in Chief for
MakeUseOf.

If you’re going to learn a new language today, Python is


one of the options out there. 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.

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 Latest Giveaways!
hard to be ambivalent about.
Don’t Buy a Raspber
READ MORE Until You’ve Seen Cr
All-in-One Kit (Revie
and Giveaway!)
This article is for those who already have some
Bosma X1 Review: A
programming experience and simply want to transition to
Decent Indoor Secur
Python as quickly as possible. If you have absolutely no Cam That Lacks Poli
programming experience whatsoever, we instead
recommend these Python tutorial websites and these
online Python courses.
All basic Python examples were written for Python 3.x. We Mipow Power Cube X
PC & MOBILE LIFESTYLE
cannot guarantee that they’ll work on Python 2.x, but the
Wireless Charger AN
Power Bank
concepts should be transferable.
Related Articles
Strings PROGRAMMING

The 11 Best Sites for


Proper string manipulation is something that every Python Online Computer
programmer needs to learn. Strings are involved whether Programming Cours
you’re doing web development, game development, data
PROGRAMMING
analysis, and more. There’s a right way and a wrong way to
5 Functional
deal with strings in Python. Programming Langu
You Should Know
String Formatting
LINUX , PROGRAMMING

How to Add Top Feat


Let’s say you have two strings:
From Other Text Edi
to Vim
>>>name = "Joel"
>>>job = "Programmer"

And let’s say you want to concatenate (“join together”) the


Latest Videos
two strings into one. Most people might be inclined to do
this:

python databases
crate.io

nosql database for python open


source data store as backend Taste Test: Frozen Pizza DOW
UNDER | TGTS S3E5

OPEN

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


>>>title
>"Joel the Programmer"
How to Fix the "Windows Can
Automatically Detect This
But this isn’t considered Pythonic. There is a faster way to
PC & MOBILE LIFESTYLE
manipulate strings that results in more readable code.
Prefer to use the format() method:

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


>>>title
>"Joel the Programmer" Bosma X1 Security Cam Review
Decent Indoor Security Cam T
The {} is a placeholder that gets replaced by the
parameters of the format() method in sequential order. The
rst {} 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.


Don't Buy a Raspberry Pi Unt
They can be anything that can be represented as strings,
You've Seen The CrowPi All i
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 Arduino Tra ic Light Tutoria

Another nifty Pythonic trick is the join() method, which


takes a list of strings and combines them into one string.
Here’s an example:

python databases
crate.io Taste Test: Energy Drinks (Wha
nosql database for python open source V?) | TGTS S3E4
data store as backend

OPEN
>>>availability = ["Monday", "Wednesday",
PC & MOBILE "Friday", "Saturday
LIFESTYLE
>>>result = " - ".join(availability)
>>>result
>'Monday - Wednesday - Friday - Saturday' Latest Deals
Pay What You $
The de ned string is the separator that goes between each Want: Adobe CC
list item, and the separator is only inserted between two A-Z Lifetime
items (so you won’t have an extraneous one at the end).
Using the join method is much faster than doing it by hand.
The Ultimate $
Data & Analytics
Conditionals Bundle:

Programming would be pointless without conditional


statements. Fortunately, conditionals in Python are clean The A to Z $
and easy to wrap your head around. It almost feels like Microso Excel
writing pseudocode. That’s how beautiful Python can be. Certification

Boolean Values
StackSkills $
Unlimited:
Like in all other programming languages, comparison
Lifetime Access
operators evaluate to a boolean result: either True or False.
Here are all the comparison operators in Python:

Affiliate Disclosure: By buying the products w


recommend, you help keep the lights on at
>>>x = 10 MakeUseOf. Read more.
>>>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:
PC & MOBILE LIFESTYLE

>>>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:
PC & MOBILE
>>> print("I'm available on that day!") LIFESTYLE

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 PC & MOBILE LIFESTYLE

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 nd 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", "Thursd


>>>for day in weekdays:
>>> print(day)

The for loop starts at the beginning of the weekdays list,


assigns the rst item to the day variable, and the rst loop
through applies only to that variable. When the loop ends,
the next item in the weekdays list gets assigned to day and
PC & MOBILE LIFESTYLE
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 rst 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",
PC & MOBILE LIFESTYLE "Thursd
>>>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. Mastery of dicts is half the battle
in learning Python.

10 Tips for Writing Cleaner & Better


Code
Writing clean code looks easier than it actually is,
but the bene ts are worth it. Here's how you can
start writing cleaner code today.

READ MORE

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
PC & MOBILE LIFESTYLE
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():
PC & MOBILE LIFESTYLE
>>> 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; it only means
that Python doesn’t click as easily for you. If that’s the

You might also like