Professional Documents
Culture Documents
10 Basic Python Examples That Will Help You Learn Fast
10 Basic Python Examples That Will Help You Learn Fast
PROGRAMMING
Joel Lee
1747 articles
Trending Now
Sublime Text 3 Keyboard
Shortcuts Cheat Sheet
by Akshata Shanbhag
and simply want to transition to Python as quickly as possible. If you have The 3 Best Flashcard Apps for
absolutely no programming experience whatsoever, we instead Mac
by James Hirtz
recommend these Python tutorial websites and these online Python
courses.
All basic Python examples were written for Python 3.x. We cannot Latest Giveaways!
guarantee that they’ll work on Python 2.x, but the concepts should be
transferable.
Is the Circle Home Plus Enough
Strings PC & MOBILE LIFESTYLE HARDWARE to Keep Your Family Safe
Online?
by Christian Cawley
Proper string manipulation is something that every Python programmer
Take Better Smartphone
needs to learn. Strings are involved whether you’re doing web
Movies, with the FeiyuTech
development, game development, data analysis, and more. There’s a right Vimble2 Gimbal
way and a wrong way to deal with strings in Python. by Joe Coburn
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: Keep Your Family Safe Online,
with Circle Home Plus
>>>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 How to Stop Irrelevant
PC & MOBILE LIFESTYLE HARDWARE
strings and combines them into one string. Here’s an example: YouTube Recommendations
The de ned string is the separator that goes between each list item, and
Take Better Smartphone
the separator is only inserted between two items (so you won’t have an
Videos, with the FeiyuTech
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 PLAY ALONG: Guess the Movie
Python can be. (SEASON FINALE) | TGTS
Boolean Values
Like in all other programming languages, comparison operators evaluate Latest Deals
to a boolean result: either True or False. Here are all the comparison
Modern $677
operators in Python:
Marketing & $39
Entrepreneurship
>>>x = 10 Bundle
>>>print(x == 10) # True
>>>print(x != 10) # False
Write Copy Like a $200
>>>print(x <> 10) # False, same as != operator
6-Figure a Year $12.99
>>>print(x > 5) # True
Copywriter
>>>print(x < 15) # True
>>>print(x >= 10) # True
>>>print(x <= 10) # True
Icon54: Unlimited $97
Membership $19
The ==, !=, and <> operators above are used to compare the values of two
Ivacy VPN: $1254
variables. If you want to check if two variables point to the same exact
Lifetime $39.99
object, then you’ll need to use the is operator: Subscription +
NAT
>>>a = [1,2,3]
>>>b = [1,2,3]
>>>c = a Affiliate Disclosure: By buying the products we
recommend, you help keep the lights on at
>>>print(a == b) # True MakeUseOf. Read more.
>>>print(a is b) # False
>>>print(a is c)PC#& True
MOBILE LIFESTYLE HARDWARE
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:
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
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
>>>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 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:
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 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
PC & MOBILE LIFESTYLE HARDWARE
range() method just for that purpose:
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:
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:
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:
>Monday is weekday 0
>Tuesday is weekday 1
>Wednesday is weekday 2
>Thursday is weekday 3
>Friday is weekday 4
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.
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 using an index; in a dict, you access the contents by using a
key.
>>>d = {}
>>>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"
>>>}
PC & MOBILE LIFESTYLE HARDWARE
To access a dict value by key:
>>>d["one_key"]
>10
>>>d["another_key"]
>"Whatever you want"
>>>d["one_key"] + d["two_key"]
>35
>>>for key in d:
>>> print(key)
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"
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 case, I recommend that you check out these
tips for learning new programming languages.
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!
your@email.com Submit
Anthony Grant
3 articles
Microsoft Power Query is a useful tool to work with data inside of Trending Now
Microsoft Excel. It comes with a lot of features that make managing Sublime Text 3 Keyboard
data sets simple yet powerful. Shortcuts Cheat Sheet
by Akshata Shanbhag
Power Query is most useful when working with multiple sets of data, The 8 Best Fact-Checking Sites
rather than just one. It acts as a bridge between sets of data and for Finding Unbiased Truth
by Megan Ellis
Microsoft Excel.
Google Maps Now O ers
Detailed Voice Guidance
To prove it, we’ll walk you through a common task where Power by Dave Parrack
Query shines: combining two different data sets into one. 6 Best Soundboard Apps to
Create or Discover Free Sound
Collections
What Is Microso Power Query? by Mihir Patkar
sets, and then combine them into one. The Cutest Speaker You’ve Ever
Seen: Divoom Ditoo
by James Bruce
Power Query is so easy, you don’t even have to open the workbooks
Keep Your Family Safe Online,
with Circle Home Plus
containing data to extract what you need. In “Vehicles.xlsx” navigate
to the “Data” tab of your workbook options.
You will see the “Get Data” option in your toolbar. This option is the
entry to Power Query and will allow you to choose your source of
data.
You want to work with an Excel workbook, so choose the “From File”
options followed by “From Workbook”. Take Better Smartphone
Videos, with the FeiyuTech
Latest Deals
Modern $677
Marketing & $39
Entrepreneurship
Bundle
On the far left clicking on the “Queries” icon will expand the menu
and show the name of the table you are currently working in. Power
Query can take multiple tables at one time and will display them all in
this toolbar.
In order to append two tables together, they both need to be
PC & MOBILE LIFESTYLE HARDWARE
uploaded into Power Query. You have one, let’s grab the other.
Inside of the editor, at the top right corner, is the “New Source”
button. This button allows you to select an additional data source and
add it to the Power Query Editor.
Just like the rst Query, the Navigator will pop up allowing you to
choose your table from the worksheet. Select the worksheet click
“OK”. You will now see both the tables from the cars and trucks
worksheets in the Queries toolbar. Clicking on either table will display
the data contained in that worksheet.
Once you’ve done all the preparation, combining the data tables is
actually quite simple. Click onto the “cars” table, and in the toolbar
select “Append Queries” within the “Combine” section.
The Append window will pop up and prompt for a table that you wish
to join to your selected table. Remember that you are on the “cars”
table and appending the “trucks” table to it. Click on the trucks table
under “Table to append” and choose “OK”
PC & MOBILE LIFESTYLE HARDWARE
Notice that all the car data and truck data are together on the same
table. The data sets are now joined! Also notice the Power Query has
created a new “step” in your list, an “Appended Query” step.
The last thing to do is take this data stored on the Power Query editor
and load it onto your worksheet.
In the top left corner click on “Close & Load” to place the newly
created table onto the Vehicles sheet in table format. Upon clicking,
the following will happen:
The Workbook will appear with the data loaded as an Excel Table
Excel will also open the Workbook Queries menu on the right
PC & MOBILE LIFESTYLE HARDWARE
side of your sheet
You’re ready to work with your brand new table, all without ever
opening up the worksheets.
READ MORE
Explore more about: Data Analysis, Microsoft Excel, Microsoft Power Query.
your@email.com Submit
MAC , PRODUCTIVITY
Shubham Agarwal
145 articles
Luckily, you don’t have to settle for this narrow set of features; there’s a
range of third-party apps to try instead. Here are the best Mac apps for
improved multitasking.
1. Magnet PC & MOBILE LIFESTYLE HARDWARE
Trending Now
Sublime Text 3 Keyboard
Multitasking on Mac with Magnet Shortcuts Cheat Sheet
by Akshata Shanbhag
them into a split-screen view. Unlike the built-in method, you don’t need to The 3 Best Flashcard Apps for
Mac
hold down any keys or create a new workspace. Magnet lets you quickly by James Hirtz
organize windows to evenly t two or even four of them side-by-side.
Plus, you don’t have to manually move them. The window manager lets
you perform these actions through customizable keyboard shortcuts.
Alternatively, you can utilize its menu bar widget. Magnet supports up to
Latest Giveaways!
six external displays and even relocating windows between them using
dedicated keyboard combos. Is the Circle Home Plus Enough
to Keep Your Family Safe
Online?
Magnet is not a free tool, as it costs $1.99. But if you often nd yourself by Christian Cawley
annoyed by macOS’s native multitasking methods, the small cost is well Take Better Smartphone
worth it. Movies, with the FeiyuTech
Vimble2 Gimbal
Download: Magnet ($1.99) by Joe Coburn
Latest Videos
PC & MOBILE LIFESTYLE HARDWARE
This Mac utility does just what its name says. It enhances Mac’s Mission Take Better Smartphone
Control (the apps overview menu) by adding a handful of missing abilities. Videos, with the FeiyuTech
For starters, Mission Control Plus attaches a little X at the top-left corner
of every window in Mission Control. You can click this to instantly hide a
window, but it doesn’t close the app. So when you select the app icon
again from the Dock, you’ll be right back where you were before.
On top of this, the app enables a couple of handy shortcuts. Hide an app
by pressing Cmd + H, or use Cmd + W to close the window. You can also
How to Stop Irrelevant
hide all apps but the one you’re on with Option + Cmd + H.
YouTube Recommendations
Mission Control Plus offers a 10-day trial, after which you’ll need to buy it.
3. Tuck
Tuck is another nifty tool for jumping between several apps on Mac. The
app allows you to temporarily tuck windows to the sides.
All you need to do is move your cursor to the center of any screen edge
PC & MOBILE LIFESTYLE HARDWARE
and Tuck will slide the window off the screen. When you want it back,
repeat the process and it will return immediately.
Instead of using your mouse, you also have the option of direct keyboard
shortcuts. You can hide as many windows as you like and easily cycle Latest Deals
through them. Additionally, Tuck includes a menu bar widget for viewing Keep Your Family Safe Online,
FastestVPN: $600
all tucked windows. with Circle Home
Lifetime Plus $19.99
Subscription (5
Tuck is free as long as you’re OK with a warning popping up every now
Devices)
and then. To get rid of that, you will have to pay a few dollars for a license.
Download: Tuck ($6.99, unlimited free trial available) Ivacy VPN: $1254
Lifetime $39.99
Subscription +
4. Slidepad NAT
web browser within a gesture’s reach. When you move your cursor
towards the right edge’s center, Slidepad pulls out a panel where you can
load and add any web app. There’s no limit to the number of apps you can
Hushed Private $150
set up; Slidepad will maintain their state when you’re working on anything Phone Line: $25
else. Lifetime
5. uBar
uBar Dock Replacement
uBar supercharges your Mac’s Dock, which Apple has barely touched in
years.
Unfortunately, uBar is a bit expensive and will set you back $30. If that’s
too costly for you, have a look at some other macOS Dock alternatives.
6. WindowSwitcher
Its biggest highlight is the resizing options. When you’re in the app
switcher, hover your cursor over an app to reveal a string of window
layouts. Click one to instantly resize the selected window. This lets you
shove it in a corner, bring it to the center, and more.
Multitasking tools are just one part of this puzzle. Next, check out the
range of missing Mac features you can add with third-party apps.
READ MORE
your@email.com Submit
Anthony Grant
3 articles
If you’re looking for a powerful new way to manage data, Microsoft Excel The 8 Best Fact-Checking
Sites for Finding Unbiased
for Windows now has powerful software built in to help: Microsoft Power Truth
Query is a new tool that gives you more control over your spreadsheets by Megan Ellis
The Beginner's Guide to Microso Excel The 3 Best Flashcard Apps for
Mac
Use this beginner’s guide to start your experience with
by James Hirtz
Microsoft Excel. The basic spreadsheet tips here will help you
start learning Excel on your own.
READ MORE
Latest Giveaways!
When you import into Power Query it creates a connection to your data. Is the Circle Home Plus
PC & MOBILE LIFESTYLE HARDWARE Enough to Keep Your Family
Using this connection, you can work with your data in the editor and make
Safe Online?
all your changes before you save to a workbook. by Christian Cawley
To work with Power Query, simply open your workbook, select the Data
tab in the ribbon, and click on Get Data to choose one of many different
places to grab data from. You’re now up and running in seconds with
Power Query.
Note: For programmers, Microsoft did develop a new language for Power Keep Your Family Safe Online,
Query known as “M”. Advanced users can code scripts using “M”, which is with Circle Home Plus
a higher-level concept but provides extra power and value for expert
users.
If you need to modify your data, you can do so right in the editor. Simple
changes are made easy. Some examples you can do are:
Rename columns
Remove errors from your table
PC & MOBILE LIFESTYLE HARDWARE
Once you’re done with changes, simply export the results right onto your
Excel workbook. It’s very easy to work with multiple sheets, without
having to open every single one and make changes.
For example, let’s say you are given a report that shows sales numbers for
the month of July and you need to make changes. You open your table,
make your changes, and save. Simple, right? Then a month later, you are
given a new report for the month of August.
How to Stop Irrelevant
With Excel, you would have to open the workbook and make all those YouTube Recommendations
changes again just to get the same result. Depending on the number of
changes, this can be a lot of time! Power Query solves this problem.
When you connect to a workbook using Power Query and make changes,
those changes are saved as “steps”. Steps are just directions you give
Excel to change data (i.e. “Delete this column” or “Sort this table by color”).
All your steps are saved together, creating a neat little package. You can
Guess the Theme Songs...
apply this set of steps to a new worksheet in one click, instead of making Again! | TGTS S3E14
your changes all over again.
READ MORE
We’ve talked a lot about Excel workbooks, but Power Query can get your
data from a lot of other places. If you want to work with data from a
webpage, you can import just as easily. Power Query can also pull data
from various sources such as:
CSV Files
Text Files
SQL Databases
XML Files
There are many more sources you can use, but don’t get overwhelmed. As
you become more comfortable using Power Query you may have a use for
some, or all, of these uses.
Go further and build up your Microsoft Excel expertise with our articles on
creating graphs from data in Microsoft Excel and analyzing data using
Pivot Tables in Microsoft Excel.
How
PC & to Create Powerful
MOBILE LIFESTYLE Graphs & Charts in
HARDWARE
Microso Excel
A good graph can make the difference between getting your
point across or leaving everyone dozing off. We show you how
to create powerful graphs in Microsoft Excel that will engage
and inform your audience.
READ MORE
your@email.com Submit