10 Simple Css Code Examples You Can Learn In 10 Minutes

Once you’ve started dabbling in HTML, you’ll probably be interested in adding more power to your web pages. CSS is the best way to do that. CSS lets you apply changes across your entire page without having to use lots of inline HTML styles.

We’ll go over how to create an inline stylesheet so you can practice your CSS skills, and then we’ll move onto 10 simple examples that will show you how to do a few basic things. From there, your imagination is the limit!

If you want a slightly more technical introduction, be sure to check out 5 Baby Steps to Learning CSS & Becoming a Kick-Ass CSS Sorcerer.

Inline Stylesheet

Every HTML document contains a <head> tag. That head section is where your inline CSS stylesheet goes. Here’s what it’ll look like:

<head>    All of your CSS declarations.  </head>

Put that at the top of your document, fill it with your CSS, and you’re set to go.

1. Easy Paragraph Formatting

The cool thing about styling with CSS is that you don’t have to specify a style every time you create an element. You can just say “all paragraphs should have this particular styling” and you’re good to go. Here’s an example of how you might do that.

Let’s say you want every paragraph (that’s everything with a <p> HTML tag) on your page to be slightly larger than usual. And dark grey, instead of black. Here’s how you would do that with CSS:

p {    font-size: 120%;    color: dimgray;  }

That’s all there is to it. Now, whenever the browser renders a <p> paragraph, the text will inherit the size (120 percent of normal) and the color (“dimgray”).

If you’re curious as to which plain-text colors you can use, check out this CSS color list from Mozilla.

2. Change Letter Case

Okay, so now that we’ve seen how to make a change to every paragraph, let’s look at how we can be a bit more selective. Let’s create a designation for paragraphs that should be in small caps. Here’s how we’d do that:

p.smallcaps {    font-variant: small-caps;  }

To make a paragraph that’s entirely in small caps, we’ll use a slightly different HTML tag. Here’s what it looks like:

<p class="smallcaps">Your paragraph here.</p>

As you can see, adding a dot and a class name to any specific element in CSS specifies a sub-type of that element defined by a class. You can do this with text, images, links, and just about anything else.

If you want to change the case of a set of text to a specific case, you can use these CSS lines:

text-transform: uppercase;  text-transform: lowercase;  text-transform: capitalize;

The last one capitalizes the first letter of every sentence.

3. Change Link Colors

Let’s try changing the style of something other than a full paragraph. There are four different colors a link can be assigned: its standard color, its visited color, its hover color, and its active color (which it displays while you’re clicking on it). Here’s how we might change those:

a:link {    color: gray;  }    a:visited {    color: green;  }    a:hover {    color: rebeccapurple;  }    a:active {    color: teal;  }

Note that each “a” is followed by a colon, not a dot.

Each one of those declarations changes the color of a link in a specific context. There’s no need to change the class of a link to get it to change color. It will all be determined by the user and the state of the link.

4. Remove Link Underlines

While underlined text pretty clearly indicates a link, it sometimes looks nicer to scrap that underline. This is accomplished with the “text-decoration” attribute. Here’s how we’d get rid of underlines on links:

a {    text-decoration: none;  }

Anything with the link (“a”) tag will remain un-underlined. Want to underline it when the user hovers over it? Just add this below:

a:hover {    text-decoration: underline;  }

You could also add this text-decoration to active links to make sure the underline doesn’t disappear when the link is clicked.

5. Make a Link Button

If you want to attract more attention to your link, using a link button is a great way to go about it. This one requires a few more lines, but we’ll go over them each individually:

a:link, a:visited, a:hover, a:active {    background-color: green;    color: white;    padding: 10px 25px;    text-align: center;    text-decoration: none;    display: inline-block;  }

By including all four link states, we ensure that the button doesn’t disappear when a user hovers or clicks on it. You can also set different parameters for hover and active links, like changing the button or text color, to add a bit of pop.

The background color is set with background-color, and text color with color. Padding defines the size of box — the text is padded by 10px vertically and 25px horizontally. Text-align ensures that the text is displayed in the center of the button, instead of off to one side. Text-decoration, as we saw in the last example, removes the underline.

makeuseof link button

“display: inline-block” is a bit more complicated. In short, it lets you set the height and width of the object, and ensures that it starts a new line when it’s inserted.

6. Create a Text Box

A plain paragraph isn’t very exciting. If you want to highlight your call to action or another element on your page, you might want to throw a border around it. Here’s how to do that with a string of text:

p.important {    border-style: solid;    border-width: 5px;    border-color: purple;  }

This one is pretty straightforward. It creates a solid purple border, 5 pixels wide, around any important-class paragraph. To make a paragraph inherit these properties, just declare it like this:

<p class="important">Your important paragraph here.</p>

This will work regardless of the size of your paragraph; a single line will get a border the width of the page, one line high, and a longer paragraph will be surrounded by a larger border.

There are many different border styles you can apply; instead of “solid,” try “dotted” or “double.” And the width can be “thin,” “medium,” or “thick.” You can even define the thickness of each border individually, like this:

border-width: 5px 8px 3px 9px;

That results in a top border of 5 pixels, a right border of 8, a bottom of 3, and a left border size of 9 pixels.

7. Center-Align Elements

For a very common task, this is a surprisingly unintuitive thing to do with CSS. Once you’ve done it a few times though, it becomes much easier. There are a couple different ways to center things.

For a block element (usually an image), we’ll use the margin attribute:

.center {    display: block;    margin: auto;  }

This ensures that the element is displayed as a block, and that the margin on each side is set automatically (which makes them equal). If you want to center all of the images on a given page, you can even add “margin: auto” to the img tag:

img {    margin: auto;  }

To learn why it works this way, check out the CSS box model explanation at W3C. Here’s a short, graphical version:

