• ¿Documento equivocado? Cámbialo gratis
  • Escrito por estudiantes que aprobaron
  • Inmediatamente disponible después del pago
  • Leer en línea o como PDF
Vender
¿Dónde estudias?
Tu idioma
Document preview thumbnail
Vista previa 4 fuera de 36 páginas
Examen

Data C8 Lab 2: Data Types | Spring 2025, Complete Solutions

Document preview thumbnail
Vista previa 4 fuera de 36 páginas

Data C8 Lab 2: Data Types | Spring 2025, Complete Solutions

Vista previa del contenido

Lab 2: Data Types
Welcome to Lab 2!

Last time, we had our first look at Python and Jupyter notebooks. So far, we've only used Python to manipulate
numbers. There's a lot more to life than numbers, so Python lets us represent many other types of data in
programs.

In this lab, you'll first see how to represent and manipulate another fundamental type of data: text. A piece of
text is called a string in Python.

You'll also see how to invoke methods. A method is very similar to a function. It just looks a little different
because it's tied to a particular piece of data (like a piece of text or a number).

Last, you'll see how to work with datasets in Python -- collections of data, like the numbers 2 through 5 or the
words "welcome", "to", and "lab".



Initialize the OK tests to get started.


In [2]: from client.api.notebook import Notebook
ok = Notebook('lab02.ok')
_ = ok.auth(inline=True)



Deadline: If you are not attending lab physically, you have to complete this lab and submit by Wednesday, 1/24
9:59am in order to receive lab credit. Otherwise, please attend the lab you are enrolled in, get the check-off with
your (u)GSI or learning assistant AND submit this assignment by the end of the lab section (with whatever
progress you've made) to receive lab credit.

Submission: Once you're finished, select "Save and Checkpoint" in the File menu and then execute the submit
cell below (or at the end). The result will contain a link that you can use to check that your assignment has been
submitted successfully.


In [ ]: _ = ok.submit()

,1. Review: The building blocks of Python code
The two building blocks of Python code are expressions and statements. An expression is a piece of code that

is self-contained, meaning it would make sense to write it on a line by itself, and
usually has a value.

Here are two expressions that both evaluate to 3

3
5 - 2


One important form of an expression is the call expression, which first names a function and then describes its
arguments. The function returns some value, based on its arguments. Some important mathematical functions
are

Function Description

abs Returns the absolute value of its argument

max Returns the maximum of all its arguments

min Returns the minimum of all its arguments

pow Raises its first argument to the power of its second argument

round Round its argument to the nearest integer


Here are two call expressions that both evaluate to 3

abs(2 - 5)
max(round(2.8), min(pow(2, 10), -1 * pow(2, 10)))


All these expressions but the first are compound expressions, meaning that they are actually combinations of
several smaller expressions. 2 + 3 combines the expressions 2 and 3 by addition. In this case, 2 and 3
are called subexpressions because they're expressions that are part of a larger expression.

A statement is a whole line of code. Some statements are just expressions. The expressions listed above are
examples.

Other statements make something happen rather than having a value. After they are run, something in the world
has changed. For example, an assignment statement assigns a value to a name.

A good way to think about this is that we're evaluating the right-hand side of the equals sign and assigning it
to the left-hand side. Here are some assignment statements:

height = 1.3
the_number_five = abs(-5)
absolute_height_difference = abs(height - 1.688)

,A key idea in programming is that large, interesting things can be built by combining many simple, uninteresting
things. The key to understanding a complicated piece of code is breaking it down into its simple components.

For example, a lot is going on in the last statement above, but it's really just a combination of a few things. This
picture describes what's going on.




Question 1.1. In the next cell, assign the name new_year to the larger number among the following two
numbers:

1. the absolute value of 25 11
− 2
1
− 2 , and
2. 5 × 13 × 31 + 2.

Try to use just one statement (one line of code).


In [2]: new_year = max(abs(2**5 - 2**11 - 2 ** 1), 5*13*31 + 2) #SOLUTION
new_year

Out[2]: 2018


Check your work by executing the next cell.

, In [6]: _ = ok.grade('q11')

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Running tests

---------------------------------------------------------------------
Test summary
Passed: 1
Failed: 0
[ooooooooook] 100.0% passed




2. Text
Programming doesn't just concern numbers. Text is one of the most common types of values used in programs.

A snippet of text is represented by a string value in Python. The word "string" is a programming term for a
sequence of characters. A string might contain a single character, a word, a sentence, or a whole book.

To distinguish text data from actual code, we demarcate strings by putting quotation marks around them. Single
quotes ( ' ) and double quotes ( " ) are both valid, but the types of opening and closing quotation marks must
match. The contents can be any sequence of characters, including numbers and symbols.

We've seen strings before in print statements. Below, two different strings are passed as arguments to the
print function.


In [7]: print("I <3", 'Data Science')

I <3 Data Science


Just like names can be given to numbers, names can be given to string values. The names and strings aren't
required to be similar in any way. Any name can be assigned to any string.


In [8]: one = 'two'
plus = '*'
print(one, plus, one)

two * two


Question 2.1. Yuri Gagarin was the first person to travel through outer space. When he emerged from his
capsule upon landing on Earth, he reportedly (https://en.wikiquote.org/wiki/Yuri_Gagarin) had the following
conversation with a woman and girl who saw the landing:

The woman asked: "Can it be that you have come from outer space?"
Gagarin replied: "As a matter of fact, I have!"


The cell below contains unfinished code. Fill in the ... s so that it prints out this conversation exactly as it
appears above.

Información del documento

Subido en
17 de abril de 2025
Número de páginas
36
Escrito en
2024/2025
Tipo
Examen
Contiene
Preguntas y respuestas
$27.99

¿Documento equivocado? Cámbialo gratis Dentro de los 14 días posteriores a la compra y antes de descargarlo, puedes elegir otro documento. Puedes gastar el importe de nuevo.
Escrito por estudiantes que aprobaron
Inmediatamente disponible después del pago
Leer en línea o como PDF

Seller avatar
Los indicadores de reputación están sujetos a la cantidad de artículos vendidos por una tarifa y las reseñas que ha recibido por esos documentos. Hay tres niveles: Bronce, Plata y Oro. Cuanto mayor reputación, más podrás confiar en la calidad del trabajo del vendedor.
Jumuja
3.9
(121)
Vendido
594
Seguidores
417
Artículos
2987
Última venta
23 horas hace




Por qué los estudiantes eligen Stuvia

Creado por compañeros estudiantes, verificado por reseñas

Calidad en la que puedes confiar: escrito por estudiantes que aprobaron y evaluado por otros que han usado estos resúmenes.

¿No estás satisfecho? Elige otro documento

¡No te preocupes! Puedes elegir directamente otro documento que se ajuste mejor a lo que buscas.

Paga como quieras, empieza a estudiar al instante

Sin suscripción, sin compromisos. Paga como estés acostumbrado con tarjeta de crédito y descarga tu documento PDF inmediatamente.

Student with book image

“Comprado, descargado y aprobado. Así de fácil puede ser.”

Alisha Student

Preguntas frecuentes