Week 1 - Section 1 - Input and Output
Site: | ΕΛ/ΛΑΚ Moodle |
Course: | Python Lab - May 2017 |
Book: | Week 1 - Section 1 - Input and Output |
Printed by: | Guest user |
Date: | Wednesday, 27 November 2024, 9:28 PM |
Description
In the first section of the first week we will learn how to send the output of a program to the screen and how to read from the keyboard.
Chapter 1.1 - Printing Text
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.
Chapter 1.2 - Printing Results of Expressions
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.
Chapter 1.3 - Printing Multiple Items
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 as text. Anything outside the computer thinks 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?
Chapter 1.4 - Escape Codes
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.
Chapter 1.5 - Comments
Chapter 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.
print("Hi")
'''
This is
a
multi
line
comment. Nothing
Will run in between these quotes.
print("There")
'''
print("Done")
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.
Chapter 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.
Chapter 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.
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.
Chapter 1.8 - Operators
Chapter 1.8 Operators
For more complex mathematical operations, common mathematical operators are available.
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.
Chapter 1.9 - Input and variable types
Until now we have learned that we can interact with Python using the CLI interface. But entering Python code at the >>> prompt is slow and can only be done one line at a time. It is also not possible to save the code so that another person can run it. Thankfully, there is an even better way to enter Python code.
Python code can be entered using a script. A script is a series of lines of Python code that will be executed all at once.
In spyder3 you can write a series of commands in the editor window and save them as a script.
Let's say that we would like to calculate the kilometers per liter that a car achieves.
A simple program would be
k = 253 # we have traveled 253km
g = 15.2 # we have used 15.2 liters of gasoline
kpg = k / g
print ("Kilometers per liter: ", kpg)
This script could be even more useful if it would interact with the user asking the users to input the variables. This can be done with the input statement. We will also use better name for the variables so we would not need comments to explain what the variables are representing. See the code below.
# This code almost works
kilometers_driven = input("Enter kilometers driven: ")
liters_used = input("Enter liters used: ")
kpl = kilometers_driven / liters_used
print("Kilometers per liter: ", kpl)
Why this code produces an error? This is because the program does not know the user will be entering numbers. The user might enter “Bob” and “Mary”.
To tell the computer these are numbers, it is necessary to surround the input function with an int( ) or a float( ). Use the former for integers, and the latter for floating point numbers.
# Calculate kilometers Per Liter
print("This program calculates kpl.")
# Get kilometers driven from the user
kilometers_driven = input("Enter kilometers driven: ")
# Convert text entered to a floating point number
kilometers_driven = float(kilometers_driven)
# Get liters used from the user
liters_used = input("Enter liters used: ")
# Convert text entered to a floating point number
liters_used = float(liters_used)
# Calculate and print the answer
kpl = kilometers_driven / liters_used
print("Kilometers per liter: ", kpl)
How can we find what type is a variable? We can use the command type. Try the following code sequentially in the command line entering a floating point number (ex. 34.5).
a = input("Enter a number : ")
print (a)
type (a)
a = float(a)
print (a)
type(a)