css box model

But what if we want to center text? CSS has a specific method of doing that:

.centertext {    text-align: center;  }

If we want to use the “centertext” class to center the text in a given paragraph, all we need to do is add that class to the <p> tag:

<p class="centertext">This text will be centered.</p>

Remembering those different steps, however, is another matter. You might want to bookmark this page.

8. Adjusting Padding

The padding of an element specifies how much space should be on each side. For example, if you add 25 pixels of padding to the bottom of an image, the following text will be pushed 25 pixels down. Many elements can have padding, but we’ll use an image for an example here.

Let’s say you want every image to have 20 pixels of padding on the left and right sides, and 40 pixels on the top and bottom. There are a number of ways you can do this. The most basic:

img {    padding-top: 40px;    padding-right: 25px;    padding-bottom: 40px;    padding-left: 25px;  }

There’s a short hand we can use to present all of this information:

img {    padding: 40px 25px 40px 25px;  }

This sets the top, right, bottom, and left paddings to the right number. But we can make it even shorter:

img {    padding: 40px 25px  }

When you use only two values, the first value is set for the top and bottom, while the second will be left and right.

9. Highlight Table Rows

CSS can do a lot to make your tables look really nice. Adding colors, adjusting borders, and making your table responsive to mobile screens are all easy. We’ll look at just one cool effect here: highlighting table rows when you mouse over them.

Here’s the code you’ll need for that:

