Skip to content

Instantly share code, notes, and snippets.

@1travelintexan
Last active September 5, 2024 00:28
Show Gist options
  • Save 1travelintexan/80a08d0e9af7e42d74023be6b8b47d44 to your computer and use it in GitHub Desktop.
Save 1travelintexan/80a08d0e9af7e42d74023be6b8b47d44 to your computer and use it in GitHub Desktop.
#These are the basics of python
#create a variable
#*******variable types in Python*****
string = "Hello World" #string
integer= 20 #int
a_float = 20.5 #float
complex_variable = 1j #complex
a_list = ["apple", "banana", "cherry"] #list
tuple_list = ("apple", "banana", "cherry") #tuple (cant have repeating elements)
a_range = range(4,6) #range is a method that gives a range of nums starting at 0 or with two arguments (inclusive)
dictionary = {"name" : "John", "age" : 36} #dict
a_set = {"apple", "banana", "cherry"} #set
a_frozen_set = frozenset({"apple", "banana", "cherry"}) #frozenset
a_boolean = True #bool
a_byte = b"Hello" #bytes
a_byte_array = bytearray(5) #bytearray
a_memory_view = memoryview(bytes(5)) #memoryview
a_none_type = None #NoneTypea
# #**************String methods*****************
upper_cased = string.upper() #turns a string to all upper cased
lower_cased = string.lower() #turns a string to all lower cased
is_upper_cased = string.isupper() #returns boolean if the whole string is upper cased.
is_lower_cased = string.islower() #returns boolean if the whole string is lower cased.
index_of = string.index('ell') #returns the index of a letter or the start of a sub string. Will throw error if not found
print(index_of)
# #************** importing *********************
# #this is how you import from the math library in Python
# from math import *
# #********** Number Methods *********
absolute_value = abs(integer) #abs is for the absolute value
raised_to_a_power = pow(4, 2) #this is 4 raised to the second power
biggest_number = max(4,6,20) #returns the biggest of the numbers
smallest_number = min(3,4)#returns the smallest of the numbers
rounded_number = round(3.2) #rounds the number to the nearest integer
always_down = floor(3.9)
always_up = ceil(2.1)
square_root = sqrt(36)
# #************* use template literal with f in front ******************
name = 'Ragnar'
inject_in_a_string = f"hello {name}"
print(inject_in_a_string)
# #***************** Getting input from a user *****************
# #**************** Always returns a string, so if you want a number then convert it*
# # ***************** int changes to an integer ****************
# # ***************** float changes to a decimal number ***********
name = input('enter name: ')
number1 = int(input('enter a number: '))
number2 = float(input('enter a number: '))
# #******************Lists ***********************
friends = ['Kevin', "Ragnar", 'Karen', 'Ragnar', 'Mitch']
#len(friends) will give you the length
print(len(friends))
#this will start at index one and print all others after
print(friends[1:])
# #This will print friends from index one and go until index 2 non inclusive
print(friends[1:2])
# #you can grab from the back of the list with negatives
print(friends[-1])
# #***************List Functions ***************
#combine two lists together
numbers = [1,2,3,44,32,20]
#.extend() adds the second list to the first, not create a new list
friends.extend(numbers)
#.append() adds only one element to the end of a list
friends.append('Buddy')
#.insert() adds an element to a specific index
#first argument is the index and the second is what you want to add
friends.insert(1, 'Jordan')
#.remove() an element from a list
friends.remove("Jordan")
#.pop() removes the last element from a list
friends.pop()
#.clear() removes every element from a list
# friends.clear()
# print(friends)
#find the index of an element in the list
#if it is not in the list then it will crash
Ragnars_position = friends.index('Ragnar')
# print(Ragnars_position)
#count how many times something repeats in a list
friends.append('Ragnar')
ragnar_count = friends.count('Ragnar')
# print(ragnar_count)
#sort a list in ascending order
friends.sort()
#.reverse() reverses a list
friends.reverse()
#.copy() copies the list
friends2 = friends.copy()
# print(friends2)
# #***************Tuples *****************
# #tuples is a list that is immutable, it is not able to change
# #zero index same as lists or arrays
coordinates = (3,6)
list_of_tuples = [(1,3), (7,8), (22,3)]
# #********************Functions ****************
# #use the def keyword
def my_function():
print('this is my function')
# #call the function
my_function()
# #**************** if statements *************
# #the if statements dont need ( )
is_male = False
is_tall = False
# #True and False are capital
# #'or' and 'and' are keywords for the if statements
# #the not is the opposite value
if is_male and is_tall:
print('you are a male and tall')
elif is_male:
print('you are a male but not tall')
elif is_tall:
print('You are tall and not a male')
elif not(is_tall) and not(is_male):
print('You are not tall and not a male')
#********************* Objects ******************
monthConversion = {
"Jan": "January",
"Feb" : "February",
"Mar": "March",
"Apr": "April",
"May": "May",
"Jun": "June",
"Jul": 'July',
"Aug": "August",
"Sep": "September",
"Oct": "October",
"Nov": "November",
"Dec": "December"
}
# # Use the .get() method to access the keys
# #If the key does not exist then you can pass the second argument to handle the missing key
# # print(monthConversion.get('Jun', 'Not a valid key'))
# #**************While loop**********
i=1
while i <=10:
# print(i)
i+=1
# #************for loop ************
my_friends = ['Ragnar', "Ellie", 'Daylin']
#range() takes a starting point and an ending point (non inclusive ending point)
for index in range(3,10):
print(index)
# #specify an array and each element will be the variable 'friend' here
for friend in my_friends:
print(friend)
# #************Nested loop ***********
my_arr = [
[1,2,3],
[4,5,6],
[7,8,9],
[0]
]
for row in my_arr:
for number in row:
print('number', number)
# #************try / except blocks ***************
# #in the example, input has a string instead of a number so it will crash. The except will catch the crash and handle it
try:
my_num = int(input('enter a number: '))
print('here is your number', my_num)
except ZeroDivisionError:
print('Cant divide by zero')
except:
print('invalid input')
# #************Reading Files *************
# #python read command (js doesnt have this)
# #first argument is the relative path to the file and the mode is the second. ('r' for read, 'w' for write, 'a' for append, 'r+' read and write)
text_file = open('test.txt', 'r')
# #.readable() will tell you if it is readable true/false
# #.readline() is when you want to read one specific line (readline will read the first line and then you need to call it again for the next)
# #.readlines() will return to you an array of all the lines, then you can write a for loop to loop over it
# #Ex:
# # for line in text_file.readlines():
# # print(line)
# #.read() will read the whole file
print(text_file.readable())
print(text_file.read())
text_file.close()
# #*********Writing a new file and appending to files***********
# #The 'a' is for append to the end of the file
# #if the file doesnt exist, then it will create a new one.
# #If it does exist then it appends to the end
# #make sure to append but start with new line which is the \n
the_file = open('test.txt', 'a')
the_file.write('\n I just put this here')
the_file.close()
# #write a new file or overwrite the existing one
# #the 'w' is for writing a new file
the_file = open('test1.txt', 'w')
the_file.write('\n I just put this here')
the_file.close()
# #**************importing useful tools from other files*********
# # IF IN SAME DIRECTORY use the import keyword and then the name of the file
import useful_tools
# #else use an import like the one below
import tools.useful_tools as useful_tools
print(useful_tools.roll_dice())
# #*********************Classes **********************
class Student:
#you need an initialize function
#it takes the self and then everything for the constructor
def __init__(self, name, major, gpa, is_on_probation):
self.name=name
self.major = major
self.gpa = gpa
self.is_on_probation = is_on_probation
def go_to_class(self):
print('going to class')
#create a new student with the Student class
my_new_student = Student('Jim', 'Business', 3.1, False)
print( 'new student', my_new_student.go_to_class())
# #********** Extending a class **************
#Put the parent class inside the ()
#you can rewrite the parents methods just by naming it the same and defining
class exchange_student(Student):
def learn_new_language(self):
print('Learning new language')
Joshua = exchange_student('Joshua', 'Pizza Major', 3.0, False)
Joshua.go_to_class()
Joshua.learn_new_language()
#**************Build a Question Game ***********
#first make the Question class
class Question:
def __init__(self, question, answer):
self.question = question
self.answer = answer
questions_list = [
Question('\nWhat color is the sky?', 'Blue'),
Question('\nWho is the best dog?', 'Ragnar'),
Question('\nWhat is the best food?', 'BBQ'),
]
def play_game():
score = 0
print('score in game ', score)
for question in questions_list:
answer = input(question.question)
if(answer == question.answer):
score += 1
print('You scored a '+ str(score))
return score
play_game()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment