Chapters 1-20 Flashcards

1
Q

What is the command to create a directory in Powershell?

A

mkdir

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How would you output the text below in a Python print statement.

That’s a ‘piece of cake’ as they say

A

print(“That’s a ‘piece of cake’ as they say”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the command to run Python from Powershell?

A

python

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you write a single line comment in Python?

A

#

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What data type is 4.0

A

It’s a float

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

If we execute the statement

x = 4/2
then what is the datatype of x

A

It’s a float

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

what data type is 4

A

It’s an int

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

what is the % operator called and what does it do

what is the result of 5 % 2

A

It’s the modulo operator and displays the remainder portion of a division

5 % 2 is 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the order of calculation of the following operators

+ - % / * ( ) **

A

P
E
(M&D) left to right
(A&S) left to right

(MD)(AS)The actual order is that you do the multiplication and division in one step, from left to right, then you do the addition and subtraction in one step from left to right.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the exponent operator in Python

A

**

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you round a floating point number in Python (e.g. 1.73)

A

round()

round(1.73) gives the answer 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How can we output a variable in the middle of some text in a print statement

e.g.
my_height = 180

print the statement
my height is (my_height) cms

A

print(f”some text {variable_name} more text”)

print(f”my height is {my_height} cms”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How can we create a string with a variable in it?

A

f-string can be used to do this

e.g text_to_output = f”my height is {my_height} cms”

The text is substituted in when the command is executed - if the variable subsequently updates to a new value, the f-string is not implicitly updated with the new value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How can we create a string with a variable in it that overcomes f string limitation to dynamically update.

A

Every object has a .format method e.g.

hilarious = False
joke_evaluation=”Is that funny? {}”
joke_evaluation.format(hilarious)

=> ‘Is that funny? False’

If hilarious is updated to True then you get

joke_evaluation.format(hilarious)

=> ‘Is that funny? True’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does the following code do

print(“my name is “,end=’’)
print(“Hans Solo”)

A

The end = ‘’ argument will not create an auto LF/CR at the end of the print statement.

The second print statement is on the same line as the first.

e.g.
my name is Hans Solo

is output

Using end = ‘ ‘ or end = ‘,’ would place a space or , at the end of the first print statement or any specified delimiter text

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is output?

welcome_text = “Welcome to {} in the {}”

print(welcome_text.format(“LA”,”USA”))

print(welcome_text.format(“London”,”UK”))

A

Welcome to LA in the USA
Welcome to London in the UK

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the code for the following:

  1. define x = 43 and y = 51
  2. define a variable z to holds the text “You are x degrees of longitude and y degrees of latitude” where x and y are themselves variables
  3. print the value of z
A

x=43
y=45
z=”You are {} degrees longitude and {} degrees of latitude”
print(z.format(x,y))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the escape sequence that prints a new line e.g. how do we split

print(“line 1 line 2”)

line 1 line 2

so that there is a separate line between them when printed

A

The escape sequence for new line is \n (backslash n) so

print(“line 1 \nline 2”) gives

line 1
line 2

as output

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do we print text across multiple lines in a print statement (not using \n)

E.g so we get :

line 1 followed by line 2
in turn followed by line
line 3
finishing at line 4

A

Use “”” in the print statement so

print(“"”line 1 followed by line 2
in turn followed by line
line 3
finishing at line 4”””)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is an escape sequence? and how do you put one into a string?

A

Escape sequences are used in strings for handling difficult-to-type characters.

There are different ways of starting an escape sequence - they can start with single quote - ‘ - double quote - “ - or backslash - .

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How you would you use an escape sequence to print the sentence with a double quote “ escape character

I am 6’2” tall.

A

print(“I am 6’2" tall.”)

escape second double quote inside string

I am 6’2” tall.

The escape character tells Python the second double quote is part of the string

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How you would you use an escape sequence to print the sentence with a single quote ‘ escape character

I am 6’2” tall.

A

print(‘I am 6'2” tall.’)

escape second quote inside string

I am 6’2” tall.

The escape character tells Python the second single quote is part of the string

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How can you put a tab into a line of text with an escape sequence

A

\t

e.g.
“\tI’m tabbed in.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the escape character to allow for text to be accepted as a series of lines

A

””” or ‘’’

e.g.

fat_cat = “””
I’ll do a list:
\t* Cat Food
\t* Fishies
\t* Catnip\n\t* Grass
“””

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What do the following escape sequences do?

\
'
"
\t
\r

A

output a

\ - Backslash ()
' - Single-quote(‘)
" - Double-quote(“)
\t - Horizontal tab
\r - Carriage Return

26
Q

What do the following escape sequences do?

\a
\b
\f
\n
\v

A

output a

\a ASCII bell (BEL)
\b ASCII backspace (BS)
\f ASCII form feed (FF)
\n ASCII line feed (LF)
\v ASCII vertical tab (VT)

27
Q

What do the following escape sequences do?

\uxxxx
\Uxxxxxxxx

A

output a

\uxxxx - character with a 16-bit hex value
\Uxxxxxxxx - character with a 32-bit hex value

print(“hex 16 gives \u0048\u0065\u006c\u006c\u006f”)
print(“hex 32 gives \U00000048\U00000065\U0000006c\U0000006c\U0000006f”)

gives

hex 16 gives Hello
hex 32 gives Hello

28
Q

What doe the following escape sequence do?

\ooo

e.g.

txt = “\110”

A
#A backslash followed by three integers will result in a octal value: 
txt = "\110\145\154\154\157" 
print(txt) 

gives result
Hello

29
Q

What doe the following escape sequence do?

\xhh

e.g.
txt =”\x48”

A
#A backslash followed by an 'x' and a hex number represents a hex value: 
txt = "\x48\x65\x6c\x6c\x6f" 
print(txt) 

gives result
Hello

30
Q

What doe the following escape sequence do?

\N{name}

A

A backslash followed by an ‘N’ and a character named in the Unicode database will output the named character from UniCode

e.g. print(“Here is the card suit for spades \N{BLACK SPADE SUIT}”)

prints spade symbol

Here is the card suit for spades ♠

31
Q

How do we input a value into a variable ?

e.g. complete the next line
print(“What is your age?”, end=’ ‘)

and capture a variable named age

What does end = ‘ ‘ do?

What will the datatype be?

A

age = input()

will prompt for a value and capture it as a string (‘str’)

32
Q

How do we capture a value into a variable and issue a prompt in one command / line of code?

A

a_variable = input(“issue a prompt”)

e.g.
age = input(“How old are you? “)

33
Q

How would you search for python documentation on the input command from within Windows PowerShell

A

python -m pydoc input

34
Q

what is a script in python?

A

It’s simply a .py file

35
Q

what does argv do?

A

argv holds the values of arguments passed in when running a python script

e.g. python ex13.py first 2nd 3rd

use and unpack like this:

from sys import argv
script, first, second, third = argv

note first argument unpacked is the script name and then the arguments passed in

36
Q

What is a module?

A

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

You can name the module file whatever you like, but it must have the file extension .py

37
Q

How do you include a module in your python code?

A

import

e.g. to include functionality from mymodule and use in your script

import mymodule 
mymodule.greeting("Jonathan") 

When using a function from a module, use the syntax: module_name.function_name.

38
Q

How do you create an alias to a module in your code?

A

Use as

e.g. 
import mymodule as mx 

a = mx.person1[“age”]
print(a)

39
Q

What is a built-in module?

A

There are several pre-supplied and built-in modules in Python, which you can import whenever you like.

e.g.
import platform

x = platform.system()
print(x)

40
Q

How do you include only a specified part of a module?

A

You can choose to import only parts from a module, by using the from keyword.

e.g.
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)

person1 = {
“name”: “John”,
“age”: 36,
“country”: “Norway”
}

Import only the person1 dictionary from the module:

from mymodule import person1

print (person1[“age”])

Note: When importing using the from keyword, do not use the module name when referring to elements in the module. Example: person1[“age”], not mymodule.person1[“age”]

41
Q

How do you close a file in Python?

A

use the close() command on your file object e.g.

filename = “myfile.txt”
file_object = open(filename)
txt = file_object.read()
file_object.close()

Closing a file has the same action as File … Save in Windows menu

42
Q

How do you read a a single line of file in Python?

A

use the readline() command on your file object e.g.

filename = "myfile.txt"
file\_handler = open(filename)
txt = file\_handler.readline()

will read and load the contents of the first line of the file into the txt variable

Each time a file_handler.readline() command is issued a line is read from the current seek position until right after the next \n that ends the line.

43
Q

How do you read a file in Python?

A

use the read() command on your file handler e.g.

filename = "myfile.txt"
file\_handler = open(filename)
txt = file\_handler.read()

will read and load the contents of the file into the txt variable

file_handler = open(filename,’r’) does the same thing - option r (read) is the default option

44
Q

How do you open a file in Python?

A

use the open() command and associate it with a file handler that we can then issue futher commands to

e.g.

filename = “myfile.txt”

file_handler = open(filename)

Think of a file handler as being like a DVD player - you can issue command to it to manipulate the DVD as required e.g. open, read, read line, find a position, close

Files can be opened by more than one file handler if needed

45
Q

How do you delete a file?

A

file_handler.truncate()

or open in ‘w’ mode has the effect of truncating (deleting any existing file before writing to a new one).

46
Q

How do you move the read/write location to a specified position in the file and

1 ) print the position in the file

2) read the current line from that position

A

.seek()

.tell()

.readline()

seek moves the file handler to the specified position (byte). tell confirms the current position. readline reads a line from the file and positions the file handler ‘head’ after the \n that ends the line

f = open("GfG.txt", "r")
print(f.read())
f.seek(20) # sets Reference point to twentieth byte
 # index position from the beginning

print(f.tell()) # prints current position

print(f.readline()) # read fron current position until end of line (\n)
f.close()

47
Q

How do you move the read/write location to the beginning of the file

A

file_handler.seek(0)

48
Q

How do you open a file to write to it? Name two methods - one to overwrite and one to add to existing file.

A

file_handler = open(file_to_open,’w’)

w has the effect of truncating deleting any existing file before writing to a new one.

file_handler = open(file_to_open,’a’)

will append and not delete existing file.

49
Q

What is a module in Python?

A

Consider a module to be the same as a code library - it’s a .py script / file containing a set of functions you want to include in your application.

You can write your own modules and/or use the built-in functions (BIFs) supplied by Python.

50
Q

What is a module in Python?

How do we import a module in Python?

Can we import part of a module?

A

A module to be the same as a code library - it’s a .py script / file containing a set of functions you want to include in your application.

e.g. Save this code in a file named mymodule.py

def greeting(name):
 print("Hello, " + name)

To use the module it’s simply import

import mymodule
mymodule.greeting("Jonathan")

Note: When using a function from a module, use the syntax: module_name.function_name.

51
Q

What does the from keyword do?

How would you use it?

A

If we are using a large module with many functions defined in it - we can choose to import only named functions

e.g.

from my_code_library import my_function

from os.path import exists

(os.path is a built in library supplied by Python)

import platform
x = platform.system()
print(x)

52
Q

What can go in a module?

How do you rename a module in your code?

A

A module can contain functions but also variables of all types (arrays, dictionaries, objects etc)

Use as to rename a module and use it in your code (or alternatively reference it direct by module_name.function_name

import mymodule as mx

a = mx.person1[“age”]
print(a)

53
Q

What does the exists command do? and how do you use it?

A

Exists returns True if a file exists based on its name in a string as an argument. It returns False if not.

e.g.

from os.path import exists

file_to_create = input(“file name for new file”)

file_exists_check = exists(file_to_create) # check if file exists

54
Q

What does cat do on the Powershell command line?

A

cat prints the contents of a named file

>cat text.txt

55
Q

How can you create a simple text file from the command line?

A

> echo “This is a test file.” > test.txt

will create a file named test.txt with the content specified

56
Q

What is a function?

A

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

57
Q

How do you code a function in Python?

A

Functions are created using the def keyword followed by brackets for any inputs, then a colon.

After the colon the code to carry out the activity required by the function is written.

e.g.

def my\_function():
 print("Hello from a function")

To call the function it’s

my_function() # will print Hello from a function”

This simple function has no inputs and outputs.

58
Q

How do you pass an unspecified number of arguments into a function (a bit like argv does to scripts)?

A

Use *args as input parameter

def my\_function(\*args) :
# body of function code goes here

*args tells Python to take all the arguments to the function and put them in args as a list (tuple)

This way the function will receive a tuple of arguments, and can unpack and access the items accordingly

59
Q

How would you write a simple function to print the square and cube of an number input to the function?

A
def square\_and\_cube\_it(number):
 print(f"""
 Your number is {number}
 Its square is {number\*\*2}
 Its cube is {number\*\*3}
 """)

square_and_cube_it(4)

gives

Your number is 4
Its square is 16
Its cube is 64

60
Q

Can functions have variables? and what is their scope?

A

Any type of variable can be used in a function. The scope of the variable is local to the function.

Variables that are created outside of a function are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

def int\_and\_ext():
 c = 10
 print("In function local c = ",c)

c = 5
print(“Before function global c = “, c)
int_and_ext()
print(“After function global c = “, c)

gives the following ouput

Before function global c = 5
a*b*c in function is 60
In function local c = 10
After function global c = 5