knowt logo

PYTHON LESSON 1: Syntax (Part 1)

Print Statements;

If programming is the act of teaching a computer to have a conversation with a user, it would be most useful to first teach the computer how to speak. In Python, this is accomplished with the print statement.

print "Hello, world!"
print "Water—there is not a drop of water there! Were Niagara but a cataract of sand, would you travel your thousand miles to see it?"

A print statement is the easiest way to get your Python program to communicate with you. Being able to command this communication will be one of the most valuable tools in your programming toolbox.

There are two different Python versions. Both Python 2 and Python 3 are used throughout the globe. The most significant difference between the two is how you write a print statement. In Python 3, print has parentheses.

print("Hello World!")
print("Deep into distant woodlands winds a mazy way, reaching to overlapping spurs of mountains bathed in their hill-side blue.")

Test it out in your python program!

Strings;

When printing things in Python, we are supplying a text block that we want to be printed. Text in Python is considered a specific type of data called a string. A string, so named because they’re a series of letters, numbers, or symbols connected in order — as if threaded together by string. Strings can be defined in different ways:

print "This is a good string"
print 'You can use single quotes or double quotes for a string'

Above we printed two things that are strings and then attempted to print two things that are not strings. While double-quotes (“) and single-quotes (‘) are both acceptable ways to define a string, a string needs to be opened and closed by the same type of quote mark.

We can combine multiple strings using +, like so:

print "This is " + "a good string"

This code will print out “This is a good string”.

A string can contain letters, numbers, and symbols.

name = "Ryan"
age = "19"
food = "cheese"

In the above example, we create a variable name and set it to the string value "Ryan". We also set age to "19" and food to "cheese".

Multi-Line Strings;

We have seen how to define a string with single quotes and with double quotes. If we want a string to span multiple lines, we can also use triple quotes:

address_string = """136 Whowho Rd
Apt 7
Whosville, WZ 44494"""

This address spans multiple lines, and is still contained in one variable, address_string.

When a string like this is not assigned to a variable, it works as a multi-line comment. This can be helpful as your code gets more complex:

"""The following piece of code does the following steps:
takes in some input
does An Important Calculation
returns the modified input and a string that says "Success!" or "Failure..."
"""

String Methods;

String methods let you perform specific tasks for strings.

We’ll focus on four string methods:

  1. len()

  2. lower()

  3. upper()

  4. str()

Let’s start with len(), which gets the length (the number of characters) of a string!

parrot = “Norweigan Blue”
print len(parrot)

The result will be how many letters there are in Norwegian Blue!

You can use the lower() method to get rid of all the capitalization in your strings. You call lower() like so:

"Ryan".lower()

which will return "ryan". upper() makes your string 100% lower case! A similar method exists to make a string completely upper case.

Now let’s look at str(), which is a little less straightforward. The str() method turns non-strings into strings! For example:

str(2)

would turn 2 into "2".

String Concatenation;

You know about strings, and you know about arithmetic operators. Now let’s combine the two!

print "Life " + "of " + "Brian"

This will print out the phrase Life of Brian.

The + operator between strings will ‘add’ them together, one after the other. Notice that there are spaces inside the quotation marks after Life and of so that we can make the combined string look like 3 words.

Combining strings together like this is called concatenation.

Explicit String Conversion;

Sometimes you need to combine a string with something that isn’t a string. In order to do that, you have to convert the non-string into a string.

print "I have " + str(2) + " coconuts!"

This will print “I have 2 coconuts!”.

The str() method converts non-strings into strings. In the above example, you convert the number 2 into a string and then you concatenate the strings together just like in the previous exercise.

String Formatting with %;

When you want to print a variable with a string, there is a better method than concatenating strings together.

name = "Mike"
print "Hello %s" % (name)

The % operator after the string is used to combine a string with variables. The % operator will replace the %s in the string with the string variable that comes after it.

If you’d like to print a variable that is an integer, you can “pad” it with zeros using %02d. The 0 means “pad with zeros”, the 2 means to pad to 2 characters wide, and the d means the number is a signed integer (can be positive or negative).

day = 6
print "03 - %s - 2019" %  (day)
# 03 - 6 - 2019
print "03 - %02d - 2019" % (day)
# 03 - 06 - 2019

Remember, we used the % operator to replace the %s placeholders with the variables in parentheses.

name = "Mike"
print "Hello %s" % (name)

You need the same number of %s terms in a string as the number of variables in parentheses:

print "The %s who %s %s!" % ("Knights", "say", "Ni")

This will print "The Knights who say Ni!".

Handling Errors;

As we get more familiar with the Python programming language, we run into errors and exceptions. These are complaints that Python makes when it doesn’t understand what you want it to do. Everyone runs into these issues, so it is a good habit to read and understand them.

Here are some common errors that we might run into when printing strings:

print "Mismatched quotes will cause a SyntaxError'
print Without quotes will cause a NameError

If the quotes are mismatched Python will notice this and inform you that your code has an error in its syntax because the line ended (called an EOL) before the double-quote that was supposed to close the string appeared. The program will abruptly stop running with the following message:

SyntaxError: EOL while scanning a string literal

This means that a string wasn’t closed, or wasn’t closed with the same quote-character that started it.

Another issue you might run into is attempting to create a string without quotes at all. Python treats words not in quotes as commands, like the print statement. If it fails to recognize these words as defined (in Python or by your program elsewhere) Python will complain the code has a NameError. This means that Python found what it thinks is a command, but doesn’t know what it means because it’s not defined anywhere.

Escaping Characters;

There are some characters that cause problems. For example:

'There's a snake in my boot!'

This code breaks because Python thinks the apostrophe in 'There's' ends the string. We can use the backslash to fix the problem, like this:

'There\'s a snake in my boot!'

IC

PYTHON LESSON 1: Syntax (Part 1)

Print Statements;

If programming is the act of teaching a computer to have a conversation with a user, it would be most useful to first teach the computer how to speak. In Python, this is accomplished with the print statement.

print "Hello, world!"
print "Water—there is not a drop of water there! Were Niagara but a cataract of sand, would you travel your thousand miles to see it?"

A print statement is the easiest way to get your Python program to communicate with you. Being able to command this communication will be one of the most valuable tools in your programming toolbox.

There are two different Python versions. Both Python 2 and Python 3 are used throughout the globe. The most significant difference between the two is how you write a print statement. In Python 3, print has parentheses.

print("Hello World!")
print("Deep into distant woodlands winds a mazy way, reaching to overlapping spurs of mountains bathed in their hill-side blue.")

Test it out in your python program!

Strings;

When printing things in Python, we are supplying a text block that we want to be printed. Text in Python is considered a specific type of data called a string. A string, so named because they’re a series of letters, numbers, or symbols connected in order — as if threaded together by string. Strings can be defined in different ways:

print "This is a good string"
print 'You can use single quotes or double quotes for a string'

Above we printed two things that are strings and then attempted to print two things that are not strings. While double-quotes (“) and single-quotes (‘) are both acceptable ways to define a string, a string needs to be opened and closed by the same type of quote mark.

We can combine multiple strings using +, like so:

print "This is " + "a good string"

This code will print out “This is a good string”.

A string can contain letters, numbers, and symbols.

name = "Ryan"
age = "19"
food = "cheese"

In the above example, we create a variable name and set it to the string value "Ryan". We also set age to "19" and food to "cheese".

Multi-Line Strings;

We have seen how to define a string with single quotes and with double quotes. If we want a string to span multiple lines, we can also use triple quotes:

address_string = """136 Whowho Rd
Apt 7
Whosville, WZ 44494"""

This address spans multiple lines, and is still contained in one variable, address_string.

When a string like this is not assigned to a variable, it works as a multi-line comment. This can be helpful as your code gets more complex:

"""The following piece of code does the following steps:
takes in some input
does An Important Calculation
returns the modified input and a string that says "Success!" or "Failure..."
"""

String Methods;

String methods let you perform specific tasks for strings.

We’ll focus on four string methods:

  1. len()

  2. lower()

  3. upper()

  4. str()

Let’s start with len(), which gets the length (the number of characters) of a string!

parrot = “Norweigan Blue”
print len(parrot)

The result will be how many letters there are in Norwegian Blue!

You can use the lower() method to get rid of all the capitalization in your strings. You call lower() like so:

"Ryan".lower()

which will return "ryan". upper() makes your string 100% lower case! A similar method exists to make a string completely upper case.

Now let’s look at str(), which is a little less straightforward. The str() method turns non-strings into strings! For example:

str(2)

would turn 2 into "2".

String Concatenation;

You know about strings, and you know about arithmetic operators. Now let’s combine the two!

print "Life " + "of " + "Brian"

This will print out the phrase Life of Brian.

The + operator between strings will ‘add’ them together, one after the other. Notice that there are spaces inside the quotation marks after Life and of so that we can make the combined string look like 3 words.

Combining strings together like this is called concatenation.

Explicit String Conversion;

Sometimes you need to combine a string with something that isn’t a string. In order to do that, you have to convert the non-string into a string.

print "I have " + str(2) + " coconuts!"

This will print “I have 2 coconuts!”.

The str() method converts non-strings into strings. In the above example, you convert the number 2 into a string and then you concatenate the strings together just like in the previous exercise.

String Formatting with %;

When you want to print a variable with a string, there is a better method than concatenating strings together.

name = "Mike"
print "Hello %s" % (name)

The % operator after the string is used to combine a string with variables. The % operator will replace the %s in the string with the string variable that comes after it.

If you’d like to print a variable that is an integer, you can “pad” it with zeros using %02d. The 0 means “pad with zeros”, the 2 means to pad to 2 characters wide, and the d means the number is a signed integer (can be positive or negative).

day = 6
print "03 - %s - 2019" %  (day)
# 03 - 6 - 2019
print "03 - %02d - 2019" % (day)
# 03 - 06 - 2019

Remember, we used the % operator to replace the %s placeholders with the variables in parentheses.

name = "Mike"
print "Hello %s" % (name)

You need the same number of %s terms in a string as the number of variables in parentheses:

print "The %s who %s %s!" % ("Knights", "say", "Ni")

This will print "The Knights who say Ni!".

Handling Errors;

As we get more familiar with the Python programming language, we run into errors and exceptions. These are complaints that Python makes when it doesn’t understand what you want it to do. Everyone runs into these issues, so it is a good habit to read and understand them.

Here are some common errors that we might run into when printing strings:

print "Mismatched quotes will cause a SyntaxError'
print Without quotes will cause a NameError

If the quotes are mismatched Python will notice this and inform you that your code has an error in its syntax because the line ended (called an EOL) before the double-quote that was supposed to close the string appeared. The program will abruptly stop running with the following message:

SyntaxError: EOL while scanning a string literal

This means that a string wasn’t closed, or wasn’t closed with the same quote-character that started it.

Another issue you might run into is attempting to create a string without quotes at all. Python treats words not in quotes as commands, like the print statement. If it fails to recognize these words as defined (in Python or by your program elsewhere) Python will complain the code has a NameError. This means that Python found what it thinks is a command, but doesn’t know what it means because it’s not defined anywhere.

Escaping Characters;

There are some characters that cause problems. For example:

'There's a snake in my boot!'

This code breaks because Python thinks the apostrophe in 'There's' ends the string. We can use the backslash to fix the problem, like this:

'There\'s a snake in my boot!'