Python Flashcards

1
Q

How to run a python file?

A

Navigate to file location in terminal. run “python file.py”

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

What’s a variable in Python?

A

Variables are labels. They reference a value.

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

What are the rules for naming variables in Python?

A
  • They can only contain letters, numbers, and underscore
  • They can start with a letter or an underscore, but not a number
  • Spaces are not allowed in variables
  • Avoid using Python keywords such as print or class
  • Variables should be short and descriptive
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What’s a string in Python?

A

In programming, programs collect data and do something with them. Since they are different types of data, it helps to differentiate the different types.

A string is a data type. A string is a series of characters. Anything inside a single or double quote is a string.

Examples of string:

  • “this is a string”
  • ‘this is a string’
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the string method title do in Python?

A

It capitalizes each first letter of a string

```python
name = “james leveille”
print(name.title())
~~~

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

What is the string method upper do in Python?

A

upper case a string
name.upper()

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

What is the string method lower do in Python?

A

It lower case a string
name.lower()

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

How to use variables in a string in Python?

A

By using the f keyword to format the string.

print(f”{fName} {lName}”)

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

How to add a tab in a string in Python?

A

\t
print(“\tname”)

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

How to add a new line in a string in Python?

A

\n
print(“\nname”)

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

How to remove write space from a string in Python?

A

name = “ James “
// remove left whitespace
name.lstrip()
// remove right whitespace
name.rstrip()
// remove left and right whitespace
name.string()

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

How to remove a part of string from a string in Python?

A

remove prefix

name = “James”
name.removeprefix(“Ja”)
# remove suffix
name.removesufix(“es”)

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

What’s a list in Python?

A

A list is a way of storing a list of items. Square brackets ([]) are used to create a list. Lists in python are zero index-based. You can access them by passing an index.

bicycles = ['trek', 'cannondal', 'redline', 'spcialized']

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

How do you access an element of a list in Python?

A

bicycles[0]

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

How do you access the last element of a list?

A

you can use Python special syntax bicycles[-1]. If you pass -1, python will return the last element in the list. -2 return the second item from the end and so forth

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

How do you modify an element in the list in Python?

A

Just set the data using the indexbicycles[0] = “LUKI”

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

How do you add an element to a list in Python?

A
  • You can append the element to the end of the list. bicycles.append('ducati')
  • You can also insert the element at a certain position bicycles.insert(0, 'ducati') This will insert the new element and shift the rest of the list
18
Q

How do you remove an item from a list in Python?

A
  • You can use del to delete an element given its index. For example, del bicycles[0] will delete the first element of the list. If the index is not found, it will throw an out of index error
  • pop is another way you can remove an item from the list. Pop removes the last element of the list and returns the value.
    popped_item = bicycles.pop()
19
Q

How do you remove an item from the list given the value in Python?

A

You remove an item if you know the value by calling the remove method on the list. bicycles.remove(‘ducati’). This will remove the first occurrence of that value.

20
Q

How to sort a list in Python?

A
  • sort - this will sort the list permanently.
    bicylces.sort()
  • sorted - sorted is a function that you can call on your list to sort it.
    newList = sorted(bicycles)
21
Q

How do you loop through a list in Python?

A

bicylces = ["ice", "looki", "pit", "brake"]

```python
for bike in bicycles:
print(bike)
~~~

The colon (:) is required.

The line after the : must be indented

22
Q

How do you loop through a list of numbers in Python?

A

range (k, n) - is use to iterate over a list start at k through n-1

range (n) - is use to iterate over a list start at 0 through n-1

