Programming - DataCamp Basics

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/130

encourage image

There's no tags or description

Looks like no tags are added yet.

131 Terms

1
New cards

What is a Python script, and how is it different from the IPython Shell?

  • A Python script is a file containing Python instructions, usually ending in .py.

  • The IPython Shell lets you execute commands interactively and immediately see their results.




2
New cards

Write Python code that displays Hello World.

print("Hello World")

Strings need quotation marks, and functions such as print() use parentheses.

3
New cards

What is a variable in Python? Create one called age containing 19.

age = 19

A variable is a name referring to a stored value. You can then use a variable later on in calculations:

  • age = variable name

  • = = assignment

  • 19 = assigned value


4
New cards

Question: Are age, Age, and AGE the same variable?

No. Python is case-sensitive.

5
New cards

Explain what an integer is and give three examples.

An integer is a whole number without a fractional part - whole number.


age = 19

temperature = -5

savings = 100

6
New cards

What is a float, and how does it differ from an integer?

A float is used for decimal numbers.


age = 19 # int

height = 1.75 # float

price = 5.0 # float

7
New cards

What is a string, and how do you write one?

A string represents text, written inside single or double quotation marks.


name = "Diana"

message = 'Hello'

number = "123"

8
New cards

What is a Boolean? Create a variable called is_good with the value True.

A Boolean is a data type with two possible values: True and False.

Boolean values do not need quotation marks.


is_good = True



9
New cards

What does the type() function do?

It identifies the data type of a value or variable.


print(type(19))

print(type(1.75))

print(type("Hello"))

print(type(True))


Output:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>


10
New cards

What is the difference between 100 and "100"?


100 # Integer
"100"# String

100 is a number that can be used in mathematical calculations.

"100" is text.

11
New cards

Predict both outputs:


print(5 + 3)

print("5" + "3")

8
53

Why?

  • Integers are added mathematically.

  • Strings are joined together - Joining strings is called concatenation.


12
New cards

What does this code print?

print("Hello" + "World")

And how would you code it, if you wanted space inbetween?

HelloWorld

print("Hello" + " " + "World")

Output: Hello World

13
New cards

What happens when you convert True and False to integers?

print(int(True))

print(int(False))


1

0


True converts to 1, and False converts to 0.

14
New cards

What do int(), float(), str(), and bool() do?

They convert values between data types when conversion is possible.

int("12") # 12

float(5) # 5.0

str(25) # "25"

bool(0) # False

15
New cards

Why doesn't this code print 100?

savings = 100

print("savings")

"savings" is a string, so Python prints the word instead of retrieving the variable's value.


Correct code:

savings = 100
print(savings)

Output: 100

16
New cards

Write code that adds savings = 100 and new_savings = 40, stores the result in total_savings, and prints it.

savings = 100

new_savings = 40

total_savings = savings + new_savings

print(total_savings)


Output:

140


17
New cards

What does None mean in Python?

None represents the absence of a value.

For example:

result = None

The variable exists, but its current value is None.

Important: None is different from 0, False, and an empty string "".

18
New cards

What is a list, and how do you create one?

A list stores multiple values together in a particular order.

  • Lists use square brackets [].

  • Elements are separated by commas.

  • Lists can contain different data types.


numbers = [10, 20, 30]

19
New cards

Can one Python list contain integers, floats, strings, and Booleans?

Answer: Yes.


my_list = ["Diana", 19, 1.75, True]

20
New cards

What is the difference between a list and a set?

A list: Keeps order and allows duplicates.

numbers = [1, 2, 2, 3]


A set: Contains only unique values: 1, 2, and 3.

numbers = {1, 2, 2, 3}

Lists use []; set displays use {}.


21
New cards

Can sets contain values of different data types?

Yes, provided the elements are hashable (unchanging hash value).

my_set = {"Hello", 5, 2.5, True}


22
New cards

What is a nested list? Create one containing two rooms and their areas.


hallway - 11.25

kitchen - 18.0

Answer: A nested list is a list containing other lists.

[[], []] represents a list containing two inner lists.


house = [

["hallway", 11.25],

["kitchen", 18.0]

]

23
New cards

Explain the difference:

a = ["hallway", 11.25, "kitchen", 18.0]

b = [["hallway", 11.25], ["kitchen", 18.0]]

a contains four separate elements.

b contains two elements, and each element is itself a list.

24
New cards

What is indexing in Python, and where does counting begin?

fruits = ["apple", "banana", "orange"]

Indexing means accessing an element using its position.

Python starts counting at 0.


  • Index 0 = "apple"

  • Index 1 = "banana"

  • Index 2 = "orange"


25
New cards

Write code to print "banana" using indexing.

fruits = ["apple", "banana", "orange"]

print(fruits[1])

Use square brackets for indexing!

26
New cards

What does index -1 mean?

numbers = [10, 20, 30, 40]

print(numbers[-1])

It selects the LAST item.

Output: 40


Other examples:

  • [-2] = second from the end

  • [-3] = third from the end


27
New cards

Predict the outputs:


numbers = [10, 20, 30, 40]

print(numbers[0])

print(numbers[2])

print(numbers[-2])

Python counts forward from 0 and backward from -1.


10
30
30


28
New cards

What is list slicing, and what is its syntax?

Slicing selects a range of elements.

my_list[start:end]
  • start is included.

  • end is excluded.


29
New cards

What does this print?

numbers = [10, 20, 30, 40, 50]

print(numbers[1:4])

[20, 30, 40]


30
New cards

Write code to select the first six elements of areas.

areas[:6]

This selects indexes: 0, 1, 2, 3, 4, 5

31
New cards

How do you select the last four elements of a list?

areas

areas[-4:]

  • -4 begins four elements from the end.

  • No ending index means continue to the end.


32
New cards

How do you select indexes 100 through 110, including index 110?

numbers[100:111]


33
New cards

What does this expression select?

numbers[:]

It selects all elements from beginning to end.

34
New cards

What does house[0][1] mean?


house = [

["hallway", 11.25],

["kitchen", 18.0]

]

It selects 11.25.

Step by step:

  1. [0] selects the first inner list.

  2. [1] selects the second element inside that list.


35
New cards

What does this print?

animals = [["cat", 2], ["dog", 5]]

print(animals[1][0])

dog
  • [1] selects ["dog", 5].

  • [0] selects "dog".


36
New cards

How do you replace an existing list element?

numbers = [10, 20, 30]

You want to replace 20 with 99.

Select the element using its index and assign a new value.

list[index] = new_value

numbers[1] = 99

Output: [10, 99, 30]

37
New cards

Why is this incorrect?

areas[-1 = 10.50]


The assignment must happen after the closing square bracket.

Correct:

areas[-1] = 10.50

This changes the final element to 10.50.

38
New cards

How can you replace several list elements at once?

numbers = [10, 20, 30, 40]

You want to exchange the numbers 22 and 30 with 99 and 88.

Use slice assignment.

numbers[1:3] = [99, 88]

Result: [10, 99, 88, 40]

39
New cards

What happens when you use + between two Python lists?

a = [1, 2]

b = [3, 4]

print(a + b)

Python joins the lists into one new list = concatenation. + joins lists without changing the original list.

[1, 2, 3, 4]


40
New cards

Add a poolhouse and its area of 24.5 to an existing list called areas, storing the result in areas_1.



areas_1 = areas + ["poolhouse", 24.5]



41
New cards

How do you delete an element from a list?

numbers = [10, 20, 30]

You want to delete 20 from the list.

del numbers[1]


[10, 30]

42
New cards

What happens here?

numbers = [10, 20, 30, 40, 50]

del numbers[1:3]

[10, 40, 50]

43
New cards

What happens to list indexes when you delete an element?


numbers = [10, 20, 30, 40]

del numbers[1]

Elements after the deleted element shift left by one position.

Now the list is [10, 30, 40].

The number 30, previously at index 2, is now at index 1.

44
New cards

How do you add one element to the end of a list?

numbers = [10, 20, 30]

You want to add 40 at the end of the list.

Use .append() it changes the original list.

numbers.append(40)

print(numbers)

[10, 20, 30, 40]


45
New cards

What is the difference between .append() and + when working with lists?


  • a = [1, 2]

  • a.append(3)


  • b = [1, 2]

  • c = b + [3]


Changes a to [1, 2, 3].


Creates c = [1, 2, 3], while b remains [1, 2].


.append() changes the original list; + creates a new list.

46
New cards

What does the .remove() list method do?

numbers = [10, 20, 20, 30]

You want to get rid of the number 20.

It removes the first element whose value matches the argument.

numbers.remove(20)

Result: [10, 20, 30]

47
New cards

What is the difference between .remove() and del?

numbers = [10, 20, 30]

You want to get rid of the number 20.

numbers.remove(20) removes the element with value 20.

del numbers[1] removes the element at index 1.



Merke: .remove() uses a value; del uses an index or slice.

48
New cards

What happens when you call .reverse() on a list?

numbers = [10, 20, 30]


It reverses the order of the existing list and changes the original list.

numbers.reverse()

print(numbers)

[30, 20, 10]


49
New cards

What happens here?

x = [10, 20, 30]

y = x

y[0] = 99

print(x)

[99, 20, 30]

Both x and y refer to the same list in memory.

Changing the list through y also affects what you see through x.

50
New cards

How do you copy a list without sharing the same outer list object?

original = [10, 20, 30]

copy = list(original)


Now you can replace elements in copy without changing original.

51
New cards

How do you make a copy using slicing?

original = [10, 20, 30]

copy = original[:]

[:] selects all elements and creates a new outer list.

52
New cards

Explain the difference between these three statements.

b = a

b = list(a)

b = a[:]

  • b = a makes both variables refer to the same list.

  • b = list(a) creates a new list.

  • b = a[:] also creates a new list.


Assignment is not the same as copying. (?)

53
New cards

Why might changing an inner list affect the original after copying with [:]?

a = [[1, 2], [3, 4]]

b = a[:]

b[0][0] = 99

print(a)

Because [:] creates a shallow copy: the outer list is new, but inner mutable objects are still shared.


Output: [[99, 2], [3, 4]]

A shallow copy does not independently copy nested lists.

54
New cards

What is a function in Python, and why do we use functions?

A function is reusable code that performs a particular task.

For example:

print("Hello")

Here, print() is a function that displays information.

55
New cards

How do you call a Python function?

function_name(arguments)

56
New cards

What is an argument in a function call?

An argument is a value you provide to a function.

print("Hello")

"Hello" is the argument.

57
New cards

What does the len() function do?

numbers = [10, 20, 30]

Counts the number of elements in a collection, or the number of characters in a string.


print(len(numbers))

Output: 3

58
New cards

How do you find the largest number in a list?

numbers = [10, 50, 20]

Use max().


print(max(numbers))

Output: 50


59
New cards

What does round() do?

With the the number: 1.68

print(round(1.68, 1))

Output: 1.7


The first argument is the number.

The second argument specifies how many decimal places to keep.

Merke: round(number, ndigits)

60
New cards

What happens when you call round() without specifying the number of decimal places?

With the the number: 1.68

Python rounds to the nearest integer according to its rounding rules.

print(round(1.68))

2


61
New cards

How can you find information about how a Python function works?

Let´s say the function pow.

help(pow)

or

?pow



62
New cards

What does this code calculate?

print(pow(2, 3))

23 = 8

pow(base, exp) raises the base to the exponent.

63
New cards

In the signature pow(base, exp, mod=None), what does mod=None tell you?

Answer: mod is optional, since it says “None”.


  • base is required.

  • exp is required.

  • mod can be omitted.



64
New cards

Predict the output:


print(pow(2, 3, 5))

3
  1. 23 = 8

  2. Remainder when dividing 8 by 5.

  3. The remainder is 3.



65
New cards

How do you sort numbers from smallest to largest?

numbers = [5, 2, 9, 1]

print(sorted(numbers))

By default, sorted() sorts in ascending order and returns a new list.


Output: [1, 2, 5, 9]

66
New cards

How do you sort a list from largest to smallest?


numbers = [5, 2, 9, 1]

print(sorted(numbers, reverse=True))

Output: [9, 5, 2, 1]

67
New cards

Write code to combine two lists and sort the result in descending order.


a = [5, 10]

b = [3, 20]

full = a + b

full_sorted = sorted(full, reverse=True)

print(full_sorted)

Output: [20, 10, 5, 3]

68
New cards

What is the difference between a function and a method?

A function is called by its name; a method is called on an object using dot notation.


print(numbers)

numbers.append(10)


69
New cards

What is an object in Python?

An object is a value with a type and associated behavior.


name = "Diana"

numbers = [10, 20]


The string and list are both Python objects.

Different types provide different methods.

70
New cards

How do you find the position of a particular value in a list?

numbers = [10, 20, 30]

You want to find 20.

print(numbers.index(20))

Output: 1


.index() returns the index of the first matching element.

71
New cards

How do you count how many times a value appears?

numbers = [10, 20, 20, 30]

print(numbers.count(20))

Output: 2



.count() counts occurrences, not positions.

72
New cards

Predict both outputs:


numbers = [5, 10, 5, 20]
print(numbers.index(5))
print(numbers.count(5))


0
2

.index(5) finds the first position of 5.

.count(5) counts its total occurrences.

73
New cards

What does .upper() do to a string?

place = "poolhouse"

It returns an uppercase version of the string.

print(place.upper())

Output: POOLHOUSE


The original string remains unchanged.

74
New cards

Predict the output:

name = "diana"

print(name.capitalize())

Diana


75
New cards

How do you replace text inside a string?

word = "hello"

You want to replace the ”h” with a “j”.

print(word.replace("h", "j"))


Output: jello


.replace() returns a new string rather than modifying the original string.

76
New cards

How many times does "o" appear in "poolhouse", and how does Python calculate it?


place = "poolhouse"

print(place.count("o"))

Output: 3



77
New cards

Why is this wrong?


numbers = [10, 20, 30]
print(index(20))


.index() is a method called on the list.


print(numbers.index(20))

Output: 1


Merke: object.method(argument)

78
New cards

Can you use every method on every Python data type?

No. Available methods depend on the object's type.


