Common Codes Flashcards
Become familiar with common tools in Python (14 cards)
print() #function print("string") print(integer) print(float) print(variable)
Use to print strings, integers, variables, and floats.
Must print same items.
print(“str” + “int”) will result in error
print(“int” + “int”) will give mathematic result
print(“int” + “float) will give mathematic result with corresponding decimal – print(1 + 2.0) = 3.0
string.split() #function
Use to split a string and covert it into a list of strings.
Example:
string = “This is a string”
string2 = string.split()
print(string2) gives [‘This’, ‘is’, ‘a’, ‘string’]
string.split(“separator”) #function
Use to split a string and convert it into a list of strings.
In this case we can use a desired separator if there is one.
Example:
string = “This is a string, a long string”
string2 = string.split(“,”)
print(string2) gives [‘This is a string’, ‘ a long string’]
Without a separator it defaults to space as the separator giving [‘This’, ‘is’, ‘a’, ‘string,’, ‘a’, ‘long’, ‘string’]
f = open (‘C:\Users\jazzp\Desktop\Python Files\myfile.txt’, ‘r’)
firstline = f.readline()
print(firstline)
f.close()
This function is used to open files not saved in same folder and current PY file with active code.
‘C:\Users\jazzp\Desktop\Python Files\myfile.txt’
(remember to add \ and replace myfile with your target file name)
f = open (‘C:\Users\jazzp\Desktop\Python Files\DT.txt’, ‘r’)
for line in f:
print(line, end = ‘’)
f.close()
For loop applied to open all lines in a ‘txt’ file.
print(line, end = ‘’) *make sure to use double single quotes after “=”, if you want to get rid of the gap after every sentence
f = open (‘C:\Users\jazzp\Desktop\Python Files\DT.txt’, ‘a’)
f. write(‘\nThis sentence will be.’)
f. close()
Used to append the ACTUAL target document. Line will be added to the end. Running this code will add “This sentence will be.” at the end of the text file.
ord() #function
chr() #function
The ord() function converts a single string item into a number.
The chr() function converts a known number and converts it into a letter.
Example:
ord(“B”) gives 66
chr(66) gives “B”
Note that ord() and chr() are similar to each other.
message = ["Please encrypt this message"] cypher = 5 encrypt = ""
for list in message:
for character in list:
encrypt += chr(ord(character) + cypher )
print(encrypt)
Using ord() and char(), we can encrypt a message using a cypher.
Running this code gives the encrypted message string as follows:
Uqjfxj%jshw~uy%ymnx%rjxxflj
We can change the cypher as needed and to decrypt the message we need to know the cypher.
(1)ab = [“it’s”], [‘was’], [‘annoying’]
message = []
for i in ab:
message += i
print(message)
(2) mylist = “,”.join(message)
(2b) mylist= “ “.join(message)
(3)mylist = mylist.replace(“,”,’ ‘)
print(str(mylist))
1) loops through list while adding them to create a new list
Ex. [“it’s”], [‘was’], [‘annoying’] INTO [“it’s”, ‘was’, ‘annoying’]
2) JOIN command turns a list into to string
Ex. [“it’s”, ‘was’, ‘annoying’] INTO it’s,was,annoying
2b) You can also use “ “.join to get it’s was annoying
3) REPLACE command can be used to change characters within a string.
Ex. it’s,was,annoying INTO it’s was annoying
*In this ex. we are replacing “,” with an empty space “ “
a = [someList]
a.append(x)
someList.append(x)
Using this, we can add items "x" into a list. Ex. a = [1, 2, 3] a.append(4) print(a) Gives [1, 2, 3, 4]
class Employee: def \_\_init\_\_(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company'
emp_1 = Employee('Corey', 'shafer', 50000) emp_2 = Employee('rey', 'fer', 560000)
print(emp_1.email)
print(emp_2.email)
Create a class(blue print/template) for instances. Think of it as creating characters for a video game with unique attributes.
Print result:
Corey.shafer@company
rey.fer@company
print (“My name is {} and I have {} dogs”.format(“Ting”, 4))
.format with {} can be useful when writing text with defined variables.
Ex. inputs, classes/methods
class employee:
raise_amount = 1.04 def \_\_init\_\_(self, first, last, pay): self. first = first self. last = last self. pay = pay self. email = first + '.' + last + 'company.com'
def fullname(self): return '{} {}'.format(self.first, self.last)
def apply_raise(self): self.pay = int(self.pay * self.raise_amount)
Format for class and objects
with open('/Users/Tung_Nguyen/PycharmProjects/Test/baby.txt', 'r') as myfile: data = myfile.read()
listSplit = data.split()
import random
print(random.choice(data))
Opens a .txt file using the “with…as” function and sets it to a string variable. Converts that string into a list using the split function. Finally import the random function and randomly pulling an item from the list.