Python & Data Structures Flashcards

1
Q

Variables

A

Python has no keyword for declaring a variable and the data type doesn’t have to be specified as well. It is automatically inferred from the value you specify:

A variable is created the moment you first assign a value to it. Python is a dynamically typed language and this is a consequence of that:

x = 4    # x is of type int
y = "Sally"    # y is now of type str
print (type (x), type (y) )
#output: ‹class 'int'> class 'str'>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Type Keyword

A

The built-in function type() returns the type of an object. In Python 3, everything is an object and thus an instance of a class. Therefore, the built-in function type() can be used to return the class type of the passed variable

Example:

type (5)
#output: <class "int'>
type( "hello" )
#output: <class 'str'>
type( {"age": 3})
#output: <class 'dict'>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

For Loops

A

The for loop is used to iterate through the members of a sequence (lists and string) or any iterable object (dictionaries and sets).

Loop continues until we reach the last item in the sequence. The body of a for loop is separated from the rest of the code using indentation.

Lists:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
print (x)
#output: apple banana cherry

Strings:

for x in "banana":
    print (x)
#output: b a n a n a

Range Functions:

for x in range(6):
    print (x)
#output: 0 1 2 3 4 5

Dictionaries:

d = ['x': 1, 'y': 2, 'z': 3}

for key, value in d. items():
    print(key, value)
#output
#x 1
#y 2
#z 3
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly