Unit 4 Flashcards

1
Q

What is the difference between a string variable and a numeric variable?

A

A string is a collection of one or more letters or characters.—> like a word (Letters go into something go into strings). We put quotations marks around it to let Python expect a string. You need to make sure that the quotation marks matches.

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

What is the term for combining strings?

A

Concatenating strings

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

How can you write code that uses Python’s built-in function to get input from the user (prompt the user to enter data) and then process it for use in your programs?

A

To get information from the user, we use a function called input()

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

Let’s say that you have two different variables
Question = …
Response= …
What are the different ways that you can put quotation marks for these two variables?

A

Question= ‘….’
Response=‘…’

Or
Question= “…”
Response=“…”

Or
Question=‘…’
Response=“…”

Or
Question=“…”
Response=‘…’

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

Which of the following is an invalid string according to Python?
my_string =This is an invalid “string”.
my_string=“T”
my_string=‘This is an invalid string.’
my_string=“This is an invalid string.”

A

my_string= This is an invalid “string”.

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

How can we store two jokes in the same variable, but on two different lines?

A

We use multi-line strings. You use three single quotation marks (‘’’) around your string and press enter anytime you want to go onto a new line.
For example:
Joke_1=‘’’What did one ocean say to the other?
They wave!’’’

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

Which of the following correctly creates and prints out a multi-line string?
A:
my_joke=‘What does a computer snack on?
Computer chips!’
print(my_joke)

B:
my_joke=‘’What does a computer snack on?
Computer chips!’’
print(my_joke)

C:
my_joke=‘’’What does a computer snack on?
Computer chips!’’’
print (my_joke)

D:
my_joke= “What does a computer snack on?”
“Computer chips!”
print(my_jokes)

A

C

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

What happens if I need to include a quotation mark inside my string?
For example: ‘Why can’t you give Elsa a balloon?’

A

You will get a syntax error. To prevent getting a syntax error you can either use a triple quotation mark or add a slash \ before the ‘ in can’t to tell Python that it can safely ignore your quotation marks.

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

What is the definition of syntax?

A

Syntax is the arrangement and order of words and commands you use to written your program.

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

Which of the following is an invalid string according to Python?
A:
my_string=‘This isn’t a valid string.’

B:
my_string=‘This isn\’t a valid string.’

C:
my_string=‘’’This isn’t a valid string.’’’

D:
my_string=“ This isn\’t a valid string.”

A

A
Remember you must use three single quotes. (‘’’) or an escape character (\’) to include a quotation mark inside of a string.

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

What should the code be to have this as the output?

When the snow is shaken
From the balsam trees
And they’re cut down
And brought into our bourses

-from “Noel” by Anne Porter

Please use comments for your program

A

Define the poem as a multi-line string using triple quotes (‘’’)

poem=‘’’When the snow is shaken
From the balsam trees
And they’re cut down
And brought into our houses

-from “Noel” by Anne Porter’’’
#Print the poem
print (poem)

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

What is the tool in python you can use to change or add to a string later on?

A

String formatting

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

What is string formatting?

A

We use a set of curly braces {} to indicate where you’ll fill something in later on. It means that when there’s the curly braces, we’re going to be able to add a string later on. That way we can easily change whatever we are going to code.

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

What do we type in order to let Python know what string we want to insert?

A

We use the .format() method on our beginning string. We’ll learn about methods a bit later in the course, but for now, just know that it’s a way we can specify how we want our string to look.

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

How does string formatting help?

A

It makes it more convenient and saves time as we do not have to type the whole beginning out into a new variable now. We could use curly braces to indicate that we wanted to put in or insert the contents of the variable …. And the variable of …

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

Is this statement true or false?
We can only insert one variable into one curly braces for string formatting.

A

True. Each {} holds one variable.

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

How can we insert more than one variable for a single string? State an example.

A

By using multiple pairs of {}

beginning=‘’’Knock knock!
Who’s there?
{}
{} who?’’’
print (beginning.format(joke_1,joke_1))

As you have noticed, you need to type joke_1 twice here to suggest that joke_1 is inserted into the first and second {}

Output:
Knock knock!
Who’s there?
A little old lady
A little old lady who?

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

How do you multiply strings together?

A

I don’t think you can multiply strings together only string with an integer. So depending on the integer, your string woud repeat that number of times. To add “white space” to how your string disposals in Python.

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

For the concept called “white space” is it only for the coding world or the non-coding world?

A

The concept called “white space” is in both the coding world and the non-coding world.

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

What is the meaning of white space?

A

This means space, or room, before or after the other text you’ve written.

Think about a letter you might receive in the mail. Many times, the address line has white space before it to make it line up nicely.

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

What do you use white space for?

A

In Python, as we’ll learn later on, you use white space to indicate when certain sections, or blocks of code are supposed to remain together.

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

Code a program that gives this as the output.
I need some extra space!
Here is some extra space!

A

extra_spaces=‘ ‘ * 10
print(‘{} I need some extra space!’.format(extra_spaces))
print(‘ {} Here is some extra space!’.format(extra_spaces))

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

Which of the following correctly prints exactly 45 white space characters before the text?

A:
extra_spaces = “ * 45”
print(‘ {}Exactly 45 spaces!’.format(extra_spaces))

B:
extra_spaces=‘ ‘ * 45
print( ‘ {}Exactly 45 spaces!’.format (extra_spaces))

C:
extra_spaces= ‘’’’ * 45– two different “
print(‘ {} Exactly 45 spaces!’ .format(extra_spaces))

D:
extra_spaces= ‘’’ * 45’’’
print(‘ {} Exactly 45 spaces!’ .format(extra_spaces))

A

B is the correct answer.

C is incorrect as there is no space between the two double quotation marks. However, if it has a space in between “ “ then it would work.

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

What is a function?

A

A function is a block of organised, reusable code that ideally performs a single action.

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

Code a program that allows you to find out what the user’s name is and then printing that out.

A

First, we use the print() function to ask the name :
print (“What’s your name?”)
name= input()

In this example, we’ve decided to save what our user tells us into a variable named name.
The user will “enter” their name and press enter when they’re finished giving us the information.

If you were to print(name), you would be able to see the name that the person entered.

This allows us to successfully ask the user a question and then store the information they gave us into a variable.

26
Q

The information the user gives us through the input function is going to be stored inside a ______.

A

An important detail to note for now is that the information the user gives us is going to be stored inside a string variable.

27
Q
A

it might not be obvious that you’re asking the user to answer a question.
So, one way that Python makes that easier is by allowing you to put a symbol before the space where the user answers a question. You do this by passing an “argument” to the input() function.

28
Q

What is the category of the input that you get from the user?

A

It is in the form of a string.

29
Q

What is the difference between strings and numbers?

A

Usually, a string will have quotation marks around it like “3” and a number will just be written 3.

30
Q

Look at this code below. Do you think we can do any mathematical operations with it?

string_1=input(“Please enter the first number:”)
string_2=input(“Please enter the second number:”)

A

No, we can’t do any mathematical operations with it because Python doesn’t know they’re numbers

31
Q

What function do we use to tell Python that we want strings to be numbers?

A

int()

32
Q

What function do we use to tell Python that we want numbers to be strings?

A

str ()

33
Q

Create a simple calculator that prompts the user to enter two whole numbers and then calculates and displays their sum.

A

Prompt the user to enter two numbers

first_number=input(“Pick a number:”)
second_number=input(“Pick another number:”)
#Convert the user’s input to integer values for arithmetic
number1=int(first_number)
number2=int(second_number)
#Calculate the sum
answer=number1+number2
#Print the answer
print(“The sum is {}.’’.format(answer))

For the last line the reason why there is a .’’ Is to add a full stop to the line the sum is {}. And the ‘’ is to match the beginning one. Then you also need .format to insert string.

34
Q

What would the output be for this?
first_string= “red”
second_string= “yellow”
complete_string=first_string + second_string
print (complete_string)

A

redyellow

35
Q

How do you add a space between red and yellow based on this code?
first_string= “red”
second_string= “yellow”
complete_string=first_string + second_string
print (complete_string)

A

complete_string= first_string+ “ “ +second_string

36
Q

How do you combine two or more strings together?

A

You use the “+” sign.

37
Q

Can we use “+” sign to combine strings and numbers together?

A

No. You will get an error message (TypeError) stating that you can’t concatenate strings and integers.

38
Q

What should you do if you want to combine a number with a string based on this example:
number= 3
string= “red”
combined= string +number

A

you have to make sure to turn the number into a string first

take note that for this example, you can only turn the number into a string and not the string into a number.

39
Q

my_number=12
my_string_1= “hello”
my_string_2= “goodbye”

Assuming the code above, which of the following would cause an error in Python?

A:
combined= my_number + my_string_1
B:
combined= my_string_1 + “farewell”
C:
combined = my_string_1 + my_string_2
D:
combined= my_string_1 + “12”

A

A

40
Q

There is only one way that you can use the format() method. True or false?

A

False.
String formatting.
There are actually a few additional ways that you can use the format() method with positional arguments and keyword arguments. We’ll talk more in a later unit on what the terms “method”: and arguments” mean, but for now, just know that these are different ways of giving the format() command information.

41
Q

my_string= ‘ {0} is {1} years old.’
print(my_string.format(‘Mary’, 12))

Is this positional arguments with format() or keyword arguments with format()? Why?

A

Positional arguments with format()

When you use positional arguments, Python will substitute in the values in numerical order, starting at 0. In this example, the string ‘Mary’ is in the 0 position and the number 12 is in the 1 positions, so those are substituted in the string. Here’s the output of the code with the corresponding values substituted in:

Mary is 12 years old.

42
Q

Is it true that you can add as many arguments as you would like for positional arguments with format()? Give an example and state it’s output.

A

Yes. You could even extend it to be something like this:
my_string=‘{0} is {1} years old and she is in {2} grade. Her favourite subject is {3} and she likes to ride {4}.’
print (my_string.format(‘Mary’,’12,’7th’,’Python’, ‘bikes’))

Here’s the output of the code with the corresponding values substituted in:
Mary is 12 years old and she is i the 7th grade. Her favourite subject is Python and she likes to ride bikes.

43
Q

What is keyword arguments with format()?

A

Keyword arguments let you name each {} so that you don’t have to try to remember and match up the values in the correct order. Instead of using numbers inside the curly braces ({}), you use a keyword that describes the information that will go there. Then, when you call the format() method, you include the keywords and the corresponding data

44
Q

What is the output of this?
my_string = ‘{name} is {age} years old.’
print(my_string.format(name=‘Mary’,age=12))

A

Mary is 12 years old.

45
Q

What is number formatting?

A

Number formatting is a technique that uses the format() method to tell Python how many decimal places you want a number to have.

46
Q

What is the output of this?
grade_1= 93
grade_2 =89
grade_3 = 95
average = (grade_1 + grade_2+ grade_3)/3
print(“The average is :{average}. ‘’ .format(average=average))

A

The average is: 92.33333333333333

47
Q

What if we wanted to show only one decimal place in our calculation?
grade_1= 93
grade_2 =89
grade_3 = 95
average = (grade-1 + grade_2+ grade_3)/3
print(“The average is :{average}. ‘’ .format(average=average))

A

print (“The average is: {average:.1f}.”.format(average=average))

Adding this line of code tells Python that we would like it to be to one place value after the decimal point (the .1) and that it contains a floating-point value (the f).

The output will be changed to:
The average is: 92.3

48
Q

What are the two different ways to code something that has this output:
10 divided by 3 is 3.3333333333333335

A
  1. X=10
    Y=3
    _10_divided_by_3= X/Y
    print (“10 divided by 3 is”, _10_dvided_by_3)

Or

  1. X=10
    Y=3
    print (f ’{X} divided by {Y} is {X/Y} ‘ )
49
Q

You have a great YouTube vlog that earns $20,000.00 per year. You would like to display your monthly income in currency format. You can format your output by ___________. The code should be: _________

A

You can format your output by adding a comma (,) as the thousand separators before your number format. The
The code should be:
yearlyIncome= 20000.00
monthlyIncome=yearlyIncome/12
print (f’My monthly income is ${monthlyIncome:,.2f}’)

The output would be:
My monthly income is $1,666.67

50
Q

What does the f-string do?

A

Using f-string, you can display a nicely formatted string output using the letter f or F followed by your string literal within quotation marks. Inside our string literal, you can include variables and /or expressions enclosed by curly brackets, {}. Finally, you print the expression using the print() function.

If you are using Python version 3.6 or later, you can use this f-string technique to display almost all your formatted strings in this course. You can also apply Python’s number formatting rules in f-string to button up your output even more effectively.

f-string also enables you to align text to display our output neatly on the screen. you can sure ^ character to Center, > to right, and < to left align your text.

51
Q

Code something to get this as the output:
Report Card
=======================================
Python for Middle School Students : 95.00
Introduction to Java : 87.00
Algebra I : 92.00
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Average : 91.33%

Explain your code.

A

reportHeading = “Report Card”
double line= “=“
singleLine= “-“
course1= “Python for Middle School Students”
course2= “Introduction to Java”
course3= “Algebra I”
course1Grade=95
course2Grade=87
course3Grade=92

average= (course1Grade+course2Grade+course3Grade)/3.0

print (f ‘ {reportHeading:^60}’)
print (f ‘ {doubleLine * 60} ‘ )
print (f ‘ {course1:<40}{‘’ : ‘’ ^4}{course1grade:>16.2f}’)
print (f ‘ {course2:<40}{‘’ :’’ : ^ 4}{course2Grade:>16.2f}’)
print (f’ {course3:<40}{“:”:^4}{course3Grade:>16.2f}’)
print( f’ {singleLine * 60}’)
print ( f’ {‘’Average” : < 40}{“:”:^4}{average:>15.2f}%’)

Explanation:
The variables are defined, and their value Ds are assigned prior to creating the report. The report width is 60 characters, so the heading is Center aligned using the ^ character within that 60-character space. The heading line is followed by a double bar line created using string multiplication to match the report width. We did not do any string formatting here though. Just for the consistency, we used f-string formatting syntax. Next, we printed the course names, a colon followed by the grade. Note, the course names are 40 characters in width and aligned left using the < character, colons are centre aligned with the width of 4 characters. Finally, the grades are displayed as a floating-point numbers with 2 decimal points and right aligned using > character. The following two lines are printed using the same formatting rule discussed above.

52
Q

Numbers can be formatted using _____ after the variable or expression followed by the alignment character, ___ for thousands separator, decimal point and the desired number of places, and the data type.

A

First blank: Using a colon (:)
Second blank: comma (,)

53
Q

What are some stuff that you need to take note for string manipulation?

A

Summary:
Remember to use the quotation marks around a string and make sure that starting and ending quotation marks match.
Use triple quotes whenever you have a quotes or apostrophes inside of your string. You can also use a backslash() to escape quotation characters inside of your string.
Convert float to an integer before multiplying it with a string since multiplication between a string and float is not supported in Python.
Remember to specify values for each {} placeholder in the string when using the format() method.
Remember to convert all user input using int() or float() before doing arithmetic.

54
Q

Can you multiply a string with an integer?

A

Yes it is allowed. For example:
print (“Python” * 3)

55
Q

Can you add a string with a string?

A

Yes, it is allowed.
For example:
print (“Hello” + “World”)

56
Q

Can you add a string with a number?

A

It is not allowed, unless you convert the number to a string.

57
Q

Can you subtract a string form a string?

A

No, it is not allowed.
you will get a TypeError

58
Q

Can you convert a string into a number?

A

yes, you can convert a string into a number– but only if the string contains a valid numeric value.

For example:
num_str= “42”
num= int(num_str)
print (num+8)

but if the string does not contain a numeric value, then you will not be able to convert it into a number.

59
Q

What is casting?

A

Casting is the process of converting a variable from one data type to another in programming. This is often necessary when you need to perform operations that require variables to be of the same type.
For example:
Converting to integer int()
Converting to float float()
Converting to string str()

60
Q
A