Python Flashcards
append() + example
Adds an item to the end of the list.
pop() + example
Removes and returns an item at a specific index.
insert() + example
Inserts an item at a specific index.
remove() + example
Removes the first occurrence of a value.
count() + example
Counts occurrences of a specified value.
index() + example
Returns the index of the first occurrence of a value.
are list mutable in python?
Lists in Python are mutable, meaning they can be modified.
numbers = [1, 2, 3, 4, 5]
float_numbers = [1.1, 2.2, 3.3]
names = [“Alice”, “Bob”, “Charlie”]
names = [“Alice”, “Bob”, “Charlie”]
give me list of tuples
coordinates = [(1, 2), (3, 4), (5, 6)]
what is + example
int (Integer)
Definition: Represents whole numbers, positive or negative, without a decimal point.
what is + example
float (Floating-Point Number)
Definition: Represents real numbers with a decimal point.
x = 3.14 # Positive float
y = -2.71 # Negative float
z = 0.0 # Zero as a float
what is + example
matrix
Python does not have a built-in matrix type, but you can create matrices using nested lists or libraries like NumPy.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
what is + example
tuple
Definition: An ordered, immutable collection of elements. Once created, a tuple cannot be modified.
Syntax: Defined using parentheses () or without them.
tuple1 = (1, 2, 3) # Tuple with integers
tuple2 = (“a”, “b”, “c”) # Tuple with strings
tuple3 = (1, “hello”, 3.14) # Mixed data types
Tuples are faster than lists.
Useful for data that should not change.
what is + example
dictionary
Definition: An unordered collection of key-value pairs.
Syntax: Defined using curly braces {} with keys and their corresponding values.
person = {
“name”: “Alice”,
“age”: 25,
“city”: “New York”
}
Convert int to float (function)
num_int = 5 # Integer
num_float = float(num_int) # Convert to float
Convert float to int (function)
num_float = 5.7 # Float
num_int = int(num_float) # Convert to integer
Convert int to str (function)
num_int = 123 # Integer
num_str = str(num_int) # Convert to string
Convert str to int (function)
num_str = “456” # String
num_int = int(num_str) # Convert to integer
Convert str to float (function)
num_str = “3.14” # String with decimals
num_float = float(num_str) # Convert to float
Convert list to tuple and tuple to list (function)
Tuple to List
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
my_tuple = (4, 5, 6)
my_list = list(my_tuple)
for loop
iterate over list of strings and print those
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
for loop
print numbers from 0-4
for i in range(5): # Iterates from 0 to 4
print(i)
while loop.
when to use it?
The while loop repeatedly executes a block of code as long as a condition is True. It is useful when you do not know the number of iterations in advance.
example of while loop with a counter
count = 0
while count < 5:
print(count)
count += 1 # Increment the counter
explain break and continue
break Exits a loop prematurely. break
continue Skips the current iteration of a loop and moves to the next iteration. continue
explain all() and any() Functions
Check if any number is greater than 10
numbers = [2, 4, 6, 8]
# Check if all numbers are even
if all(num % 2 == 0 for num in numbers):
print(“All numbers are even”)
if any(num > 10 for num in numbers):
print(“At least one number is greater than 10”)
else:
print(“No number is greater than 10”)
sorted()
what is + example
Sorting in reverse order
The sorted() function is used to return a new sorted list from the items in an iterable.
numbers = [3, 1, 4, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 4]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) # Output: [4, 3, 2, 1]
how to print a variable inside string in python?
f-strings (formatted string literals)
print(f”My name is {name} and I am {age} years old.”)
replace() in strings
text = “Hello, world!”
new_text = text.replace(“world”, “Python”)
print(new_text) # Output: Hello, Python!
split() in strings
text = “apple,banana,cherry”
fruits = text.split(“,”)
print(fruits) # Output: [‘apple’, ‘banana’, ‘cherry’]
I have a string in a loop called new_word.
I need after iteration to remove the first letter from that string. How to?
The [1:] syntax is a string slicing operation in Python.
It creates a new string by excluding the first character of the original string and keeping the rest.
new_word = new_word[1:]
which is the issue?
for a, b in range(total_scores):
You’re trying to unpack the result of range(total_scores) as if it provides two values (a and b), but range(total_scores) only produces integers, not pairs. Hence, Python raises the error TypeError: ‘int’ object is not iterable.
how to control decimal spaces?
give an example
f-strings
print(f”{value:.2f}”)
print(f”{positive_count / total_len:.6f}”)
this is not working okey…
min_list = arr
max_list = arr
why?
This does not create separate copies of the list. Both min_list and max_list still refer to the same list as arr. When you remove an element from min_list or max_list, it modifies arr as well.
Solution:
To prevent modifying the original list, you need to create copies of arr for min_list and max_list using the copy() method or list slicing.
difference of python 2 and 3.
Python 2 and Python 3 differ primarily in design and functionality:
Print Statement:
Python 2: print “Hello”
Python 3: print(“Hello”) (requires parentheses).
Python 2: No longer supported (end-of-life in 2020).
Python 3: Actively developed and supported.
Python 3 is the future and should be used for all new projects.
python key features
Simple and Readable Syntax: Python emphasizes readability, making it easy to learn and use.
Dynamically Typed: Variables are not declared with a specific type; the type is determined at runtime.
Interpreted Language: Python code is executed line by line by an interpreter, without the need for prior compilation.
Versatile and Extensive Libraries: Python has a rich set of libraries and frameworks (e.g., NumPy, Pandas, Django).
Object-Oriented and Functional: Supports multiple programming paradigms, including OOP and functional programming.
The Global Interpreter Lock (GIL) is a mechanism used in CPython
Memory management: The GIL simplifies memory management by preventing multiple threads from modifying objects at the same time. This means that even if a Python program has multiple threads, only one thread can run Python code at any given moment.
What are Python’s mutable and immutable data types?
Mutable Data Types:
Lists: You can modify the elements of a list.
python
Dictionaries: You can add, modify, or remove key-value pairs.
python
Sets: You can add or remove elements from a set.
python
Immutable types: Strings, tuples, integers, floats, frozensets, etc.
Tuples: You cannot change, add, or remove elements from a tuple.
python
tup = (1, 2, 3)
tup[0] = 4 # Error: tuples are immutable
In Python, classes and objects are core concepts in Object-Oriented Programming (OOP).
Class
A class is a blueprint or template for creating objects. It defines a set of attributes (variables) and methods (functions) that are common to all objects of that class. You can think of a class as a way to define a structure for objects.
FORMULA_1_TEAM
functions/methods
resign_contract_with_Driver
earn_a_point
Object
An object is an instance of a class. When you create an object from a class, you are essentially creating a specific instance of that class, with its own unique values for the attributes.
FERRIRI
MER
key difference between @staticmethod, @classmethod, and instance methods
Instance Methods
Definition: These are the most common methods in Python classes. They require an instance (object) of the class to be called.
obj = MyClass()
obj.instance_method()
@staticmethod
Definition: A @staticmethod is a method that belongs to the class but does not require an instance or class reference to be called.
class MyClass:
@staticmethod
def static_method():
print(“This is a static method.”)
obj = MyClass()
obj.static_method()
Class method: Use when the method needs to modify or access class-level attributes and methods (e.g., factory methods). dosent have access on instance.
how is the constructor in python?
__init__(self, …) (Constructor)
Purpose: This method is called when an instance of a class is created. It is used to initialize the object’s attributes.
how to show in string output when objects gets created and printed
__str__(self) (String Representation)
Purpose: This method defines the “informal” or user-friendly string representation of an object. It is called when str() or print() is used on the object.
explain microservices
Microservices is an architectural style that structures an application as a collection of loosely coupled, independently deployable services. Each service is designed to perform a specific business function and is developed, deployed, and scaled independently. Microservices are often used in large-scale systems to improve flexibility, scalability, and maintainability.
ej. 1. User Authentication Service:
2. products/content
3. notification service
4. payment
5. search service
creating and what is an API with cherrypy
CherryPy can be used to create an API in Python. CherryPy is a web framework that provides tools to build web applications, including APIs. It allows you to handle HTTP requests, define routes (or endpoints), and send HTTP responses.