13.0 Programming Basics with Python Flashcards

(145 cards)

1
Q

What are some other disciplines Python is commonly used for besides DevOps?

just know a few…

A
  • Web development
  • Data science
  • Machine learning
  • AI
  • Web scraping

These applications highlight Python’s versatility in various domains.

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

What are key benefits of Python?

5 things… Just name a few

A
  • Simple syntax (easy to learn, read, and write)
  • Flexible usage
  • Easy setup
  • Large ecosystem of libraries
  • Strong community support

These benefits make Python a popular choice among developers.

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

What are some use cases for Python which make it valuable for DevOps engineers?

7 things. Name just a few…

A
  • Automate system health checks
  • Monitoring
  • Backups
  • Custom Ansible modules
  • Cron management
  • CI/CD tasks
  • Cleanup tasks

Python’s automation capabilities streamline DevOps processes.

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

What two things do you need installed to write Python programs?

A
  • A Python version
  • A code editor (e.g., PyCharm or VS Code)

These installations are essential for developing Python applications.

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

What is a variable in Python?

A

A container for storing data values.

Variables allow for dynamic data handling in programs.

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

Why use variables?

A

To reuse values multiple times throughout code.

This promotes efficiency and clarity in programming.

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

What are the built-in data types in Python?

A
  • Strings
  • Integers
  • Floats
  • Lists
  • Sets
  • Dictionaries

These types are readily available for use in Python programming.

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

How do you write a comment in Python?

A

With the # symbol.

Comments are crucial for code documentation and clarity.

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

When should comments be used and not used?

A

To add value or clarity, NOT to restate obvious code behavior.

Your code should be treated as documentation but effective comments enhance code readability.

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

What is a function?

A

A block of reusable code that runs when called.

Functions promote code modularity and reusability.

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

What can functions accept and return?

A
  • Accept parameters
  • Return values

This flexibility allows functions to perform a variety of tasks.

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

How do you define a function in Python?

A

Using the def keyword.

This keyword initiates the function definition process.

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

What is a boolean value?

A

True or False.

Boolean values are fundamental in controlling program logic.

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

What is the purpose of an if/else statement?

A

To control program flow based on conditions.

This structure allows for decision-making in code.

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

What are Python built-in functions?

A

Functions provided by the language for common tasks (e.g., input()).

Built-in functions simplify coding by providing ready-made solutions.

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

Why use built-in functions?

A

They save time and prevent reinventing common solutions.

Utilizing built-in functions enhances productivity.

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

Why handle errors?

A

To prevent the program from crashing when unexpected input or conditions occur.

Error handling is crucial for robust software development.

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

How do you accept user input in Python?

A

Using the input() function.

This function allows interaction with users during program execution.

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

What is a Python list?

A

An ordered, indexed collection that can hold multiple items and allows duplicates.

Lists are versatile data structures in Python.

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

What index does the first list item have?

A

0

Python uses zero-based indexing for lists.

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

How do you loop through a list?

A

Using a for loop.

This method allows for efficient iteration over list elements.

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

When do you use a for loop?

A

When repeating logic a specific number of times or iterating over a set of values.

For loops are ideal for known iterations.

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

When do you use a while loop?

A

When logic should repeat as long as a condition remains true.

While loops are useful for indefinite iterations.

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

What is a Python set?

A

An unordered, unindexed collection that cannot contain duplicate values.

Sets are useful for storing unique items.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
When are sets useful?
When storing unique items, such as student IDs. ## Footnote Sets help maintain uniqueness in data collections.
26
What is a dictionary in Python?
A collection of key-value pairs with no duplicate keys. ## Footnote Dictionaries provide a way to associate values with unique keys.
27
What is a Python module?
A .py file containing Python code. ## Footnote Modules help organize code into manageable files.
28
Why use modules?
To organize related code into logical units. ## Footnote This promotes code maintainability and clarity.
29
What must a package include?
An __init.py__ file. ## Footnote This file indicates that the directory should be treated as a package.
30
What is PyPI?
The Python Package Index — a repository of third-party Python packages. ## Footnote PyPI facilitates package distribution and installation.
31
What is pip?
A package installer used to install Python packages. ## Footnote Pip simplifies the process of managing Python libraries.
32
What is a class in Python?
A blueprint for creating objects. ## Footnote Classes encapsulate data and behavior in object-oriented programming.
33
What is an object?
An instance of a class. ## Footnote Objects represent specific implementations of classes.
34
What is the __init__() method used for?
Initializing object properties when an object is created. ## Footnote This method sets up the initial state of an object.
35
What is an API?
A communication interface between applications. ## Footnote APIs enable different software systems to interact.
36
What is an API request?
A message sent to a service asking for data or triggering behavior. ## Footnote API requests are fundamental to web services.
37
What is JSON?
A lightweight data format used to transmit data over the web. ## Footnote JSON is widely used for data interchange in APIs.
38
What Python library is commonly used to send HTTP requests?
`requests` ## Footnote This library simplifies the process of making HTTP requests.
39
Why is authentication required for some API requests?
To ensure only authorized users access protected data. ## Footnote Authentication is crucial for data security.
40
How should variables and functions be named?
Lowercase with underscores; descriptive names. ## Footnote This naming convention enhances code readability.
41
How should classes be named?
PascalCase (e.g., `User`). ## Footnote This convention distinguishes classes from other identifiers.
42
How are constants written?
ALL_CAPS with underscores. ## Footnote This style indicates that the value should not change.
43
What does DRY stand for?
Don’t Repeat Yourself. ## Footnote This principle encourages code reusability.
44
Why should functions be small?
To keep logic simple, reusable, and easy to understand. ## Footnote Small functions enhance maintainability and clarity.
45
How do you assign a **variable** in Python?
```python score = 5 name = "James" ``` ## Footnote This demonstrates basic variable assignment in Python.
46
How do you check the **type** of a variable?
```python type(score) ``` ## Footnote This function returns the data type of the variable.
47
Example of **string concatenation**.
```python full = "Hello " + "World" ``` ## Footnote This combines two strings into one.
48
Convert a string to an **int**.
```python num = int("10") ``` ## Footnote This converts the string "10" into an integer.
49
How do you write a **single-line comment**?
```python # this is a comment ``` ## Footnote Comments are used to explain code and are ignored by the interpreter.
50
How do you define a **basic function**?
```python def greet(): print("Hello") ``` ## Footnote This defines a function named `greet` that prints a greeting.
51
How do you define a function with **parameters**?
```python def add(a, b): return a + b ``` ## Footnote This function takes two parameters and returns their sum.
52
How do you **call a function**?
```python result = add(3, 4) ``` ## Footnote This calls the `add` function with arguments 3 and 4.
53
Basic **if/else** syntax.
```python if score > 10: print("high score") else: print("low score") ``` ## Footnote This demonstrates conditional statements in Python.
54
How to **chain conditions** with `elif`?
```python if temp > 30: print("hot") elif temp > 20: print("warm") else: print("cold") ``` ## Footnote This allows for multiple conditions to be checked in sequence.
55
What do **comparison operators** look like?
```python == # equal != # not equal > # greater than < # less than >= # greater or equal <= # less or equal ``` ## Footnote These operators are used to compare values.
56
Example **boolean comparison**.
```python is_adult = age >= 18 ``` ## Footnote This assigns a boolean value based on the comparison.
57
How do you accept **user input**?
```python user_input = input("Enter number: ") ``` ## Footnote This prompts the user for input and stores it in a variable.
58
How to convert input to an **integer** safely?
```python num = int(input("Enter a number: ")) ``` ## Footnote This converts the user input into an integer.
59
Basic **try/except** example.
```python try: age = int(input("Age: ")) except ValueError: print("Please enter a number.") ``` ## Footnote This handles exceptions that may occur during input conversion.
60
How do you define a **list**?
```python friends = ["tim", "sara", "john"] ``` ## Footnote This creates a list containing three string elements.
61
Loop through **list items**.
```python for f in friends: print(f) ``` ## Footnote This iterates over each item in the list and prints it.
62
Add an item to a **list**.
```python friends.append("mary") ``` ## Footnote This adds a new item to the end of the list.
63
Get item by **index**.
```python first = friends[0] ``` ## Footnote This retrieves the first item from the list.
64
For-loop iterating over a **range**.
```python for i in range(5): print(i) ``` ## Footnote This loops through numbers from 0 to 4.
65
While loop **example**.
```python count = 0 while count < 3: print("running") count += 1 ``` ## Footnote This continues to loop until the condition is no longer true.
66
How do you create a **set**?
```python ids = {3441, 1661, 7845} ``` ## Footnote This creates a set containing three unique integers.
67
Add to a **set**.
```python ids.add(9999) ``` ## Footnote This adds a new item to the set.
68
Loop through a **set**.
```python for item in ids: print(item) ``` ## Footnote This iterates over each item in the set.
69
How do you define a **dictionary**?
```python person = { "name": "James", "age": 30 } ``` ## Footnote This creates a dictionary with two key-value pairs.
70
Access value by **key**.
```python person["name"] ``` ## Footnote This retrieves the value associated with the key "name".
71
Add/update **key/value pair**.
```python person["email"] = "james@test.com" ``` ## Footnote This adds a new key-value pair or updates an existing one.
72
How do you **import a module**?
```python import datetime ``` ## Footnote This imports the `datetime` module for use in the program.
73
How do you import a **single function** from a module?
```python from math import sqrt ``` ## Footnote This imports only the `sqrt` function from the `math` module.
74
How do you create your own **module**?
A file named: helper.py With content: ```python def greet(): print("hello") ``` ## Footnote This defines a simple function in a separate file.
75
How to use your own **module**?
```python import helper helper.greet() ``` ## Footnote This imports the custom module and calls the `greet` function.
76
Install a package with **pip**.
pip install requests ## Footnote This command installs the `requests` library for making HTTP requests.
77
How do you define a **class**?
```python class User: def __init__(self, name): self.name = name ``` ## Footnote This defines a class with an initializer method.
78
How do you create an **object** from a class?
```python u = User("James") ``` ## Footnote This creates an instance of the `User` class.
79
Access an object's **attribute**.
```python print(u.name) ``` ## Footnote This retrieves the `name` attribute from the `User` object.
80
How to send a **GET request** using `requests` library?
```python import requests r = requests.get("https://gitlab.com/api/v4/projects") ``` ## Footnote This sends a GET request to the specified URL.
81
How to **parse JSON** in a response?
```python data = r.json() ``` ## Footnote This converts the response content from JSON format to a Python dictionary.
82
Example of **basic authentication**.
```python r = requests.get( url, auth=("username", "password") ) ``` ## Footnote This sends a GET request with basic authentication.
83
Example request with **headers**.
```python headers = {"PRIVATE-TOKEN": "123abc"} r = requests.get(url, headers=headers) ``` ## Footnote This sends a GET request with custom headers.
84
Example of **snake_case** naming.
```python total_items = 10 ``` ## Footnote This follows the convention of using snake_case for variable names.
85
Example of **constant naming**.
```python MAX_RETRY = 5 ``` ## Footnote Constants are typically written in all uppercase letters.
86
Example of a small **single-purpose function**.
```python def is_adult(age): return age >= 18 ``` ## Footnote This function checks if a person is an adult based on their age.
87
What is Python commonly used for?
* Web development * Data science * Machine learning * AI * Automation * DevOps task automation * Scripting * Web scraping ## Footnote These applications highlight Python's versatility across various domains.
88
What are key benefits of Python?
* Simple syntax * Easy setup * Huge ecosystem * Large community * Flexible across domains ## Footnote These benefits make Python a popular choice for developers.
89
Why is Python valuable for DevOps engineers?
* Enables automation of monitoring * Backups * CI/CD actions * Cron tasks * Cleanup tasks * Custom tooling ## Footnote Python's capabilities streamline many DevOps processes.
90
How do you create variables in Python?
```python score = 5 name = "James" ``` ## Footnote Variables in Python are created by assigning a value to a name.
91
How do you check the type of a variable?
```python type(value) ``` ## Footnote This function returns the type of the specified variable.
92
Example of string concatenation.
```python greeting = "Hello " + "World" ``` ## Footnote This combines two strings into one.
93
Convert a string to an integer.
```python num = int("42") ``` ## Footnote This converts the string representation of a number into an integer.
94
Convert an integer to a string.
```python text = str(42) ``` ## Footnote This converts an integer into its string representation.
95
How do you format strings with f-strings?
```python name = "James" msg = f"Hello {name}" ``` ## Footnote F-strings allow for easy and readable string formatting.
96
How do you define a function?
```python def greet(): print("Hello") ``` ## Footnote This defines a simple function that prints a greeting.
97
Function with parameters.
```python def add(a, b): return a + b ``` ## Footnote This function takes two parameters and returns their sum.
98
How do you call a function?
```python result = add(2, 3) ``` ## Footnote This calls the `add` function with arguments 2 and 3.
99
Basic if/else syntax.
```python if x > 10: print("big") else: print("small") ``` ## Footnote This demonstrates a simple conditional statement.
100
If/elif/else example.
```python if x == 0: print("zero") elif x > 0: print("positive") else: print("negative") ``` ## Footnote This shows how to handle multiple conditions.
101
What are Python's boolean values?
`True` and `False` ## Footnote These values are used in logical operations and conditions.
102
Comparison operators.
== != > < >= <= ## Footnote These operators are used to compare values.
103
Example boolean expression.
```python is_adult = age >= 18 ``` ## Footnote This expression checks if a person is an adult based on their age.
104
Get user input.
```python user_input = input("Enter something: ") ``` ## Footnote This function prompts the user for input.
105
Convert input to number.
```python num = int(input("Enter number: ")) ``` ## Footnote This converts the user input into an integer.
106
Basic error handling block.
```python try: x = int(input("Age: ")) except ValueError: print("Invalid input.") ``` ## Footnote This demonstrates how to handle exceptions in Python.
107
Catch any exception.
```python except Exception as e: print(e) ``` ## Footnote This catches all exceptions and prints the error message.
108
Create a list.
```python friends = ["tim", "sara", "john"] ``` ## Footnote This creates a list of friends.
109
Access first element.
```python friends[0] ``` ## Footnote This retrieves the first element from the list.
110
Append an item to a list.
```python friends.append("mary") ``` ## Footnote This adds a new item to the end of the list.
111
Loop through a list.
```python for f in friends: print(f) ``` ## Footnote This iterates over each item in the list.
112
For-loop with range.
```python for i in range(5): print(i) ``` ## Footnote This loops through a range of numbers.
113
While loop example.
```python count = 0 while count < 3: print("running") count += 1 ``` ## Footnote This demonstrates a while loop that runs until a condition is met.
114
Create a set.
```python ids = {3441, 1661, 7845} ``` ## Footnote This creates a set of unique identifiers.
115
Add to a set.
```python ids.add(9999) ``` ## Footnote This adds a new item to the set.
116
Create a dictionary.
```python person = {"name": "James", "age": 30} ``` ## Footnote This creates a dictionary with key-value pairs.
117
Access a dictionary value.
```python person["name"] ``` ## Footnote This retrieves the value associated with the key 'name'.
118
Add or update a key/value pair.
```python person["email"] = "ex@example.com" ``` ## Footnote This adds a new key-value pair to the dictionary.
119
Import a built-in module.
```python import datetime ``` ## Footnote This imports the datetime module for handling dates and times.
120
Import specific functions.
```python from math import sqrt ``` ## Footnote This imports only the `sqrt` function from the math module.
121
Create your own module.
File: `helper.py` ```python def greet(): print("hi") ``` ## Footnote This defines a simple function in a custom module.
122
Use your custom module.
```python import helper helper.greet() ``` ## Footnote This imports the custom module and calls the greet function.
123
What file marks a directory as a Python package?
`__init__.py` ## Footnote This file is required for Python to recognize a directory as a package.
124
Install a package with pip.
pip install requests ## Footnote This command installs the requests library for making HTTP requests.
125
Define a class with an initializer.
```python class User: def __init__(self, name): self.name = name ``` ## Footnote This defines a class with an initializer method.
126
Create an object.
```python u = User("James") ``` ## Footnote This creates an instance of the User class.
127
Access an object attribute.
```python u.name ``` ## Footnote This retrieves the name attribute from the User object.
128
Send a GET request.
```python import requests r = requests.get("https://api.example.com") ``` ## Footnote This sends a GET request to the specified URL.
129
Parse JSON response.
```python data = r.json() ``` ## Footnote This parses the JSON response from the GET request.
130
Send a request with headers.
```python r = requests.get(url, headers={"Authorization": "token"}) ``` ## Footnote This sends a GET request with custom headers.
131
Basic authentication example.
```python r = requests.get(url, auth=("user", "pass")) ``` ## Footnote This demonstrates how to send a request with basic authentication.
132
Example of snake_case variable naming.
```python total_count = 42 ``` ## Footnote Snake case is a common naming convention in Python.
133
Constant naming example.
```python MAX_RETRY = 3 ``` ## Footnote Constants are typically named in uppercase.
134
Example of a small, single-purpose function.
```python def is_even(n): return n % 2 == 0 ``` ## Footnote This function checks if a number is even.
135
Indentation matters in Python.
```python if True: print("Indented block") ``` ## Footnote Indentation is crucial for defining code blocks in Python.
136
Logical operators.
```python and or not ``` ## Footnote These operators are used to perform logical operations.
137
The `len()` function.
```python len([1, 2, 3]) # 3 ``` ## Footnote This function returns the number of items in an object.
138
Slicing syntax.
```python numbers = [10, 20, 30, 40] subset = numbers[1:3] # [20, 30] ``` ## Footnote Slicing allows you to access a subset of a list.
139
String methods.
```python "hello".upper() "HELLO".lower() "test".startswith("t") ``` ## Footnote These methods perform various operations on strings.
140
List comprehensions.
```python squares = [x*x for x in range(10)] ``` ## Footnote This creates a list of squares using a concise syntax.
141
The `in` operator.
```python if "tim" in friends: print("Found") ``` ## Footnote This checks for the presence of an item in a list.
142
Mutability.
* Lists & dicts **mutable** * Strings & tuples **immutable** ## Footnote This distinction affects how data structures can be modified.
143
How to read files.
```python with open("file.txt") as f: data = f.read() ``` ## Footnote This reads the entire content of a file.
144
How to write files.
```python with open("out.txt", "w") as f: f.write("hello") ``` ## Footnote This writes a string to a file.
145
Basic CLI argument parsing.
```python import sys print(sys.argv) ``` ## Footnote This retrieves command-line arguments passed to the script.