```python
for value in range(1, 5):
print(value)
~~~

23
Q

How do you access the last item of a list?

A

players = [“john”, “luke”, “peter”]. print(players[-1]will print peter

24
Q

How do you convert a range to a list?

A

list = list(range(0, 4)). This will return [0, 1, 2, 3] because list converts a range to a list.

25
Q

How do you generate a subset of a list using range in Python?

A

```python
players = [‘charles’, ‘martina’, ‘michael’, ‘florence’, ‘eli’]
print(players[0:3])
# or
print(players[:3] # start from the beginning of the list
~~~

26
Q

How do you copy a list from another list in Python?

A

```python
players = [‘charles’, ‘martina’, ‘michael’, ‘florence’, ‘eli’]
copied_players = players[:]
~~~

27
Q

What is a Tuple in Python and why use it?

A

A tuple allows you to create a list that is immutable (can not change).

Here is how you define a tuple dimensions = (200, 50)

Here is how you access it. print(dimensions[0])

If you were trying to change this value, Python will throw an error dimensionsp[0] = 123. This will throw an error.

28
Q

How do you create an if statement in Python?

A

if car == “bmw” :
print(car.upper())

if car == “audi” and age >= 21:
print(“able to rent”)

29
Q

How do you create an else if block in Python?

A

if age > 18 :
print(“can vote”)

elif age > 21:
print(“can vote and drink”)
else:
print(“too young”)

30
Q

What’s a dictionary in Python?

A

A dictionary in Python is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the value associated with that key. A key’s value can be a number, a string, a list, or even another dictionary. In fact, you can use any object that you can create in Python as a value in a dictionary.

alien_0 = {'color': 'green', 'points': 5

  • You can add or remove a key from a dictionary
31
Q

How to access the value of a key of a dictionary?

A

Give the name of the dictionary and the place the key inside a set of square brackets

alien_0['points']

Another way to retrieve is to use the get method. It’s better to use because if the key doesn’t exist, it won’t throw an error, it will return none.

alien_0.get('points') will return 5

alien_0.get('badkey') will return none

32
Q

How to loop through a dictionary?

A
  • How to loop through a dictionary?you can loop through all the key, pair
    python
      for key, value in user_0.items():
          print(f"\nKey: {key}")
          print(f"Value: {value}")
     
    or all the keys
    python
      for name in favorite_languages.keys():
          print(name.title())
     
    or all the values
    python
      for language in set(favorite_languages.values()):
          print(language.title())
     
33
Q

How do you get data from the user in Python?

A

You can use the input() function to get data from the user

  • The input function pauses the program and waits to get the user to enter text
  • message = input("Enter a word")
  • this creates a variable named message and assigns the value of the user’s input to this variable
34
Q

How do you convert a string to an integer in Python?

A

numb = int(‘23’)

35
Q

What does the module % do in Python?

A

The modulo operator tells you what the remainder is when you divide a number by a number. 6 % 2 is 0. This means the remainder of 6 / 2 is zero.

36
Q

What’s a while loop in Python and what’s the syntax?

A

The while loop runs as long as a certain condition is true.

If the condition is always true, the loop will run forever. So make sure to have the condition false so that the loop may stop

```python
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
~~~

37
Q

How do you define a function in Python?

A

To define a function use the keyword def, then the name of the function, followed by () . The parentheses are required and inside of them you pass the information that are required to run the function. If you pass nothing, then nothing is required to run the function.

```python
def greet_user():
print(“hello”)
~~~

To call the function use greet_user()

38
Q

What is a parameter and argument in Python?

A

In Python, when you define a function, you can specify parameters, which act as placeholders for values the function will receive.

Example of a Parameter:

```python
python
def greet_user(username):
print(f”Hello, {username}!”)

In this function, `username` is a **parameter**—it defines the expected input when the function is called.

---

When you call the function and provide a value, that value is called an **argument**.

**Example of an Argument:**

```python
python
name = "Louis"
greet_user(name)

Here, name (which holds the value "Louis") is the argument being passed to the greet_user function.

Key Difference:

  • Parameter → A variable inside the function definition (e.g., username).
  • Argument → The actual value passed when calling the function (e.g., "Louis").
39
Q

How do you create a function that returns a value in Python?

A

You just need to have the keyword return in the function

40
Q

How do you pass a number of arguments in a function in Python?

A

To pass a series of arguments, you use *parameter_name when defining the function. This allows the function to accept multiple arguments as a tuple.

If you have multiple parameters, it’s important to place the parameter with * (which collects multiple arguments) at the end of the parameter list.

Example:

```python
python
CopyEdit
def greet_names(*names):
for name in names:
print(f”Hello, {name}!”)

Here, `*names` allows the function to accept multiple names as arguments.

**Example with Multiple Parameters:**

```python
python
CopyEdit
def greet(group, *names):
    print(f"Greetings to the {group} group!")
    for name in names:
        print(f"Hello, {name}!")

In this case, group is a regular parameter, while *names collects multiple additional arguments.

41
Q

What are modules in Python? What are their advantages? How to use them?

A
  • Modules in Python are separate files that contain different functions.
  • Using modules is important because they help reuse code and encapsulate low-level details, making programs more organized and maintainable.
  • To import all functions from a module, use:```python
    python
    CopyEdit
    import pizza```
  • To import a specific function from a module, use:```python
    python
    CopyEdit
    from pizza import make_pizza```
  • You can also use an alias when importing modules and functions for better readability or convenience.Example:```python
    python
    CopyEdit
    import pizza as p
    from pizza import make_pizza as mp```
42
Q

Tips on style when creating a function

A
  • Functions should have descriptive names, and these names should use lowercase letters and underscores. Descriptive names help you and others understand what your code is trying to do. Module names should use these conventions as well.
  • Every function should have a comment that explains concisely what the function does. This comment should appear immediately after the function definition and use the docstring format.
  • If you specify a default value for a parameter, no spaces should be used on either side of the equal sign: