Module 1 - Section 1 - Output

Site: ΕΛ/ΛΑΚ Moodle
Course: Python Lab
Book: Module 1 - Section 1 - Output
Printed by: Guest user
Date: Thursday, 21 November 2024, 5:13 PM

Description

After the completion of this module the students will be able to:

  • complete commands to send to the output
  • construct a command for multiple output
  • state and use Escape Codes
  • create comments
  • use arithmetic operators

1.1.1 - Printing Text

How does a program print something to the screen? The code is simple. Just one line is required:

>>> print("Hello World.")

This program prints out “Hello World” to the screen. Go ahead and enter it into the CLI prompt and see how it works. Try printing other words and phrases as well. The computer will happily print out just about anything you like, true or not.

Remember, the command for printing in Python is easy. Just use print. After the print command are a set of parentheses (). Inside these parentheses is what should be printed to the screen. Using parentheses to pass information to a function is standard practice in math, and computer languages.

Notice that there are double quotes around the text to be printed. If a print statement has quotes around text, the computer will print it out just as it is written. For example, this program will print 2+3:

>>> print("2+3")

Go ahead and try it entering the expression inside the CLI.

1.1.2 - Printing Results of Expressions

This next program does not have quotes around 2+3, and the computer will evaluate it, as a mathematical expression. It will print 5 rather than 2+3.

>>> print(2 + 3)

The code below will generate an error because the computer will try to evaluate “Hello World” as a mathematical expression, and that doesn't work at all:

>>> print(Hello World)

The code above will print out an error SyntaxError: invalid syntax which is computer-speak for not knowing what “Hello” and “World” mean.

Try to print the output of other expressions using the CLI.

1.1.3 - Printing Multiple Items

A print statement can output multiple things at once, each item separated by a comma. For example this code will print out : Your new score is 1040

>>> print("Your new score is", 1030 + 10)

The next line of code will print out "Your new score is 1030+10". The numbers are not added together because they are inside the quotes. Anything inside quotes, the computer treats it as text. Anything outside quotes the computer thinks it is a mathematical statement or computer code.

>>> print("Your new score is", "1030 + 10")

This next code example doesn't work at all. This is because there is no comma separating the text between the quotes, and the 1030+10. At first, it may appear that there is a comma, but the comma is inside the quotes. The comma that separates the terms to be printed must be outside the quotes. If the programmer wants a comma to be printed, then it must be inside the quotes:

>>> print("Your new score is," 1030 + 10)

This next example does work, because there is a comma separating the terms. It prints: 

Your new score is, 1040

Note that only one comma prints out. Commas outside the quotes separate terms, commas inside the quotes are printed. The first comma is printed, the second is used to separate terms.

>>> print("Your new score is,", 1030 + 10)

Now try and think. When a comma goes outside the parenthesis and when not. When you should put a comma and when you shouldn't?

1.1.4 - Escape Codes

If quotes are used to tell the computer the start and end of the string of text you wish to print, how does a program print out a set of double quotes? For example:

>>> print("I want to print a double quote " for some reason.")

This code doesn't work. The computer looks at the quote in the middle of the string and thinks that is the end of the text. Then it has no idea what to do with the commands for some reason and the quote and the end of the string confuses the computer even further.

It is necessary to tell the computer that we want to treat that middle double quote as text, not as a quote ending the string. This is easy, just prepend a backslash in front of quotes to tell the computer it is part of a string, not a character that terminates a string. For example:

>>> print("I want to print a double quote \" for some reason.")

This combination of the two characters \" is called an escape code. Almost every language has them. Because the backslash is used as part of an escape code, the backslash itself must be escaped. For example, this code does not work correctly:

>>> print("The file is stored in C:\new folder")

Why? Because \n is an escape code. To print the backslash it is necessary to escape it like so:

>>> print("The file is stored in C:\\new folder")


What is a “Linefeed”? Try this example:

>>> print("This\nis\nmy\nsample.")

The output from this command is:

This
is
my
sample.

The \n is a linefeed. It moves “cursor” where the computer will print text down one line. The computer stores all text in one big long line. It knows to display the text on different lines because of the placement of \n characters.

1.1.5 - Comments

Sometimes code needs some extra explanation to the person reading it. To do this, we add “comments” to the code. The comments are meant for the human reading the code, and not for the computer. 

There are two ways to create a comment. The first is to use the # symbol. The computer will ignore any text in a Python program that occurs after the #. For example:

>>> # This is a comment, it begins with a # sign

>>> # and the computer will ignore it.

>>> print("This is not a comment, the computer will")

>>> print("run this and print it out.")

If a program has the # sign between quotes it is not treated as a comment. A programmer can disable a line of code by putting a # sign in front of it. It is also possible to put a comment in at the end of a line.

>>> print("A # sign between quotes is not a comment.")

>>> # print("This is a comment, even if it is computer code.")

>>> print("Hi") # This is an end-of-line comment

It is possible to comment out multiple lines of code using three single quotes in a row to delimit the comments.

'''

This is
a
multi
line
comment. Nothing
Will run in between these quotes.
print("There")

'''


Most professional Python programmers will only use this type of multi-line comment for something called docstrings. Docstrings allow documentation to be written along side the code and later be automatically pulled out into printed documentation, websites, and Integrated Development Environments (IDEs). For general comments, the # tag works best.

Even if you are going to be the only one reading the code that you write, comments can help save time. Adding a comment that says “Handle alien bombs” will allow you to quickly remember what that section of code does without having to read and decipher it.

1.1.6 - Assignment Operators

Chapter 1.6 - Assignment Operators

How do we store the score in our game? Or keep track of the health of the enemy? What we need to do this is the assignment operator

An operator is a symbol like + or -. An assignment operator is the = symbol. It stores a value into a variable to be used later on. The code below will assign 10 to the variable x, and then print the value stored in x. 

>>> # Create a variable x

>>> # Store the value 10 into it.

>>> x = 10

>>> # This prints the value stored in x.

>>> print(x)

>>> # This prints the letter x, but not the value in x

>>> print("x")

>>> # This prints "x= 10"

>>> print("x=", 10)

An assignment statement (a line of code using the = operator) is different than the algebraic equality your learned about in math. Do not think of them as the same. On the left side of an assignment operator must be exactly one variable. Nothing else may be there.

On the right of the equals sign/assignment operator is an expression. An expression is anything that evaluates to a value. Examine the code below.

>>> x = x + 1

There are also assignment operators for addition, subtraction, multiplication and division.

1.1.7 - Variables

So what is a variable? Variable is a container. And what it contains? It can contain almost everything from numbers (integer, floating or complex) to strings

Variables should start with a lower case letter. They can start with an upper case or an underscore but you should not do it in normal basis. After the first lower case letter, the variable may include uppercase and lowercase letters, along with numbers and underscores. Variables may not include spaces.

Variables are case sensitive. This can be confusing if a programmer is not expecting it. In the code below, the output will be 6 rather than 5 because there are two different variables, x and X.

>>> x = 6

>>> X = 5

>>> print(x)

>>> print(X)

There are some rules for naming variables but it is not something that we should always follow.

Check the table below and think what are the rules for naming.


Variable Names
Legal Variable Names       Illegal Variable Names      Legal but not proper     
first_name first name FirstName
distance 9ds firstName
ds9 %correct D9

All upper-case variable names like MAX_SPEED are allowed only in circumstances where the variable's value should never change. A variable that isn't variable is called a constant.

1.1.8 - Operators

Chapter 1.8 Operators

For more complex mathematical operations, common mathematical operators are available.


Operators
operator      operation      example      code     
+ addition 3+2 a = 3+2
- subtraction 3-2 b = 3-2
* multiplication 3*2 c=3*2
/ division 10/2 d=10/2
// floor division e=10//3
** power 23 f=2**3
% modulus g=8%3

Try to check the results of the code in two lines, first calculating the result of the operation and then print the result like the following code.

>>> a = 3 + 2

>>> print(a)

“Floor division” will always round the answer down to the nearest integer. For example, 11//2 will be 5, not 5.5, and 99//100 will equal 0.


The official style guide for Python says that there should be a space before and after each operator