tr:hover {    background-color: #ddd;  }

Now whenever you mouse over a table cell, that row will change color. To see some of the other cool things you can do, check out the W3C page on fancy CSS tables.

fancy css table

10. Shifting Images Between Transparent and Opaque

CSS can help you do cool things with images, too. For example, it can display images at less than full opacity (they appear slightly “whited out”) and bring them to full opacity when you mouse over them. Here’s how we’ll do that:

img {    opacity: 0.5;    filter: alpha(opacity=50);  }

The “filter” attribute does the same thing as “opacity,” but Internet Explorer 8 and earlier don’t recognize the opacity measurement, so it’s a good idea to include it.

Now that the images are slightly transparent, we’ll bring them to fully opaque on a mouseover:

img:hover {    opacity: 1.0;    filter: alpha(opacity=100);  }

Become a CSS Master

With these CSS code examples, you should have a much better idea of how CSS works. Once you’ve gone through all of them, you’ll notice a number of patterns that you can apply to further CSS code. And that’s when you know you’ve really started becoming a CSS master.

And if all of this sounds too complicated, remember that you just grab some CSS templates and modify them.

What do you do with CSS? Which examples would you like to see in the future? Share your thoughts in the comments below!

A Quick Introduction To Java 8 Lambdas

If you’re a Java programmer and you’re interested in learning more about Java 8 lambdas, in this article we’re going to take a closer look at lambda syntax and usage.

A lambda expression in Java is a concise way to express a method of a class in an expression. It has a list of parameters and a body. The body can be a single expression or a block. It is commonly used where an implementation of an interface is required. This need usually arises when an interface is required as the argument to invoke a method.

Some Simple Lambda Expressions

Let us look at some simple examples of lambda expressions.

The following is a lambda expression which accepts two numbers x and y and computes the sum.

(int x,int y) -> x + y;  

Drop the parameter types for a more concise representation:

(x, y) -> x + y;  

Define a function which accepts no parameters:

() -> 404;  

The following is valid too, which accepts no parameters and returns nothing:

() -> {}  

No need for parantheses enclosing parameters for a single parameter:

x -> x + 1  

More complex code blocks are also possible. The following lambda accepts a single line parameter and does some processing on it. Note that the type of the parameter is inferred from the surrounding context:

line -> {  String[] x = pattern.split(line);  return new Player(Integer.parseInt(x[0]),                    x[1],                    x[2],                    x[3],                    Integer.parseInt(x[4]));  }  

Clean and Concise Coding

Using lambda expressions helps make your code clean and concise. To assist in this, Java 8 classes make extensive use of lambdas.

Looping Over a List or a Set

Collection classes such as List, Set, Queue, and such implement the Iterable interface which makes looping over the elements much easier.

Declare a list of names.

List<String> names = Arrays.asList("Joe", "Jack", "James", "Albert");  

Loop over the list without lambda:

for (String name : names) {      System.out.println(name);  }  

Using lambda, the above loop can be written as:

names.forEach(name -> System.out.println(name));  

With Java 8 method references, the above can be written even more concisely as:

names.forEach(System.out::println);  

Looping Over a Map

A Map is a mapping of keys to values. Looping over a map involves looping over each of the (key, value) mapping. Compare how you can use lambdas for this situtation.

First define a map:

Map<String,Integer> map = new HashMap<>();  map.put("Atlanta, Georgia", 110);  map.put("Austin, Texas", 115);  map.put("Baltimore, Maryland", 105);  map.put("Birmingham, Alabama", 99);  map.put("Boston, Massachusetts", 98);  

You can loop over this map in the traditional way:

for (Map.Entry<String,Integer> e : map.entrySet()) {      System.out.println(e.getKey() + " => " + e.getValue());  }  

Here is how you can do the same thing in a quick and concise way using lambdas:

map.forEach((k, v) -> System.out.println(k + " => " + v));  

Functional Interfaces

What is the return type of a lambda expression? In other words, what is the type of X in the following statement?

X x = a -> a + 1;  

The return type of a lambda expression is a functional interface – an interface with a single abstract method. You can assign a lambda expression to an interface with a compatible abstract method. Some examples below.

Creating a Multi-Threaded Task

Consider creating a task for execution in a separate thread — you are required to define the task as a Runnable interface and implement the run() method. Here Runnable is a functional interface.

class MyTask implements Runnable {     ...     public void run() {       // implement your task here       System.out.println("Running in a separate thread now.");     }     ...  }  

You can then create an instance of the MyTask class and use it to start a new thread of execution.

MyTask task = new MyTask();  Thread thread = new Thread(task);  thread.start();  

Using a lambda, the process of creating a Runnable becomes much easier. The task definition above can be rewritten as:

Runnable task = () -> System.out.println("Running in a separate thread now.");  

Or even:

Thread thread = new Thread(() -> System.out.println("Running in a separate thread now."));  thread.start();  

Comparison Using a Comparator

The Comparator is a functional interface for comparing objects of a given type. It defines a single abstract method called compare() which can be defined using a lambda expression.

Here is a lambda expression creating a Comparator used to compare strings case-insensitively.

Comparator<String> cmp = (x, y) -> x.compareToIgnoreCase(y);  

Once an instance of the Comparator functional interface has been created, it can be re-used as required.

Here, we sort a list of strings in ascending order.

List<String> names = Arrays.asList("Joe", "Jack", "James", "Albert");  Collections.sort(names, cmp);  names.forEach(System.out::println);  // prints  Albert  Jack  James  Joe  

The list above is sorted in place. We can now search it using the binarySearch() method as follows:

System.out.println("search(Joe):" + Collections.binarySearch(names, "Joe", cmp));  # prints  search(Joe):3  

Computing maximum and minimum from a list is also easy using lambdas.

Define some data:

List<Integer> temps = Arrays.asList(110, 115, 105, 99, 98, 54, 109, 84, 81, 66, 72, 135, 115, 75, 82, 90, 88);  

Use a lambda expression to define the comparator:

Comparator<Integer> cmpTemp = (x, y) -> Integer.compare(x, y);  

And print the maximum and minimum:

System.out.println("------ Max/Min ------");  System.out.println(Collections.max(temps, cmpTemp) + "/" + Collections.min(temps, cmpTemp));  

Use in GUI Programming

Lambda expressions are also extremely useful in GUI programming to implement event handlers. Here is an example of using a button click handler.

JButton button = new JButton("Click Me");  button.addActionListener(e -> System.out.println("Button clicked!"));  

And that was a quick look at using lambdas in Java 8.

Have lambdas made your life easier since Java 8? Please explain in the comments below.

How To Auto-generate A List Of Installed Programs On Windows

You probably have several dozen pieces of software installed on your computer. Aside from tools you use every day like your web browser, it’s easy to forget about programs you don’t use often. This can cause problems whenever you’re resetting your computer or buying a new machine, as you won’t remember which software you need to reinstall.

Thankfully, Windows makes it easy to generate a list of all the software you have installed. It’s made possible by PowerShell, but don’t be scared if you’ve never used it before: you only need a few easy commands.

Go ahead and open up a PowerShell window by typing Powershell into the Start Menu. Once there, paste in this line to generate a list of all your software, including its publisher and the date you installed it:

Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize  

Of course, this list alone doesn’t do you much good. To send this information to a text file, append the line below, changing the file path to your username:

> C:\Users\USERNAME\Desktop\InstalledProgramsList.txt  

Altogether, using the command below (make sure you change USERNAME to your own Windows username) will generate a list of your installed software and export it to a file on your desktop called InstalledProgramsList.txt:

Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize > C:\Users\USERNAME\Desktop\InstalledProgramsList.txt  

To easily find out the different software you have installed on different systems, run this command on two machines and paste the resulting text into a text comparison website.

Once you’re done, don’t forget to save this file to a flash drive, cloud storage, or other external media for safekeeping. If you wipe your computer, you’ll erase this file along with it!

Interested in what PowerShell can do as opposed to the Command Prompt? Have a look at their differences.

Do you find it useful to keep a list of installed software? Let us know if you’ll use this command soon down in the comments!

Image Credit: racorn via Shutterstock.com

Automate File Encryption In Windows With This Powershell Script

File encryption and file decryption can be a bit of work. However, using a PowerShell extension, you can slim down the process to a one-line command. To do this, we need to install Gpg4win and a Powershell module. Using scripts, we can automate the file encryption and decryption process.

Let’s take a look at how to encrypt files in Windows 10 automatically with a script.

The Prerequisites: Installs, Modules, and Certs

You’ll want to have the GPG4Win tools installed and configured before you begin. Head over to the project page and download the latest version. (If you need some guidance installing and configuring the tool, use this PDF guide.) You are going to use the symmetric cipher function of GPG4Win in this module.

This Powershell module handles file encryption using a passphrase rather than a keypair. The strength of your encryption depends on the strength of your passphrase. You should make sure to choose something complex. Generate it using LastPass or another password manager. Finally, complete the installation and move on to the Powershell Module.

automate file encryption windows powershell

Powershell Modules are packaged collections of functions. They use the PSM1 file format. You save these files in your profile’s Modules directory. Then, add the Module to your session/script using Import-Module.

All the module’s cmdlets are available. As you advance your Powershell skills, you can even create your own modules. To install the file Encryption module, download it from TechNet.

Next, you need to copy it into one of the Modules directories. If you want to install it for just yourself, copy it into the PowershellModules in your user folder. Copy this into Explorer for a shortcut:

%UserProfile%\Documents\WindowsPowerShell\Modules

If you want to install the module for all users, use the Program Files\Windows PowerShell\Modules folder. Paste this into Explorer for a shortcut:

%ProgramFiles%\Windows PowerShell\Modules

Create a new folder named GNUPG in the Modules directory and paste the PSM1 file into it.

automate file encryption windows powershell

You’ll need to import the module each time using: Import-Module GnuPG. However, you may need to adjust your Execution policy to Unrestricted. Do this by running the cmdlet Set-ExecutionPolicy RemoteSigned.

automate file encryption windows powershell

Since you downloaded this Module, you still need to mark it as a local file. Right-click the file and select, Properties. Next, in the dialog, click Unblock. Confirm your action in the UAC dialog, and you’re set to use the module.

Working With the Cmdlets

Skip the first Cmdlet, which is used to install GPG4Win. You should have already completed this step. If not, you can use this cmdlet to install and configure the program. The cmdlet downloads it to a folder you choose and runs the installer. The other two are complementary: Add-Encryption and Remove-Encryption. Both of these take three parameters.

automate file encryption windows powershell

The first is a directory, passed as -FolderPath. The module will step through every file in a directory to apply or remove file encryption. You wouldn’t want to point it at your Documents folder. You would want to create a couple of subfolders for working with this script. If you look at the source code for the Module, it’s using Get-ChildItem to get everything in the directory. The decryption function limits the search to files ending in .GPG.

automate file encryption windows powershell

The next parameter is the passphrase used for the file encryption: -Password. Make sure that this is complex, as it is the protection for your file. The function steps through each of the files with a ForEach loop. The file and passphrase combine as arguments in Start-Process for GPG4Win.

The final parameter, -GPGPath is not mandatory. It is set to the default install location for GPG4Win. If you have it on another drive, you can update it using this parameter. It changes the target for the Start-Process.

Writing the Script

Now it’s time to automate the process. This script will encrypt the files in a directory. Move the decrypted files to a new directory. The script will delete the original file.

You start your script with some prep. First, import the module using Import-Module GnuPG. You need to set up a couple of variables. The first variable $EncryptionTarget is your target folder. (In the example, an environment variable is used to point to the current user’s document folder.) Set the second variable as your passphrase. This step makes it easier to change it later.

Import-Module GnuPG  $EncryptionTarget = "$($env:USERPROFILE)\Documents\Files-ToEncrypt"  $Passphrase = "MakeAVeryLongSecurePhrase"  Add-Encryption $EncryptionTarget -Password $Passphrase  Start-Sleep -Seconds 60  $EcnryptedFiles = Get-ChildItem $EncryptionTarget | Where-Object $_.Name -like "*.gpg"  foreach ($gpg in $EcnryptedFiles){    Move-Item -Path $gpg.FullName -Destination "$($env:USERPROFILE)\Documents\$($gpg.Name)"  }  $UnEncryptedFiles = Get-ChildItem $EncryptionTarget | Where-Object $_.Name -notlike "*.gpg"  foreach ($nongpg in $UnEcnryptedFiles){    Remove-Item -Path $nongpg.FullName -Confirm $false  }  

Those variables go to Add-Encryption as parameters. You use a Start-Sleep to give the file encryption time to complete. The example uses three minutes. You can alter it based on the size and number of files you are working with.

You get the .GPG files by combining Get-ChildItem with Where-Object. Using a ForEach loop, each one of those files is copied to a new directory. We repeat these steps, but switching the -like for -notlike. A second ForEach loop cleans up the original files.

Setting the Recurring Task

You have the script, now you need to create a scheduled task. Open Task Scheduler and click Create Task.

automate file encryption windows powershell

Name it something like AutoEncrypt. If you only want the task to run when you are logged in, just leave the default. If you set it to run regardless, it can only access local directories. However, if your destination is on a remote machine, you need to store your password for the job to run. You may want to set up a secondary account to protect the security of your main account.

automate file encryption windows powershell

Click on the Triggers tab and setting up the conditions. Next, click on New to pull up the scheduling window. You can leave the trigger settings set to the default. Click the checkbox next to Repeat Task Every and set it to 5 Minutes. You can choose to run this less often if your need isn’t urgent. In the dropdown next to for the duration of: select Indefinitely. Click OK to go back to the Create Task window.

automate file encryption windows powershell

On the Actions tab, click New. In the popup, put the path to Powershell in the Program box:

%SystemRoot%/system32/Windows PowerShell/v1.0/powershell.exe

In the arguments box put ./ and the path to your script. Click OK twice and your script is set to run as a Scheduled task.

Some Security Concerns and Other Ideas

Be aware that you have the passcode to decrypt the files on the same machine where you are storing them. These types of file encryptions are more for encrypting a file before you send it, or store it on another machine. (If you want a locked down file system, use Full Disk Encryption.) You can set up a similar task to do the same with decryption.

Do you have a project that needs a quick and dirty file encryption script? Let us know in the comments.

Python Dictionary: How You Can Use It To Write Better Code

A python dictionary is a data structure similar to an associative array found in other programming languages. An array or a list indexes elements by position. A dictionary, on the other hand, indexes elements by keys which can be strings. Think of a dictionary as unordered sets of key-value pairs.

a python dictionary key-value pairs

In this article, we introduce you to working with the python dictionary.

Creating a Dictionary

There are several ways of creating a python dictionary. The simplest uses brace initialization, with a syntax reminiscent of JSON.

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  

You can use numbers too as the keys. However, be careful using floating point numbers as keys, since the computer stores these as approximations.

rain_percent = { 1980: '17%', 1981: '15%', 1982: '10%'}  print rain_percent  print rain_percent[1980]  # prints  {1980: '17%', 1981: '15%', 1982: '10%'}  17%  

Specifying Key-Value Pairs

You can also create and initialize a dictionary using name value pairs as keyword arguments to the dict() constructor.

population = dict(California=37253956, Colorado=5029196, Connecticut=3574097, Delaware=897934)  print population  # prints  {'Connecticut': 3574097, 'Delaware': 897934, 'California': 37253956, 'Colorado': 5029196}  

Array of Key-Value Tuples

Yet another way of creating a dictionary is to use an array of key-value tuples. Here is the same example as above.

pairs = [('California', 37253956), ('Colorado', 5029196), ('Connecticut', 3574097), ('Delaware', 897934)]  population = dict(pairs)  print population  # prints  {'Connecticut': 3574097, 'Delaware': 897934, 'California': 37253956, 'Colorado': 5029196}  

Dict Comprehension

Dict comprehension provides a cool syntax to initialize a dict if you can compute the values based on the keys. The following initializes a dict of numbers and square values for a range of numbers.

print {x: x**2 for x in xrange(10, 20)}  # prints  {10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225, 16: 256, 17: 289, 18: 324, 19: 361}  

How does it work? The latter part (for x in xrange(10, 20)) returns a range of numbers in the specified range. The dict comprehension part ({x: x**2 ..}) loops over this range and initializes the dictionary.

Working With a Python Dictionary

What can you do with dictionaries once you have created them? Well, you can access elements, update values, delete elements, etc.

Accessing Python Dictionary Elements

Access an element of a dict using the key within brackets, just like you would an array or a list.

print population['Delaware']  # prints  897934  

If the key is a number, you don’t need the quotes. The expression then appears to look like a list or array indexing.

print rain_percent[1980]  # prints  17%  

The type of the key when accessing it must match what is stored in the Python dictionary. The following causes an error since the stored keys are numbers while the access key is a string.

x = '1980'  print rain_percent[x]  # results in        1 x = '1980'  ----> 2 print rain_percent[x]    KeyError: '1980'  

Accessing a non-existent key is an error.

rain_percent = { 1980: '17%', 1981: '15%', 1982: '10%'}  print rain_percent[1983]  # prints        1 rain_percent = { 1980: '17%', 1981: '15%', 1982: '10%'}  ----> 2 print rain_percent[1983]    KeyError: 1983  

To access a key and provide a default value if the mapping does not exist, use the get() method with default value as the second argument.

print rain_percent.get(1985, '0%')  # prints  0%  

Checking for Existence

What if you want to check for the presence of a key without actually attempting to access it (and possibly encountering a KeyError as above)? You can use the in keyword in the form key in dct which returns a boolean.

print 1980 in rain_percent  print '1980' in rain_percent  # prints  True  False  

Reverse the condition (i.e. ensure that the key is not present in the Python dictionary) using the form key not in dct. This is equivalent to the standard python negation not key in dct.

print 1980 not in rain_percent  print 1985 not in rain_percent  # prints  False  True  

Modifying Elements

Change the value by assigning to the required key.

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  users['age'] = 29  print users  # prints  {'lastname': 'Smith', 'age': 29, 'firstname': 'John'}  

Use the same syntax to add a new mapping to the Python dictionary.

users['dob'] = '15-sep-1971'  print users  # prints  {'dob': '15-sep-1971', 'lastname': 'Smith', 'age': 29, 'firstname': 'John'}  

Update multiple elements of a dictionary in one shot using the update() method.

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  users.update({'age': 29, 'dob': '15-sep-1971'})  print users  # prints  {'dob': '15-sep-1971', 'lastname': 'Smith', 'age': 29, 'firstname': 'John'}  

Set a default value for a key using setdefault(). This method sets the value for the key if the mapping does not exist. It returns the current value.

# does not change current value  print users.setdefault('firstname', 'Jane')  # prints  John    # sets value  print users.setdefault('city', 'NY')  # prints  NY    # Final value  print users  # prints  {'lastname': 'Smith', 'age': 27, 'firstname': 'John', 'city': 'NY'}  

Deleting elements

Delete mappings in the dictionary by using the del operator. This operator does not return anything.

You will encounter a KeyError if the key does not exist in the dictionary.

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  del users['age']  print users  # prints  {'lastname': 'Smith', 'firstname': 'John'}  

Use the pop() method instead, when you want the deleted value back.

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  print users.pop('age')  print users  # prints  27  {'lastname': 'Smith', 'firstname': 'John'}  

What if you want to delete a key if it exists, without causing an error if it doesn’t? You can use pop() and specify None for second argument as follows:

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  users.pop('foo', None)  print users  # prints  {'lastname': 'Smith', 'age': 27, 'firstname': 'John'}  

And here is a one-liner to delete a bunch of keys from a dictionary without causing an error on non-existent keys.

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27, 'dob': '15-sep-1971'}  map(lambda x : users.pop(x, None),['age', 'foo', 'dob'])  print users  

Want to delete all keys from a dictionary? Use the clear() method.

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  users.clear()  print users  # prints  {}  

Looping With Python Dictionaries

Python provides many methods for looping over the entries of a dictionary. Pick one to suit your need.

Looping Over Keys

  • The simplest method for processing keys (and possibly values) in sequence uses a loop of the form:
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  for k in users:    print k, '=>', users[k]  # prints  lastname => Smith  age => 27  firstname => John  
  • Using the method iterkeys() works exactly the same as above. Take your pick as to which form you want to use.
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  for k in users.iterkeys():    print k, '=>', users[k]  # prints  lastname => Smith  age => 27  firstname => John  
  • A third method to retrieve and process keys in a loop involves using the built-in function iter().
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  for k in iter(users):    print k, '=>', users[k]  # prints  lastname => Smith  age => 27  firstname => John  
  • When you need the index of the key being processed, use the enumerate() built-in function as shown.
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  for index, key in enumerate(users):    print index, key, '=>', users[k]  # prints  0 lastname => John  1 age => John  2 firstname => John  

Looping Over Key-Value Pairs

  • When you want to retrieve each key-value pair with a single call, use iteritems().
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  for k, v in users.iteritems():    print k, '=>', v  # prints  lastname => Smith  age => 27  firstname => John  

Iterating Over Values

  • The method itervalues() can be used to iterate over all the values in the dictionary. Though this method looks similar to a loop using values(), it is more efficient since it does not extract all the values at once.
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  for value in users.itervalues():    print value  # prints  Smith  27  John  

Extracting Arrays

The following methods describe extracting various Python dictionary information in an array form. The resulting array can be looped over using normal python constructs. However, keep in mind that the returned array can be large depending on the size of the dictionary. So it might be more expensive (memory-wise) to process these arrays than using the iterator methods above.

One case where it is acceptable to work with these arrays is when you need to delete items from the dictionary as you encounter undesirable elements. Working with an iterator while modifying the dictionary may cause a RuntimeError.

  • The method items() returns an array of key-value tuples. You can iterate over these key-value pairs as shown:
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  for k, v in users.items():    print k, '=>', v  # prints  lastname => Smith  age => 27  firstname => John  
  • Retrieve all the keys in the dictionary using the method keys().
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}  print users.keys()  # prints  ['lastname', 'age', 'firstname']  

    Use the returned array to loop over the keys.

    for k in users.keys():    print k, '=>', users[k]  # prints  lastname => Smith  age => 27  firstname => John  
  • In a similar way, use the method values() to retrieve all the values in the dictionary.
    for value in users.values():    print value  # prints  Smith  27  John  

How Do You Use Python Dictionaries?

We have tried to cover the most common use cases for python dictionaries in this article. Make sure to check out all of our other Python articles for even more Python tipsIf you have other use cases you feel should be included, please let us know in the comments below!

Image Credits: viper345/Shutterstock

The Essential HTML FAQ You Should Bookmark

Advertisement

HTML has been around for a long time now, so it’s about time you learned the basics. What is it, how it works, and how to write some common elements in HTML.

Before starting, make sure your read our guide to free online HTML editors


5 Best Free Online HTML Editors to Test Your Code




5 Best Free Online HTML Editors to Test Your Code

For times when you just want to fiddle around with a small snippet of HTML so you can tweak it to your liking, an online HTML editor will serve you better.
Read More

and the best websites for quality HTML examples


8 Best Websites For Quality HTML Coding Examples




8 Best Websites For Quality HTML Coding Examples

There are some awesome websites that offer well-designed and useful HTML coding examples and tutorials. Here are eight of our favorites.
Read More

.

What Is HTML?

HTML is the language used to construct web pages. HTML stands for Hypertext Markup Language and is simple a set of instructions for your web browser. Using these instructions, your browser displays what a web page should look like.

It’s important to understand that it’s a markup language, not a programming language. Programming languages allow you to solve problems, such as math equations, manipulating data, or moving a video game character.

You’re unable to write any logic in HTML. It is only concerned with layout.

What Does HTML Look Like?

HTML consists of several elements known as “tags”. Tags are instructions for styling a specific part of your web page. Going back to construction, HTML is the plans, and tags are specific features such as windows or doors.

Here’s what a very basic web page looks like in HTML:

<html>
  <head>
    <title>MUO Website</title>
  </head>
  <body>


  </body>
</html>

Tags in HTML are pre-defined, and specify common features like images, links to other webpages, buttons, and more.

The vast majority of tags have to be open and closed. This simply defines some feature, with text, images, or other tags inside it, and then ends the definition. Thinking back to houses, opening the tag is like saying “start the window here”, and closing the tag is like saying “here’s where the window ends”.

HTML tags won’t actually show up on your website. Your browser follows the instruction, but never shows it to any visitors. It’s not secret, however. Anyone can look at your HTML once you publish your web pages.

While there is a large number of different HTML tags, you don’t have to learn them all before you can code a website. Today you’ll learn how to write some common tags, and what they can be used for.

What Are HTML Tag Attributes?

One last thing to know about tags is attributes. Attributes define special features of tags. If tags are windows and doors, then attributes specify specific building details. This could be the width and height of the frame, whether the window opens, or if the door has a lock.

Attributes are included inside the opening tag, like this:

<p width="123" height="567"></p>

You can’t just make up your own tags or attributes. Attributes and tags are pre-defined by the World Wide Web Consortium (W3C).

What Is HTML5?

HTML5 is the latest version of HTML. It contains several new tags, attributes, and features.

As HTML is a set of instructions, different web browsers sometimes interpret it differently. One browser might decide that windows and doors should be painted black unless you say otherwise.

everything know about html

While browsers have finally started to become quite consistent with each other, you can still get caught out sometimes with very new features. Perhaps Google Chrome has implemented a new tag, but Microsoft’s internet Explorer has not yet.

For the most part, your web pages will look the same across all the major browsers, but it’s still worth having a quick test before your publish anything, especially if you’re using newer tags, which may not be supported by all browsers yet.

If you’d like to know more about HTML5, then take a look at our HTML5 getting started guide


Get Started With HTML5




Get Started With HTML5

You’ve heard of HTML5. Everybody is using it. It’s being heralded as the savior of the Internet, allowing people to create rich, engaging web pages without resorting to using Flash and Shockwave.
Read More

.

How to Comment Out HTML

Like many other languages, markup or programming, HTML has the ability to “comment out” blocks of markup. A comment is something that is ignored by the browser. This may be a note to remind yourself about what this particular piece of your website does.

By commenting out markup, you are instructing the browser to ignore one or more tags. This may be useful to remove functionality, or to hide a piece of your website without deleting the code.

When a web browser sees a comment, it understands it as “don’t use these instructions until I say otherwise”. Comments consist of an “opening” comment, and a “closing” comment—just like tags.

Here’s an example:

<!-- Don't forget to add the XYZ here! -->
<p width="123" height="567"></p>

Commenting out code is done exactly the same way:

<!-- <p width="123" height="567"></p> -->

Rather than a message, put your markup between the comment tags.

How to Insert Images in HTML

Inserting images into your HTML is done with the image tag:

<img src="MUO_logo.jpg" alt="MakeUseOf Logo">

Notice how the tag name is called img, and there are two attributes. The src attribute specifies where to find the image, and the alt tag is an alternative text description, in case the image cannot be loaded for any reason.

The image tag does not need closing, unlike most other tags.

How to Change Font in HTML

Fonts can be changed using the font tag and the face attribute:

<font face="arial">MUO Arial Text</font>

everything know about html

Font size can be easily changed using the size attribute:

<font size="12">MUO Big Text</font>

everything know about html

If you’d like to change the font color, this can be easily done with the color attribute:

<font color="red">MUO Red Text</font>

everything know about html

These attributes are unique to the font tag. If you wish to use another tag, you can nest tags, by placing one inside the other:

<p><font color="red">MUO Red Text</font></p>

How to Add a Link in HTML

Links can be added using the a tag:

<a href="">MakeUseOf.com</a>

The href attribute is the destination of your link.

How to Make a Table in HTML

HTML tables involve nesting several different tags. You’ll need to start with a table tag:

<table>
  
</table>

Now add some rows using the tr tag:

<table>
  <tr>
    
  </tr>
  <tr>
    
  </tr>
  <tr>
    
  </tr>
</table>

Finally, use the td tag to create your table cells, which will also create the columns:

<table>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

It’s possible to go overboard and go quite wild with your table layout, but it’s usually best to keep things simple if possible. In the past, tables were used to structure a web page, but this practice is dated and looks terrible. Keep tables simply for relaying data to the reader.

Using CSS With HTML

These examples have covered the basics, but if you want to get really creative, you’ll need to use CSS. Cascading Style Sheets allow you much greater control over your website design, and allow you to re-use quite a lot of code between different parts of your website.

While we have tutorials on learning CSS


5 Baby Steps to Learning CSS and Becoming a Kick-Ass CSS Sorcerer




5 Baby Steps to Learning CSS and Becoming a Kick-Ass CSS Sorcerer

CSS is the single most important change webpages have seen in the last decade, and it paved the way for the separation of style and content. In the modern way, XHTML defines the semantic structure…
Read More

and quick CSS examples


10 Simple CSS Code Examples You Can Learn in 10 Minutes




10 Simple CSS Code Examples You Can Learn in 10 Minutes

We’ll go over how to create an inline stylesheet so you can practice your CSS skills. Then we’ll move onto 10 basic CSS examples. From there, your imagination is the limit!
Read More

, there’s still some setup you can do in HTML.

If you’d like to write CSS alongside your HTML, you can use the style attribute. This attribute simply applies the CSS to the tag it’s used on:

<p ></p>

While this way works well, you’ll find it hard work to maintain if you have a lot of markup which requires similar styling.

The better way is to use the style tag, placed inside the head tag. Here you can define CSS for your whole page:

<html>
  <head>
    <style type="text/css">
      MANY CSS RULES
    </style>
  </head>
</html>

The style tag has an attribute of text/css. This is required to let your browser know the exact style to expect in the tag.

The third and final way of using CSS is through an external file, using the link tag. This links your HTML to CSS stored in its own file, which is great if you have a large amount of it:

<link rel="stylesheet" type="text/css" href="muostyle.css">

There are several attributes in use here. The rel attribute declares your link as a stylesheet. The type of “text/css” is once again defined in the type attribute, and the href attribute is where to find the external file.

How Do You Make a Website With HTML?

As you’ve seen, HTML really isn’t that bad, is it? Using a few simple tags and attributes, you can quickly assemble a web page, even if you’ve never written HTML before!

If you’re looking to write a complete website, then make sure you take a look at our beginner’s guide to making a website


How to Make a Website: For Beginners




How to Make a Website: For Beginners

Today I’ll be guiding you through the process of making a complete website from scratch. Don’t worry if this sounds difficult. I’ll guide you through it every step of the way.
Read More

.

7 Best Coding Apps For Kids To Learn Programming

Young children learn languages better. While older brains may be more efficient, younger brains are increasingly malleable. Like spoken languages, it’s an excellent idea for kids to foray into programming languages. BBC’s micro:bit hardware teaches kids coding and the Kano is a DIY computer for kids to learn programming.

But just as old and young brains differ in retention, so too do learning methods. Coding apps offer ample opportunities to teach children programming. It’s a fun, controlled environment. Rather than send children to a coding boot camp, check out these five best coding apps for kids to learn programming.

1. Kodable (Free/Paid, Web/iOS)

Kodable-screenshot
Image Credit: iTunes

Kodable’s tagline reads “programming for kids, made with love.” Its easy lessons target kindergarten to fifth graders. While the K-3 curriculum is mostly foundational, fourth and fifth grade learning shifts to a focused set of topics. Kodable adheres to programming standards which teach JavaScript. Since JavaScript is an excellent language for beginners, the fundamentals Kodable enforces foster fantastic programming skills.

Plus, progression through lessons remains fun. Games arrive as a set of challenges like navigating a maze. But Kodable doesn’t keep programming concepts too simple. Rather, Kodable even includes notions including looping and branching. Largely Kodable presents if/then decisions to initially present the concept of programming. Moreover, Kodable makes learning JavaScript fun by using gamification. Overall, Kodable is a solid entry-level means for kids to learn programming.

Why it’s great: Kodable is free and web-based, and introduces basic programming concepts like looping and branching.

2. Daisy the Dinosaur (Free, iOS)

Fact: dinosaurs are awesome. As a kid, my favorite chicken nuggets were the dinosaur-shaped ones. Adding dinosaurs is a recipe for excellence. Further proving this point, Daisy the Dino is one of the best coding apps for kids. Mini-games teach children programming basics. For instance, a loop-deloop challenge encourages kids to use word commands to make Daisy perform various moves. But there’s a catch: you’re limited to using the spin command once. A hint suggests nesting the spin command inside the repeat five command.

Daisy the Dinosaur isn’t just one of the best coding apps for kids to learn programming because there’s a dinosaur. Although the dino protagonist certainly helps, it’s more the spectacular focus on coding and its challenges. Furthermore, Daisy the Dinosaur doesn’t seem tech-oriented. On the surface it’s a simple word and puzzle solving game. While Daisy the Dinosaur might be a bit short, it’s free and fundamentally sound.

Why it’s great: Daisy the Dinosaur is free, simple, and appeals to even non-techie kids.

3. Think and Learn Code-a-Pillar (Paid, iOS/Android)

Code-a-Pillar
Image Source: Amazon

The Think and Learn Code-a-Pillar by Fisher-Price offers a unique bonus: an app and an offline toy. While it’s an excellent idea to start kids off with hands-on tech and programming edification, too much screen time yields detrimental results. Therefore, the Think and Learn Code-a-Pillar app and its corresponding toy work in conjunction.

With the app, kids solve puzzles which present basic computer programming and coding concepts. It’s aimed at younger children, ages 3–6. While there is a Code-a-Pillar toy, the app is standalone. Some of the directions might be slightly challenging for the kiddos. Therefore it’s best if an adult supervises. Though the same can be said about a young age group deciphering the directions to “Candy Land.” Sound effects and the soundtrack may both be turned off. This remains a pleasant touch as it limits possible distractions.

Why it’s great: There’s a corresponding physical toy in addition to the standalone app. Plus, music and effects can be turned off for a distraction-free experience.

4. Gamestar Mechanic (Paid, Web)

Gamestar Mechanic is a web-based app that teaches kids to make their own videos games. Playing games is enticing, so the promise of game design is appealing to children, moreso than web development or app development. Thus, game design is an excellent foray with a huge payoff: getting to play a game. But since Gamestar Mechanic focuses on game design, it’s decidedly more advanced. Don’t expect simplistic matching games as seen in apps such as Think and Learn Code-a-Pillar.

For kids around 7–14, Gamestar Mechanic is perfect. The app boasts courses, game creation, and a play and learn feature with gamification. Quests build game design, and you gain items which you can use to make games. A robust community rounds out Gamestar Mechanic, making it a spectacular coding app for teens and pre-teens.

Why it’s great: Gamestar Mechanic aims at a slightly older age group. Game design is a promising and budding sector, so there’s a perfect segue into more advanced programming.

5. Minecraft (Paid)

Minecraft is a massively popular game. Its sandbox style makes it highly adaptable. While it’s not necessarily aimed at kids, Minecraft and its all-ages content prominently offers a safe environment for programming. Some mods specifically target children, such as the child-centric LearnToMod mod.

You might use Minecraft as an opportunity to teach your children about servers and set up a Linux game server.

However, Minecraft is not pre-configured for younger audiences. Adults may need perform a bit of initial set up. But once it’s created, LearnToMod offers a bevy of programming knowledge that’s digestible. There’s a thriving online community. As most of these apps go, Minecraft is pricier. Yet it holds loads of promise with its tutorials which foster real-world programming skills. Minecraft Pi is an awesome medium to get kids modding in Minecraft.

Why it’s great: Mods such as the LearnToMod mod teach kids actual coding skills with lessons and instructions.

6. Tynker (Free/Paid, Web)

Tynker is a solid app. Its name suggests tinkering, which connotes getting hands on. As such, Tynker teaches programming brilliantly. Like many apps for kids to learn programming, Tynker infuses coding with excitement. As a platform, it boasts a smattering of choices. Kids can code robots and drones, mod Minecraft, build apps and games, or explore STEM.

Children begin with code using visual blocks before starting with Python and JavaScript. But along the way, programming centers on projects so there’s an enticing value proposition for kids. Since Tynker starts with visual blocks before moving up to actual code, there’s a clear learning path. A comprehensive environment with levels of increasing advancement makes Tynker one of the best mediums for kids to learn programming. You may also consider the similarly-minded Scratch, which is backed by MIT.

Why it’s great: It’s free, and offers paid tiers. Tynker allows kids to make neat projects and grows as kids do.

7. Nancy Drew: Codes & Clues – Mystery Coding Game (Paid, iOS/Android)

If there was anything that motivated me to type, it was Mavis Beacon. However, had my mother allowed me a copy of Typing of the Dead, I would likely have preferred that. Perhaps a Coding of the Dead game is in order though maybe not for kids. Similarly, Nancy Drew: Codes & Clues – Mystery Coding Game presents learning with games. Moreover, the Nancy Drew: Codes & Clues game includes a subtle STEM theme with its protagonist.

The premise is simple yet effective. There’s a narrative about a tech fair and a mystery to solve. Along the way, kids drag and drop visual code blocks into their proper places. Certain mini-games involve selecting costumes. Goldieblox: Adventures in Coding – The Rocket Cupcake Co. is another stupendous entry-level coding app with a STEM concentration. Because of its balanced gameplay, Nancy Drew is one of the best coding apps for kids to learn programming.

Why it’s great: Intuitive, entertain gameplay and STEM themes.

The Best Coding Apps for Kids to Learn Programming

Although programming might sound incredibly advanced, it’s an excellent idea to get kids started early. These five best coding apps for kids provide a spectacular opportunity for kids to learn programming. Microsoft remains at the forefront of tech, and its Kodu GameLab stands as a solid foray into programming. As a child, I mostly played Oregon Trail II and Math Blaster.

As your kids grow older, you may even want to introduce them to these awesome coding games for learning programming. Once you’ve selected the best apps for your kids to learn programming, check out these indestructible and educational tablets for kids.

Image Credits: tuthelens/Shutterstock