Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 6510565127 6510565127 6510565127 6510565127 6510565127 6510565127
- # 6510565127 6510565127 6510565127 6510565127 6510565127 6510565127
- # 6510565127 6510565127 6510565127 6510565127 6510565127 6510565127
- # "turn on" or "activate" a module so that you can call its functions
- import operator
- import re
- import json
- import urllib.request
- import math
- import csv
- # round a floating-point number upward
- print(math.ceil(3.4))
- # import a single function from a module
- from math import log10
- print(log10(2000))
- # reading a string, an integer, and a floating-point number;
- # remember to give a prompt (can be passed as param to input, or use separate print statement)
- my_string = input()
- my_int = int(input())
- my_float = float(input())
- # scientific notation
- EARTH_MASS = 5.97E24
- # exponentiation
- volume_of_spherical_cow = (4.0/3.0)*math.pi*(radius ** 3)
- # printing a floating point number with 2 decimal places, then an int with commas
- print(f'Rent is ${rent:.2f} for {size:,} sq ft... Gosh darn high!')
- # splitting a single string into a list of substrings (e.g., by semi-colons)
- my_list = my_string.split(';')
- # stripping leading and trailing whitespace
- my_string.strip()
- # define a function and return a result
- def my_function(x, y, z):
- """
- Remember to describe your function's purpose.
- """
- return x + y + z
- # special characters
- print("The tab:\t--nice, huh?")
- print("The newline:\n--nice, huh?")
- # replacing one substring's occurrences with another substring
- print("spaces to semicolons".replace(' ', ';'))
- # taking a substring from position x up to but not including y
- my_string[x:y]
- # taking a sublist from position x up to but not including y
- my_list[x:y]
- # raising an exception and then catching it
- try:
- if some_value < 0:
- raise Exception('Ummmmm, well, this is Embarrassing')
- else:
- print("all is well")
- except:
- print("an exception happened!")
- # bailing out of your program entirely
- exit()
- # iterating from 0 up to but not including N, in steps of 2
- for i in range(0, N, 2):
- pass # special command that does nothing, useful for empty loops
- # iterate over a list
- for eachitem in my_list:
- print(eachitem)
- # finding the location of a substring inside of a longer string
- # (-1 if not found)
- my_string.find(desired_substring)
- # grab substring using regular expression
- import re
- my_string = 'grab the substring from abcdefgh Donald ijklmnopqrst'
- match_info = re.search('abcdefgh ([A-Za-z]+) ijklmnopqrs', my_string)
- if match_info:
- part_inside_parentheses = match_info.group(1)
- # reference for regular expressions
- # [0-9] or \d -- digit
- # [a-zA-Z] -- any lowercase or uppercase character
- # [a-z0-9_] -- any lowercase character, digit, or underscore
- # . -- special character representing any regular character
- # ^ -- special character representing start of string
- # $ -- special character representing end of string
- # + -- repeat whatever comes before, one or more times
- # * -- repeat whatever comes before, zero or more times
- # ? -- whatever comes before is optional (0 or more times)
- # {x} -- whatever comes before occurs exactly x times
- # {x,y} -- whatever comes before occurs x to y times
- # building up a list of 1 through 10
- my_list = []
- for i in range(1, 11):
- my_list.append(i)
- # get the length, total, minimum, and maximum of a list of numbers
- print("length: "+str(len(my_list)))
- print("total: "+str(sum(my_list)))
- print("minimum: "+str(min(my_list)))
- print("maximum: "+str(max(my_list)))
- # sorting all the items in a list
- sorted_list = sorted(my_list)
- # building up a dictionary
- all_about_me = {}
- all_about_me["name"] = "Sir Launcelot of Camelot"
- all_about_me["quest"] = "To seek the Holy Grail"
- all_about_me["favorite color"] = "Blue"
- # a list of dictionaries
- cars = [
- {"buyer": "Jane Edwards", "price": 6000, "make": "Honda"},
- {"buyer": "Ahmed Moustef", "price": 9000, "make": "Honda"},
- {"buyer": "Mike McGinney", "price": 2000, "make": "Ford"},
- {"buyer": "Jeffrey Pouch", "price": 4000, "make": "Honda"},
- {"buyer": "Beatrice Duff", "price": 6000, "make": "GM"}
- ]
- # getting the value of a dictionary, with a default in case the key is missing
- the_value = the_dictionary.get(the_key, the_default)
- price = car.get("price", 0)
- # computing a total for each category, from a list of dictionaries
- totals = {}
- for car in cars:
- category = car["make"]
- price = car["price"]
- totals[category] = totals.get(category, 0) + price
- # finding which entry corresponds to the maximum
- max_value = None
- max_buyer = None
- for car in cars:
- entry = car["buyer"]
- price = car["price"]
- if max_value is None or price > max_value:
- max_value = price
- max_buyer = entry
- # a dictionary of lists
- attendees = {
- "CS 201": ["Judy", "Bobby", "Kesha"],
- "CS 160": ["Randy", "Dandy", "Marsha"],
- "CS 361": ["Poppy", "Moppy", "Pasha"]
- }
- # iterating over a dictionary, printing it out
- for the_key in attendees.keys():
- print(the_key+':'+str(attendees[the_key]))
- # also can just get all the values directly (though unclear which value goes with which key)
- print(attendees.values())
- # iterating through the lines of a text file
- data_file = open(file_name)
- for line in data_file:
- pass
- # create a CSV reader from a file reference (or "handle") so that you can iterate over rows
- # https://docs.python.org/3/library/csv.html
- csv_reader = csv.reader(file_handle)
- # can convert a CSV reader directly into a list of lists
- course_list = list(csv_reader)
- # read from a URL into JSON
- json_string = urllib.request.urlopen(URL).read()
- resulting_dict_or_list = json.loads(json_string)
- # 6510565127 6510565127 6510565127 6510565127 6510565127 6510565127
- # 6510565127 6510565127 6510565127 6510565127 6510565127 6510565127
- # 6510565127 6510565127 6510565127 6510565127 6510565127 6510565127
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement