Python Exam 2

0.0(0)
studied byStudied by 0 people
0.0(0)
full-widthCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/57

flashcard set

Earn XP

Description and Tags

Week 6-10 strings, functions, dictionaries

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

58 Terms

1
New cards

strings

sequences of characters (words, sentences, symbols)

written with single (' ') , double (" ") quotes or triple quotes.

Strings can be stored in variables, or printed

2
New cards

triple quotes

""" ... """

used for multiline strings

3
New cards

multi line strings

Use triple quotes (""" ... """) for multi-line strings.

● Easier for long text or formatted stories.

● For typing a long string, it’s sometimes best to type the string across multiple lines (also

known as line breaks) so that the string is easier to read in the program

4
New cards

escape characters

let us include special symbols (apostrophes, quotes, new lines,)

inside strings.

Handle special characters inside strings without causing errors

a backslash followed by the character we

want to use

5
New cards

\n

new line

6
New cards

f strings

used to insert variable values directly. (format: f"This is a variable {variable}.")

7
New cards

+

Concatenation combines strings using the + operator

8
New cards

capitalize()

capitalize first letter

9
New cards

replace()

print(input.replace('x', 'y'))

replace parts of string

replaces x with y

10
New cards

len()

count characters

11
New cards

upper()

convert to uppercase

12
New cards

lower()

convert to lowercase

13
New cards

strip()

remove extra characters/spaces

14
New cards

title()

capitalize each word

15
New cards

{#:.2f}

prints number to 2 decimal places in f string

16
New cards

<

print(f"{'x':<#}")

left-aligned

17
New cards

>

print(f"{'x':>#}")

right-aligned

18
New cards

^

print(f"{"x":^#}")

centered

19
New cards

d for int, f for float, s for string

type format

20
New cards

endswith(suffix)

Returns True or False depending on whether the string ends with the given suffix

21
New cards

join(sequence)

Joins the sequence of strings into one string, using the “called-on” string as the separator

22
New cards

split(sep, [maxsplit=-1])

Splits a string into a list of substrings, using the given separator.

23
New cards

find(sub, [start, [end]])

Returns the index (position) where substring sub can be found in the string. Returns -1 if not found

24
New cards

center(width, [fillchar])

Centers the string between the given fill characters

25
New cards

isalnum()

returns whether the string is all alphanumeric (both letters and numbers)

returns True or False

26
New cards

isalpha()

returns whether the string is all alphabetic

returns True or False

27
New cards

isdigit()

returns whether the string is all digits

returns True or False

28
New cards

islower()

returns whether the string is all lowercase

returns True or False

29
New cards

isupper()

returns whether the string is all uppercase

returns True or False

30
New cards

rfind(sub, [start, [end]])

Returns the index where substring sub can be found in the string, searching from right to left.

Returns -1 if not found.

31
New cards

startswith(prefix)

Returns whether the string starts with the given prefix

True or False

32
New cards

alternate form

print(f"{10:#b}") # '0b1010' (binary with prefix)

print(f"{10:#x}") # '0xa' (hexadecimal with prefix)

print(f"{10:#o}") # '0o12' (octal with prefix)

33
New cards

abs()

Computes the absolute value (numerical).

34
New cards

pow()

power = pow(x,y)

Computes the first value raised to the power of the second value

raises x to the power of y

35
New cards

lambda

keyword that defines the anonymous function

quick, temporary ("throwaway") function — something

short enough to write in one line and not meant to be reused elsewhere

36
New cards

objects

(complex types like lists):

→ Only a pointer/reference is stored; the actual data lives in memory (heap).

→ Functions can modify these objects

37
New cards

primitive type

int, float, bool, str

→ Values stored directly in memory

38
New cards

add = lambda x,y: x+y

print(add(#,#)

lambda example adding

39
New cards

function body

contains whatever actions you

choose to have your function complete

40
New cards

call function

function()

To call a function, write its name followed by parentheses

41
New cards

return

statement to end a function, at the end of the actions within the function body,

which can include an expression/ optionally send a value back

42
New cards

parameter

lets you pass data/values into a function.

Values you pass when calling the function are arguments; Python takes the arguments and

assigns them to the variables named by the parameters

43
New cards

dictionary

a list of named values, which means that each item in the list consists of a key

and a value, often referred to as a key-value pair

Keys must be unique in the dictionary and can be quoted strings, numbers, or tuples.

Each key can have any value of any type. The items inside a dictionary are separated by

commas

uses curly brackets {}

44
New cards

dictionary = {key : value, key : value}

dictionary format

45
New cards

print(dictionary[key])

The value of the keys inside a dictionary can be accessed by referencing the key name using

brackets.

46
New cards

dictionary[key] = value

Add an item by referencing a new key and assigning its value

47
New cards

pop(), popitem(), del

three ways to remove items from a dictionary

48
New cards

dictionary.pop(‘x’)

removes x from dictionary

49
New cards

popitem()

removes last item

50
New cards

for key in dictionary:

print(key)

Print all keys in dictionary using for loop

51
New cards

for value in dictionary:

print(dictionary[value]:

print all values in dictionary using for loop

52
New cards

for x in dictionary.values():

print(x)

print all values in dictionary

53
New cards

for x, y in dictionary.items():

print(x, y)

print all key:alue pairs in a dictionary using for loop

54
New cards

dictionary = { “nested1”: { key1: value1, key2: value2},

“nested2” : { key3: value3, key4: value4}}

nested dictionary format

55
New cards

print(dictionary["nested"]["key"])

Access items in a nested dictionary

56
New cards

dictionary["nested"]["key"] = "value"

Add item in a nested dictionary:

57
New cards

for key, value in dictionary.items():

print(key, value)

loop through nested dictionary

58
New cards

dictionary = {}

for i in range(2):

key = input(" enter:")

value = int(input("enter:"))

dictioanry[key] = value

adds input to a dictionary loop for 2 rounds