python coding notes Flashcards
how to find where a character is
.index(character)
how to remove something from a list
list.pop(position of char)
different ways to show range
- for i in range
- num for num
different ways to do loops
- for i in
- char for char
how to find the number of time something occurs in a list
.occur()
how to sort list
- sorted(list)
- list.sort()
how to find length of something
len()
how to insert an element into a specific index of a list
list.insert()
how to skip numbers when doing range
- add a third input, eg range(2,9,2) would output 2,4,6,8
how to slice lists
list[start:end]
how to see how many times an element occurs in a string or list
.count
how to remove duplicates in a list
use list(set())
what is a tuple
a data structure that allows us to store multiple pieces of data inside of it
- the elements, the order of the elements and how many elements there are cannot be changed
- they are immutable, can’t be edited
what does zip() do
takes two or more list as inputs and returns an object that contains a list of pairs. each pair contains one element from each of the inputs
what is indefinite iteration
where the number of times the loop is executed depends on how many times a condition is met
what is definite iteration
where the number of times the loop will be executed is defined in advance
what does a while loop do
performs a set of instructions as long as a given condition is true
what does break do
stops an iteration
how to carry on an iteration
continue
how to iterate using a list
[(what u wanna append to the list) for i in list]
string in built functions
.strip() - removes characters from string
- .find() - finds the position of a character in a string
how to reverse a list
- list.reverse()
- Reverse = True
- [::-1]
what does enumerate do()
generates tuples which represent the indices and values of the elements in the list
what does while True do
loops forever
what does try do
lets you test a block of code for errors.
how to check if something is a digit
.isdigit()
how to repeat a loop, for example in a game
use While True
difference between pop and remove
remove removes using values
pop removes using indexes
if string.strip() what does this mean
checks if the input string is not empty after removing leading and trailing whitespace
other ways to remove white space in sentence
- “”.join(sentence.split())
- sentence.replace(“ “, “”)
what else does list()
- converts a string into a list, where each character in the string is a separate element in the list
- eg hello is [“h”, “e”, “l”, “l”,”o”]
what does zip do
used to combine two or more iterables, eg an integer and string, or string and a list
- eg - for i,j in zip(str(n)), range(1,len(str(n))+1) , this combines a string and an integer
how to do square root
math.sqrt() but import math before u do this
how to check if a number is whole
mod it by 1
how to make a number whole
round()
what does abs() do
gives the absolute value of a number,
- turns negative numbers positive, eg -5 to 5
- leaves positive numbers unchanged
what does set() do
A set automatically removes duplicate elements. Each element in a set must be unique.
Sets do not maintain any specific order of elements.
you can add or remove elements after the set has been created.
how to find the position of a character in a string/list
use variablename.index(character)
- eg. if theres a string called letters = “ABCDEFGHIJKLMNOPQRSTUVWXYZ” and you want to find where X is:
for char in userInput:
if char in letters:
current_index = letters.index(char)
when to use try and except
The try and except block is used to handle situations where the user inputs something invalid (like entering letters instead of a number)
- Handling User Input Errors
When converting user input into a specific data type, errors may occur if the input is invalid.
eg. try:
age = int(input(“Enter your age: “))
except ValueError:
print(“Invalid input! Please enter a number.”)
when to use a for loop
You Want to Continuously Prompt the User Until Valid Input Is Provided:
For example, asking a user for a valid number or email address until they provide one. Loops make it easy to repeat the request.
You Need Custom Validation Logic:
For example:
- Checking if a string contains only specific characters.
- Ensuring input meets specific constraints (e.g., a number in a range).
- A loop allows you to write your own logic instead of relying solely on Python’s built-in exception system.
Errors Are Not Easily Capturable by Exceptions:
- For example, checking if a string contains only letters is not something that throws an exception—you need to check this explicitly using string methods.
You Want More Granular Feedback:
- If you want to inform the user why their input is invalid (e.g., “Value is too large” or “Must be a number”), loops can provide more flexibility.
how to do a factorial recursion function
def factorial(x):
if x == 1:
return 1
else:
return x * factorial(x -1)
how to check if any character in an input is a digit
if not any(char.isdigit() for char in userInput):
Write a function that sorts a list of numbers based on the sum of their digits in descending order.
- The function should return the sorted list.
def sum_digits(x):
count = 0
for i in str(x):
count+= int(i)
return count
def digit_sum_sort(inputList):
newList = []
for i in inputList:
newList.append((i, sum_digits(i)))
newList.sort(key=lambda item : (item[1], item[1]), reverse=True)
sortedList = [item[0] for item in newList]
return sortedList
print(digit_sum_sort([134, 23, 45, 98, 321, 500]))
how to sort a parts of a tuple in descending order
newList.sort(key=lambda item : (item[1], item[1]), reverse=True)
sortedList = [item[0] for item in newList]
when to use while True opposed to while(a condition)
Use while True when:
- You don’t know beforehand when the loop will stop
- eg: Finding the smallest multiple (we don’t know the number in advance)
- You want to keep asking for user input until they enter valid data
-eg: Keep asking for a number until the user enters a valid one.
Use while (a condition) when:
- You know the stopping condition in advance
eg: Count down from 10 to 1
- You have a specific range or limit
eg: Running a loop only if a number is less than 50.
python
Copy
Edit
how to convert digit to a list
list(map(int, str(n)))