天天看點

info1110輔導quiz1

文章目錄

  • ​​This is a comment.​​
  • ​​Another implementation​​
  • ​​newlines_again.py​​
  • ​​pi_example.py​​

對于info1110來說,這門課是python程式設計基礎,整體都不難。隻是在30分鐘内做完10道題,想拿滿分,比較考驗個人的功力。

不要想着把代碼打出來驗證對錯,太耗費時間了。

直接肉眼看就行。

Lab 1: Unix Terminal and Python Basics

Introduction

Welcome to INFO1110! This course will teach you the basics of programming from the ground up in

a beginner friendly way. Hopefully you have seen the �rst lecture and are ready to dive straight in!

Ed will be our go-to communication channel. This will be where you may ask any programming

related questions, so be sure to make full use of it! We will also be posting important announcements

here, so remember to check in regularly. This will also be where you will obtain all your course

materials from.

Canvas will be used for lecture recordings, online classes as well as viewing your �nalised marks.

We strongly suggest that you use a Unix operating system (i.e. macOS or Linux) for this course. When

you use lab computers, please reboot them into Linux (Red Hat / Fedora) if they are in Windows.

At the end of this week, you should be able to:

Explain the di�erence between low-level and high-level programming language.

Solve problems by designing an algorithm in plain English.

Perform basic �le operations (view, create, remove �les) through the terminal.

Write and execute Python programs using the text editor and terminal approach.

Explain the steps to debug programs.

Evaluate and explain Python statements to another human.

Identify search terms to forage for information on the Internet on the topic of programming.

0. Test your knowledge

Question 1

True

False

Question 2

True

False

Question 3

True

False

Question 4

True

True or False. Justify your answer to another human. If you have di�culties explaining your answer,

try re-visiting these questions after you have completed the hands-on activities in this lab and the

recommended reading.

Python is a low-level programming language.

Python can be automatically converted to machine language once you have written the codes to a

�le.

There is no di�erence between a compiler and interpreter.

Python codes can be executed directly in the Python Interpreter or Python Shell.

False

Question 5

True

False

You must always write Python codes into a �le.

Attendance Link

Sign-in using any of these options:

Scan the QR code:

Short link: https://bit.ly/3rncMws

Long link: https://sres.sydney.edu.au/go/61fb7f4ab064c6857647c934

  1. The Terminal

    Ensure you have set up your Unix system. Check the “Getting Started!” Edstem post if you have not

    done so yet!

    The terminal is an interface to your machine. It is much more capable (and potentially destructive)

    than your normal �le explorer/GUI interface but it will feel very clunky at �rst! Open up a �le explorer

    and try each of the following commands one at a time to see their e�ect!

    Exercise: Create a folder named Tutorial1 in the info1110 folder and cd into it.

    Hints:

    With a bit of practice, you’ll get used to it very quickly!

    Directory means folder.

    You can press the in the terminal to auto complete! Tap it twice to see possible auto

    complete options.

    You can press the and arrow keys on your keyboard to get the previous and next

    commands you have typed!

  2. Hello, World!

    Hello, World! is usually the �rst go-to program everyone writes, and for good reason! It introduces

    you to the basic syntax (grammar) of the language and also veri�es that your system is set up

    correctly!

    Open your favourite text editor and create a new �le.

    Write the following code in the �le:

    print(‘Hello, World!’)

    Save the �le with the �lename hello.py . You have now just created a program called

    hello.py !

    Open the terminal and cd to where you saved the �le.

    Run your program in the terminal using the command python3 !

    Your program will display Hello, World! to standard out (which in this case is the terminal screen)!

    ⭐3. String and Syntax Errors

    Information in the real-world can be represented as: text and numbers. Information must be

    represented in the computer as data types before it can be used. A string is a data type that contains a

    sequence of characters. It must be surrounded by single quotes e.g. ‘Hello, World’ or double

    quotes e.g. “Hello, World” . You can use the type() function to display the data type to con�rm

    that both values are string object.

    In other programming languages such as C, single and double quotes have di�erent meanings. Single

    quotes are used for characters while double quotes are used for strings. In Python, you can use one

    or the other but not both in the same statement to represent a string. Experiment by removing the #

    and executing the following codes, a line at a time.

    Execute the codes by pressing the Run button.

    #print(“Valid string”)

    #print(‘Valid string’)

    #print(‘Invalid string") # Run this line by removing the first char (#)

    #print("Invalid string’)

    In Python, the # denotes that the line is a comment. Generally, comments are ignored by the

    compiler and added into the program for documentation purposes. In other languages, the syntax

    will be di�erent but its purpose remains the same. See the Extra section for an example in C.

    Part 1:

    Create a Python program with the following codes. Make sure the codes are exactly as it appears

    here:

This is a comment.

print(‘example’)

print(“example”)

print(type(‘example’))

print(type(“example”))

What is the �lename of your program?

What are the steps that you took to execute the program?

What do you expect to see in the the terminal once the program executes?

Why are the quotation marks not present in the output?

Why is the �rst line of codes not present in the output?

Part 2:

Novice programmers tend to forget matching pairs of parenthesis/brackets/bracers or mix

quotations while working in the text editor. This will raise an error(complaint) because the command

is syntactically wrong. Hence, it is known as Syntax Error.

Integrated Development Environments (IDE) and some text editors will help you avoid this mistake by

including the closing partner as you type these characters. It is similar to the auto-correction and

predictive text when you type text messages on your phone except in this case the software is

helping you to code!

Execute the programs bad1.py , bad2.py and bad3.py . For each case, read the messages in the

terminal and note the details of the complaint - type of error, line number and explanation. Can you

identify the source of the error?

Fix the errors. The programs must produce the exact outputs as:

$ python3 bad1.py

There is something wrong.

My partner is missing!

$ python3 bad2.py

Everything looks correct… except

wrong closing partner:/

$ python3 bad3.py

INFO1110 Introduction to Programming

Extra Knowledge

This is an example �rst program in C language. Can you guess what the program does?

Press the Run button to execute the program. Observe the output.

#include <stdio.h> // This is a comment.

int main() {

/* This is also a comment.

Does this look familiar?*/

printf(“Hello, World! \n”);

return 0;

}

There are no multi-line comments in Python language like C does. You can use triple-quotes ‘’’ to

create a docstring.

⭐ 4. Search for Escape Sequence

You may �nd yourself in a situation when you want to use an apostrophe e.g. I’m BUT if you

initialize the string variable using single quotation marks, this will be problematic. The backslash ( \ ),

called the escape character, allows you to tell the computer that this is part of the string and not the

closing quotation of the string.

Execute the following statements in Python and observe the output.

print(‘Santa’s biscuits’)

print(“Santa’s biscuits”)

Part 1:

What terms will you use to learn more about escape sequence in Python on the Internet?

Do a search using these terms to learn more about other escape sequences.

Explain the di�erence between an escape character and escape sequence to your study partner.

Complete this table for your study notes:

Part 2:

Add codes to the program escapes.py to produce this output:

‘|"/"|’

‘|/ |’

‘|\ /|’

‘|"/"|’

Make sure you understand the given sca�old program.

Part 3:

How many new lines will the newlines.py program produce? Explain your answer.

Hint: The print() documentation has a clue! It is �ne if the documentation does not make perfect sense

yet. Can you spot the escape sequence?

⭐ 5. Arithmetic Operators and Numbers

Now, we will work with numerical data types. Let’s perform arithmetic calculations in Python. This is

similar to using a physical scienti�c calculator without the buttons or using the computer calculator

without the fancy graphical interface.

The basic arithmetic operators for addition, subtraction, multiplication and division are the same

between the computer calculator and Python. In the following parts, you will be asked to test out the

Python codes directly in the Python Shell. This allows you to quickly view the result of execution

(value) without using print() because the Python Shell connects to standard output by default.

Part 1:

Launch the Python Shell (also called Python interpreter) by typing python3 in the terminal. You can

exit the Python Shell at anytime by entering the command exit() or quit() .

Execute the Python codes for each row and note down the values returned (column: Result). Example

for �rst row:

Python 3.10.2 (main, Jan 15 2022, 19:56:27) [GCC 11.1.0] on linux

Type “help”, “copyright”, “credits” or “license” for more information.

5 + 2

7

Complete the table below for your study notes:

Hint: Python document for Numeric Types - int, �oat, complex

Important:

In some languages, the ^ operator is used for exponentiation but in Python it is a bitwise

operator called XOR.

5 + 2 is di�erent from ‘5 + 2’ . The former means to add numbers, 5 and 2, together which

returns i.e. produces the result of 7. The latter is a text representation (string) of ‘5 + 2’ . If

you do not believe this, use the type() function in the Python Shell to verify the data type of

both expressions. You will see something like this:

type(5 + 2)

<class ‘int’>

type(‘5 + 2’)

<class ‘str’>

Data type int refers to integers. Data type float refers to �oating-point numbers i.e.,

numbers with decimal points like 2.5. Can you spot which expression will return a data type of

float ?

Part 2:

The order of operations follows the rules of PEDMAS - Parenthesis, Exponents,

Division/Multiplication and Addition/Subtraction. Operations that are on the same level,

Division/Multiplication and Addition/Subtraction, will be evaluated from left to right.

Predict the output of this Python expression. Explain your answer by including the step-by-step

working to reach the result and stating the data type of the result.

(7-5)*15/2+102

int((7-5)*15/2)+102

Did you �nd both expressions di�cult to read? Re-write the Python expression using parenthesis and

whitespaces to improve readability of both expressions.

Hint: PEP-8 Style Guide contains recommended practice for Python community.

Part 3:

The arithmetic operators are called binary operators. There must be a value on either side of the

operator. If a value is missing, you will be seeing another SyntaxError complaint.

What do you think will be the output if these codes when they are executed in the Python Shell? If

you are the computer, will you be able to work out the answer?

5 +

5 2

100,000

As before, it is important that you make notes of your observations. This will help you be aware of

the errors you have experienced, their causes and how to �x them.

If you have an extremely big number e.g. thousands. Do not separate them with commas e.g. 10,

  1. This format is easily readable by humans but it actually means something else in Python!

    ⭐ 6. Arithmetic Operators on String and TypeErrors

    We will now try applying the basic arithmetic operators ( + , - , * , / ) on strings. Execute each of the

    following Python expressions in the Python Shell and note down the output:

‘5’ + ‘2’

‘5’ + 2

‘5’ - ‘2’

‘5’ - 2

‘5’ * ‘2’

‘5’ * 2

‘5’ / ‘2’

‘5’ / 2

Which expressions produces a result?

Does the behaviour of the computer makes sense? If you are asked to divide two words/a word

and a number in real-life, can you do it?

For expression that did not work i.e. produces a TypeError, are the descriptions of the error

message the same?

List the conclusions that you can draw from your observations about applying arithmetic

operators on strings and TypeError.

Part 1:

Predict the output of this program. Explain your answer to another human.

print(‘Hello,’, ‘Brown’, ‘Cow!’)

print(‘Brown ’ + ‘Cow!\n’*3)

print(‘Hello,’, ‘Blue’ + ’ Cow!\n’ + ('Blue ’ + ‘Cow?\n’) * 3)

Run the program to check your answer.

Part 2:

Predict the output of this program. Explain your answer to another human.

Run this program to check your answer and observe the output.

Hint: Try executing line by line and note down the line numbers that produces an output.

print(‘This will work.’)

print(‘This will work too.’)

print(‘This is wrong!\n’ * ‘3’)

print(‘1’ + 1, ‘is’, 11)

This program is syntactically correct: the operators has values on both sides, all parenthesis and

quotation marks are in pairs. In fact, the program was partially running until something goes wrong

midway. This is called a runtime error or exception. The description in the error message provides

information on which line this occurs in and an explanation of the error.

Important Notes

The arithmetic operators that will work on strings in Python are: + and *

String multiplication is a Pythonic feature and does not work for other languages.

  1. Built-in Functions and Assignment Statement

    The word ‘function’ keeps cropping up in the previous questions e.g. print() , type()

    A function is a block of organized, reusable code that is used to perform a single, related

    action. (source)

    The functions that we have been using are built-in functions, it comes together with Python and are

    readily available for you to use. To use functions, you only need to know the pieces of information

    that it needs (inputs) and the result that it will produce (outputs). These information are usually

    present in the o�cial Python documentation. We will look at the print() function closely in this

    question.

    If you have trouble wrapping your head around functions, think about ‘driving a car’ analogy:

    "Drivers don’t exactly need knowledge of how internal combustion engines work to drive. A person

    can drive a car (use a function) as long as they know that the accelerator pedal (input) moves the car

    (output) and the brake pedal (input) stops the car (output). "

    The diagram below is an overview of how a function works using the int() function as an example:

    Mysterious

    black box that

    does something

    Inputs

    Outputs

    num = int(‘12345’)

    Input

    Function

    name

    Output

    Functions

    Recall that ‘12345’ and 12345 are two di�erent data types. The former is a str ing and the latter is

    an int eger. The int() function converts the given inputs, in this case: ‘12345’ , to the numeric

    value, 12345 .

    Try executing this statement in the Python Shell and observe the output:

int(‘12345’)

You have just performed type casting - changing of one data type to another data type. The str()

function performs type-casting to strings.

Wait, that explanation only talks about the right hand side of the equals sign ( = ). What does num

mean?

num is a variable. Once it is assigned a value i.e. 12345 , you can refer to this value by the name num

instead of the actual value itself.

The equals sign ( = ) is known as the assignment operator. It does not mean ‘is equal to’ but ‘assign

to’. An assignment statement creates a new variable (LHS of = ) and assigns the value (RHS of = ) to it.

In this case, the value is 12345 and variable is num .

Try running these codes in Python Shell and observe the output:

num = int(‘12345’)

num

Important:

Variables must be initialized before it is used. If you omit the �rst line and proceed to execute

the second line, the computer will raise the exception - NameError. It means that it cannot �nd

the the name num in its memory. There is no syntax errors in this case.

The operation of precedence of any assignment statement is RIGHT to LEFT i.e. expression on

the right hand side is evaluated before it is assign to the variable name.

The results returned by a function can be passed as an input to another function. We have seen this

in action in T1Q3 e.g. print(type(‘example’)) .

The value returned by type(‘example’) is subsequently passed as an input (argument) to print()

function. Another way of writing the codes to produce the same output:

Another implementation

temp = type(5 + 2)

print(temp)

Part 1:

Execute the program hello_again.py . What do you observe?

Open the print() documentation. Read the highlighted text. You will notice assignment operators

within the parenthesis. Remember, items inside the parenthesis are the inputs that you provide when

you use the function. sep , end and file are known as keyword arguments. If no values are

provided during the function call, the default values (those in the documentation) are used during the

function call.

Can you work out the values for: sep , end and file based on the documentation?

For each line in the program:

Which are the non-keyword arguments?

What are the values of sep , end and file ?

Now, read each paragraph. It is �ne if the documentation does not make perfect sense yet but it

should make some sense now to explain the output in the program.

Part 2:

It is important that you work these out on your own before executing the codes on the computer:

How many new lines are displayed on the terminal for the given codes? Explain your answer to

another person.

newlines_again.py

pi_example.py