numbers = [1, 2]

numbers.append(3)


Works because .append() is a list method.

But "hello".append("!") raises an error because strings don't have .append().

79
New cards

What's the difference between installing and importing a Python package?

Installing makes the package available in your Python environment.

Importing makes it available for use in the current program.


Terminal:

python -m pip install numpy


Python:

import numpy


80
New cards

How do you import the math module and access π?

import math
print(math.pi)


81
New cards

How do you import only pi from math?

from math import pi
print(pi)

You can now use pi directly without writing math.pi.


Merke: from module import name

82
New cards

What does as mean in an import statement?

You want to import numpy with the name np.

It gives the imported package or function another name. as creates an alias (when multiple variables point to the exact same object in memory.)


import numpy as np
np.array([1, 2, 3])


83
New cards

Must you write import numpy as np instead of import numpy?

No. Both are valid.

84
New cards

How can you import inv from scipy.linalg and call it my_inv?

from scipy.linalg import inv as my_inv

Merke: from module import function as nickname

85
New cards

Why is this wrong?

np = import(numpy)

import is a Python statement, not a function called with parentheses.


Correct:

import numpy as np


86
New cards

What is a NumPy array, and how is it different from a normal Python list?

A NumPy array is a data structure for storing values and performing efficient operations on them.


Python list: numbers = [10, 20, 30]

NumPy array: np_numbers = np.array([10, 20, 30])



87
New cards

Convert a Python list called baseball into a NumPy array called np_baseball.

import numpy as np
baseball = [180, 215, 210]
np_baseball = np.array(baseball)
  • np.array() creates a NumPy array.

  • baseball is the original list.

  • np_baseball refers to the new array.


88
New cards

What does this output mean?

<class 'numpy.ndarray'>


It means the variable contains a NumPy array.


  • class = Python object type

  • numpy = package

  • ndarray = N-dimensional array


89
New cards

How do you check whether np_baseball is a NumPy array?

print(type(np_baseball))


Output: <class 'numpy.ndarray'>

90
New cards

What happens when you multiply a NumPy array by 2?

numbers = np.array([10, 20, 30])


print(numbers * 2)

Every element is multiplied by 2.


Output: [20 40 60]

91
New cards

Predict the results:


a = [1, 2, 3]

b = np.array([1, 2, 3])

print(a * 2)

print(b * 2)

Output:

[1, 2, 3, 1, 2, 3]
[2 4 6]
  • A Python list multiplied by 2 repeats its elements.

  • A NumPy array multiplied by 2 multiplies each number.


92
New cards

Predict the output:

a = np.array([1, 2, 3])

b = np.array([4, 5, 6])

print(a + b)

[5 7 9]


  • 1 + 4 = 5

  • 2 + 5 = 7

  • 3 + 6 = 9

Merke: Array addition is element-wise when the shapes are compatible.

93
New cards

What happens when NumPy combines Booleans and integers?


numbers = np.array([True, 2, False])

print(numbers)

In this situation, NumPy converts the Boolean values into integers. True becomes 1, and False becomes 0.


[1 2 0]

94
New cards

Predict the output:


a = np.array([True, 1, 2])

b = np.array([3, 4, False])

print(a + b)

Output: [4 5 2]


  1. First, convert the Booleans:[1, 1, 2] + [3, 4, 0]

  2. Then add matching positions: [4, 5, 2]


95
New cards

Can a standard NumPy array contain different data types like a normal list?

A standard NumPy array normally has one common data type.


a = np.array([1, 2.5, 3])


  • NumPy converts the integers to floats.

  • NumPy commonly converts mixed input values to a shared type.

  • The array becomes:


[1. 2.5 3. ]

96
New cards

How do you select the element at index 50 from np_weight_lb?

print(np_weight_lb[50])


NumPy uses square brackets for indexing, just like Python lists.

97
New cards

How do you select indexes 100 through 110, including index 110, from np_height_in?

print(np_height_in[100:111])

Slicing works the same way as with regular Python lists.

98
New cards

Write code to convert an entire array of heights from inches to meters.

heights: 70, 72, 74

formula from m to in: *0.0254

np_height_in = np.array([70, 72, 74])
np_height_m = np_height_in * 0.0254
print(np_height_m)

Output:

[1.778  1.8288 1.8796]


99
New cards

What is a two-dimensional NumPy array?

How many rows and colums does this array have:


data = np.array([

[180, 78],

[190, 85],

[175, 72]

])

  • A 2D NumPy array organizes data into rows and columns, similar to a table.

  • This array has 3 rows and 2 columns.


100
New cards

What does this code display?


data = np.array([

[180, 78],

[190, 85],

[175, 72]

])

print(data.shape)

(3, 2)

This means:

  • 3 rows

  • 2 columns


Merke: .shape describes the dimensions of a NumPy array.