Python/Basic Code
(→Generating Examples) |
|||
(71 intermediate revisions by one user not shown) | |||
Line 1: | Line 1: | ||
− | ;variables | + | =reserved words= |
+ | These are some words that you should not use in python as they are reserved. | ||
+ | ;list | ||
+ | :reserved word that should not be used as a variable name. | ||
+ | |||
+ | =variables= | ||
:variables can be integers, floats, or boolean. Integers are whole numbers, floats are numbers with remainders, boolean is either True of False. | :variables can be integers, floats, or boolean. Integers are whole numbers, floats are numbers with remainders, boolean is either True of False. | ||
variable=integer | variable=integer | ||
− | + | ==float vars== | |
− | + | If you want the fraction included in the var, you need to define it as a float, otherwise python will automatically round the result to a whole number. | |
− | + | <nowiki> floating_var = float(7)/2</nowiki> | |
+ | This will give you the fraction from dividing 7/2. | ||
+ | ==convert int to string== | ||
+ | <nowiki>age = 13 | ||
+ | print str(age)</nowiki> | ||
+ | ==convert string to int== | ||
+ | <nowiki>n1 = "100" | ||
+ | n2 = "10" | ||
+ | int_addition = int(n1) + int(n2)</nowiki> | ||
+ | ==convert to float== | ||
+ | <nowiki>n1 = "7.5" | ||
+ | print float(n1)</nowiki> | ||
+ | ==verify is alpha (letters) only== | ||
+ | <nowiki>variable_name.isalpha() | ||
+ | ie. | ||
+ | if variable.isalpha():</nowiki> | ||
+ | =arithmetic operators= | ||
+ | ==add/subtract/multiply/divide/exponentiation/modulo== | ||
+ | ===exponentiation (exponential, similar to square roots)=== | ||
2 ** 3=8 (2*2*2) | 2 ** 3=8 (2*2*2) | ||
− | + | ===modulo (remainder)=== | |
5 % 2=1 (5/2 = 2 with a remainder of 1) | 5 % 2=1 (5/2 = 2 with a remainder of 1) | ||
− | + | ===shorthand=== | |
<nowiki>+= add vars and update first var | <nowiki>+= add vars and update first var | ||
ie. sandwich_price += sales_tax | ie. sandwich_price += sales_tax | ||
Line 14: | Line 37: | ||
-= subtract vars and update first var | -= subtract vars and update first var | ||
ie. money_in_wallet -= sandwich_price</nowiki> | ie. money_in_wallet -= sandwich_price</nowiki> | ||
− | + | ||
− | + | =comments= | |
− | + | ||
− | + | ||
− | + | ||
:<nowiki>#</nowiki> for single like quote or """ quote """ for multi line quote | :<nowiki>#</nowiki> for single like quote or """ quote """ for multi line quote | ||
#quote | #quote | ||
"""quote | """quote | ||
quote""" | quote""" | ||
− | + | =print= | |
− | + | ==display output== | |
print "Hello World" | print "Hello World" | ||
− | + | ==display specific letter, left to right, 0 forward== | |
print "TEST"[0] = "T" | print "TEST"[0] = "T" | ||
− | + | ==trailing comma== | |
− | : | + | adding a trailing comma ensures that we keep printing on the same line. |
− | + | <nowiki>print number,</nowiki> | |
− | + | ||
+ | =strings= | ||
+ | ==multi-line string== | ||
+ | :for strings that span multiple lines, use triple quotes | ||
+ | <nowiki>address_string = """136 Whowho Rd | ||
+ | Apt 7 | ||
+ | Whosville, WZ 44494"""</nowiki> | ||
+ | ==string continuation== | ||
+ | :it appears you can continue a string by using <code>\</code> though i've only seen this behavior using string concatenation | ||
+ | <nowiki>ie. | ||
+ | print "Ah, so your name is %s, your quest is %s, " \ | ||
+ | "and your favorite color is %s." % (name, quest, color)</nowiki> | ||
+ | ==string methods== | ||
:len() ; lower() ; upper() ; str() | :len() ; lower() ; upper() ; str() | ||
− | + | ===len() = get length of string - applies to anything within the parentheses=== | |
len(length) = 6 | len(length) = 6 | ||
− | + | ===lower() = convert to lowercase - applies to only the value after the "." . Dot notation only works on strings=== | |
LOWERCASE.lower() = lowercase | LOWERCASE.lower() = lowercase | ||
− | + | ===upper() = convert to uppercase - applies to only the value after the "." . Dot notation only works on strings=== | |
uppercase.upper() = UPPERCASE | uppercase.upper() = UPPERCASE | ||
− | + | ===str() = convert to string - applies to anything within the parentheses=== | |
str(3.14) = "3.14" | str(3.14) = "3.14" | ||
− | + | ==String Formatting== | |
+ | :concatenating strings through short hand | ||
+ | <nowiki>string_1 = "Camelot" | ||
+ | string_2 = "place" | ||
+ | print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)</nowiki> | ||
+ | ===define var length=== | ||
+ | when doing concatenating, you can specify the var length to be displayed. this is especially helpful with numbers when trying to apply formatting. | ||
+ | <nowiki>print '%02d:%02d:%02d' % (now.hour, now.minute, now.second) | ||
+ | 21:02:18</nowiki> | ||
+ | notice how the minute is <code>02</code>. If this was not defined to be (2) digits, it would have only been a 2 without the preceeding 0. | ||
+ | ==user input== | ||
+ | by default, raw_input creates a variable defined as a string. | ||
:variable = raw_input("display message") | :variable = raw_input("display message") | ||
− | name=raw_input("display message") | + | <nowiki>name=raw_input("display message")</nowiki> |
− | + | If you want to define another type of variable, such as an '''int''' or '''float''', you can wrap the <code>raw_input</code> function like so: | |
+ | <nowiki>number = int(raw_input("Enter Number:"))</nowiki> | ||
+ | |||
+ | ==slice== | ||
+ | :parse certain characters from a variable | ||
+ | <nowiki>x=variable | ||
+ | print x[1:3] | ||
+ | ari | ||
+ | |||
+ | x=variable | ||
+ | print [3:len(x)] | ||
+ | iable</nowiki> | ||
+ | |||
+ | slicing a string can be tricky too. think about this example '''<code>[:3]</code>''', this says to slice characters 0 through 3 from the string, however it does not include 3. the key to the logic is the word '''upto''', we are slicing from 0 upto 3. In otherwords, if you think about it as a fraction, we slice from 0 to 2.9999..., so it would '''NOT''' be inclusive of the 3rd character.<br> | ||
+ | this is also why if we do '''<code>[3:]</code>''' that would be '''from''', we are slicing from 3 to the end of the string, ie. 3+, so it would be inclusive of the 3rd character. | ||
+ | |||
+ | =Lists= | ||
+ | Another data type, lists can be used to store a list of items. | ||
+ | <nowiki>ie. numbers = [5, 6, 7, 8]</nowiki> | ||
+ | Lists can also be empty. | ||
+ | <nowiki>numbers = []</nowiki> | ||
+ | ==Access by Index== | ||
+ | You can access individual items, starting from 0. | ||
+ | <nowiki>ie. numbers = [5, 6, 7, 8] | ||
+ | print numbers[3] | ||
+ | >8</nowiki> | ||
+ | ==slicing== | ||
+ | slicing lists is a bit weird compared to accessing by index. Rather than starting at 0, you actually start at 1 when calling multiple items. | ||
+ | <nowiki>ie. letters = ['a', 'b', 'c', 'd'] | ||
+ | first_pair = letters [0:2] | ||
+ | second_pair = letters [3:4]</nowiki> | ||
+ | if you try to start at 0, it prints out an empty list. | ||
+ | <nowiki>print letters [0:0] | ||
+ | > []</nowiki> | ||
+ | I'm not sure why it behaves like this. | ||
+ | ==removing== | ||
+ | There are a few different ways to remove items from lists. | ||
+ | ===.pop()=== | ||
+ | returns the item being removed and then removes it from the list. | ||
+ | <nowiki>n = [1, 3, 5] | ||
+ | n.pop(1) | ||
+ | # Returns 3 (the item at index 1) | ||
+ | print n | ||
+ | # prints [1, 5]</nowiki> | ||
+ | ===.remove()=== | ||
+ | removes the actual item if found | ||
+ | <nowiki>n.remove(1) | ||
+ | # Removes 1 from the list, | ||
+ | # NOT the item at index 1 | ||
+ | print n | ||
+ | # prints [3, 5]</nowiki> | ||
+ | ===del()=== | ||
+ | deletes the item at the given index | ||
+ | <nowiki>del(n[1]) | ||
+ | # Doesn't return anything | ||
+ | print n | ||
+ | # prints [1, 5]</nowiki> | ||
+ | |||
+ | ==Generating Examples== | ||
+ | Generate a list of even numbers from 0-51 | ||
+ | <nowiki>evens_to_50 = [i for i in range(51) if i % 2 == 0]</nowiki> | ||
+ | Double numbers | ||
+ | <nowiki>doubles = [x * 2 for x in range(1, 6)]</nowiki> | ||
+ | |||
+ | =remove character special value= | ||
+ | :like with regular expression, you can remove a characters normal value by adding \ in front, however this does not work with all characters in python | ||
+ | 'Help! Help! I\'m being repressed!' | ||
+ | =Comparators= | ||
+ | ==basic comparisons== | ||
:<nowiki>==, !=, <, <=, >, or >=</nowiki> | :<nowiki>==, !=, <, <=, >, or >=</nowiki> | ||
− | + | ==Tuple== | |
+ | You can use a tuple as a way to compare against multiple values. I've only used it when doing an equal == comparison. | ||
+ | <nowiki>if type(num) in (int, float): | ||
+ | return abs(num)</nowiki> | ||
+ | In other words, if the type of the num parameter is equal to either int or float, then return the absolute value against 0. | ||
+ | ==Boolean Operators== | ||
:and, or, or not | :and, or, or not | ||
− | + | ===true, false=== | |
− | True and True is True | + | <nowiki>True and True is True |
− | + | True and False is False | |
− | + | False and True is False | |
− | + | False and False is False | |
− | + | True or True is True | |
− | + | True or False is True | |
− | + | False or True is True | |
− | + | False or False is False | |
− | + | Not True is False | |
− | + | Not False is True | |
− | + | ||
+ | this() and not that()</nowiki> | ||
+ | |||
+ | ==Conditional Statements== | ||
:if, else, and elif. | :if, else, and elif. | ||
def clinic(): | def clinic(): | ||
Line 77: | Line 196: | ||
clinic() | clinic() | ||
− | + | ===not in, or, and, is=== | |
− | : | + | some comparisons that can be used are: |
− | x=variable | + | ====not in==== |
− | print x[1:3] | + | <nowiki>if var not in range(x):</nowiki> |
− | + | ====or==== | |
− | + | <nowiki>if var == x or var == y:</nowiki> | |
− | x= | + | ====and==== |
− | print [ | + | <nowiki>if var == x and var == y:</nowiki> |
− | + | ====is==== | |
+ | <nowiki>if var is x:</nowiki> | ||
+ | |||
+ | =datetime= | ||
+ | builtin function within python with date time variable. | ||
+ | ==print== | ||
+ | <nowiki>print datetime.now()</nowiki> | ||
+ | ==manipulate== | ||
+ | <nowiki>print datetime.now().year | ||
+ | print datetime.now().month | ||
+ | print datetime.now().day</nowiki> | ||
+ | |||
+ | =functions= | ||
+ | functions are defined using <code>def</code> | ||
+ | <nowiki>ie. def my_function()</nowiki> | ||
+ | ==parameters== | ||
+ | parameters can be passed into a function inline when it is called. | ||
+ | <nowiki>ie def my_function(var_a, var_b, var_c)</nowiki> | ||
+ | ==return== | ||
+ | return returns the chosen value from the function, you can chose any value you want. Without return, the function will return <code>None</code>. | ||
+ | <nowiki>ie. def test_func(num): | ||
+ | number = num * 1 | ||
+ | return number | ||
+ | |||
+ | print test_func(1) | ||
+ | >1 | ||
+ | |||
+ | def test_func2(num): | ||
+ | number = num * 1 | ||
+ | |||
+ | print test_func2(1) | ||
+ | >None</nowiki> | ||
+ | |||
+ | ==Python baked in functions== | ||
+ | ===max()=== | ||
+ | returns the largest number from X arguments | ||
+ | <nowiki>ie. | ||
+ | def biggest_number(*args): | ||
+ | return max(args)</nowiki> | ||
+ | ===min()=== | ||
+ | opposite of max, gives the smallest number from X arguments | ||
+ | <nowiki>ie. | ||
+ | def smallest_number(*args): | ||
+ | return min(args)</nowiki> | ||
+ | ===abs()=== | ||
+ | absolute value from 0. if the number is a fraction, this will make it whole. | ||
+ | <nowiki>ie. | ||
+ | print abs(5) | ||
+ | >5</nowiki> | ||
+ | ===round()=== | ||
+ | rounded value of number. | ||
+ | <nowiki>ie. | ||
+ | print round(10.5) | ||
+ | >11</nowiki> | ||
+ | ===type()=== | ||
+ | returns the type of data in the argument. (ie, is it an '''int''' or '''float''' or '''string''', etc) | ||
+ | <nowiki>number_ = int(1) | ||
+ | float_ = float(4.5) | ||
+ | string_ = str("hello") | ||
+ | |||
+ | print type(number_) | ||
+ | print type(float_) | ||
+ | print type(string_)</nowiki> | ||
+ | |||
+ | ===append()=== | ||
+ | append a single (1) item to a list. You cannot use append() to add more than a single item at a time without outside help. | ||
+ | <nowiki>list.append(1)</nowiki> | ||
+ | |||
+ | ===extend()=== | ||
+ | extend the length of a list, you can also add multiple items natively. | ||
+ | <nowiki>suitcase.extend(["bathing suit", "towel", "sunscreen"])</nowiki> | ||
+ | |||
+ | ===index()=== | ||
+ | search for an item in a list | ||
+ | <nowiki>animals = ["ant", "bat", "cat"] | ||
+ | print animals.index("bat")</nowiki> | ||
+ | |||
+ | ===insert()=== | ||
+ | insert an item into a specific list position, shifting any existing items. | ||
+ | <nowiki>animals = ["ant", "bat", "cat"] | ||
+ | animals.insert(1, "dog") | ||
+ | print animals | ||
+ | > ["ant", "dog", "bat", "cat"]</nowiki> | ||
+ | |||
+ | ===sort()=== | ||
+ | sort a list smallest to largest, can be either numbers or letters. | ||
+ | <nowiki>function.sort()</nowiki> | ||
+ | |||
+ | ===remove()=== | ||
+ | remove item from a list. | ||
+ | <nowiki>listname.remove('value') | ||
+ | ie. backpack.remove('dagger')</nowiki> | ||
+ | |||
+ | ===range()=== | ||
+ | generates a list | ||
+ | ====range(stop)==== | ||
+ | stops at the specified interval | ||
+ | <nowiki>range(6) # => [0, 1, 2, 3, 4, 5]</nowiki> | ||
+ | ====range(start,stop)==== | ||
+ | starts and stops at the specified intervals | ||
+ | <nowiki>range(1, 6) # => [1, 2, 3, 4, 5]</nowiki> | ||
+ | ====range(start,stop,step)==== | ||
+ | starts and stops at the specified intervals within a specific iteration. | ||
+ | <nowiki>range(1, 6, 3) # => [1, 4]</nowiki> | ||
+ | You can also count backwards | ||
+ | <nowiki>range(100,-1,-1) # starts at 100 and goes to 0, stopping at -1</nowiki> | ||
+ | |||
+ | =Modules= | ||
+ | ==import== | ||
+ | you can import functions from modules to make reusing code easier. There are also built-in functions already in python to help save you time. | ||
+ | <nowiki> import math | ||
+ | math.sqrt(25) | ||
+ | > 5.0 </nowiki> | ||
+ | you can also import single functions to save you a bit of typing, albeit not much. | ||
+ | <nowiki>from module import function | ||
+ | ie. from math import sqrt</nowiki> | ||
+ | now you can call the function directly without having to put the module in front. | ||
+ | <nowiki> sqrt()</nowiki> | ||
+ | or import all the functions | ||
+ | <nowiki>from module import *</nowiki> | ||
+ | |||
+ | ==List all functions from a module== | ||
+ | <nowiki>import math | ||
+ | print dir(math)</nowiki> | ||
+ | |||
+ | =Loops= | ||
+ | ==For loops== | ||
+ | very similar to other scripting languages. Looping through a list will begin with the 0th element and go to the last. | ||
+ | <nowiki> for future_var in list | ||
+ | ie. | ||
+ | numbers [1, 2, 3] | ||
+ | for x in numbers | ||
+ | print x</nowiki> | ||
+ | ===dictionary loop=== | ||
+ | dictionaries are unordered, so every time you loop through, it will go in a different order. | ||
+ | <nowiki>d = {"foo" : "bar"} | ||
+ | for key in d: | ||
+ | print d[key]</nowiki> | ||
+ | |||
+ | ===counted loop=== | ||
+ | sometimes you need to loop through a list and run a series of actions against each element individually | ||
+ | <nowiki>n = [3, 5, 7] | ||
+ | for i in range(0, len(n)): | ||
+ | n[i] = n[i] * 2</nowiki> | ||
+ | ===implicit loops=== | ||
+ | Another way to do this is with an implicit count. notice how <code>num</code> is never defined nor is there a defined method to increase the num value. | ||
+ | <nowiki>hobbies = [] | ||
+ | |||
+ | for num in range(3): | ||
+ | hobby = raw_input("Tell me one of your favorite hobbies: ") | ||
+ | hobbies.append(hobby) | ||
+ | |||
+ | print hobbies</nowiki> | ||
+ | |||
+ | |||
+ | You can also do a similar method for printing individual characters in a string. | ||
+ | <nowiki>word = "eggs!" | ||
+ | |||
+ | # Your code here! | ||
+ | for c in word: | ||
+ | print c</nowiki> | ||
+ | |||
+ | ===Enumerate=== | ||
+ | This function supplies a corresponding index to each element in a list. | ||
+ | <nowiki>choices = ['pizza', 'pasta', 'salad', 'nachos'] | ||
+ | |||
+ | print 'Your choices are:' | ||
+ | for index, item in enumerate(choices): | ||
+ | print index, item</nowiki> | ||
+ | |||
+ | ===Multiple lists with zip=== | ||
+ | This allows you to iterate over multiple lists at the same time. | ||
+ | <nowiki>list_a = [3, 9, 17, 15, 19] | ||
+ | list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90] | ||
+ | |||
+ | for a, b in zip(list_a, list_b): | ||
+ | print a + " " + b</nowiki> | ||
+ | ==While Loop== | ||
+ | Loops until the condition is met. | ||
+ | <nowiki>while True: | ||
+ | print count | ||
+ | count += 1 | ||
+ | if count >= 10: | ||
+ | break</nowiki> | ||
+ | |||
+ | =Dictionaries= | ||
+ | Dictionaries use key-value pairs which allow a common (or uncommon) association of values. key-value pairs can be any string or number.<br> | ||
+ | ''You can also add lists into dictionaries.'' | ||
+ | <nowiki>d = {'key1' : 'value1', 'key2' : 'value2', 'key3' : 'value3'}</nowiki> | ||
+ | <nowiki>ie. | ||
+ | residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} | ||
+ | for animal in residents: | ||
+ | if animal in ('Sloth','Burmese Python'): | ||
+ | print residents[animal] | ||
+ | > 105 | ||
+ | > 106</nowiki> | ||
+ | |||
+ | <nowiki>my_dict = { | ||
+ | "Crypto": "ETH", | ||
+ | "Balance": 3.092, | ||
+ | "Value": 4200 | ||
+ | } | ||
+ | for key in my_dict: | ||
+ | print key, my_dict[key] | ||
+ | |||
+ | >Balance 3.092 | ||
+ | Crypto ETH | ||
+ | Value 4200</nowiki> | ||
+ | |||
+ | ==keys and values== | ||
+ | print an array of tuples with each tuple consisting of a key/value pair. | ||
+ | <nowiki>print dictionary.items()</nowiki> | ||
+ | print the dictionaries keys or values. these will NOT print in any specific order. | ||
+ | <nowiki>print dictionary.keys() | ||
+ | print dictionary.values()</nowiki> | ||
+ | |||
+ | ==adding to dictionary== | ||
+ | to add to an existing dictionary | ||
+ | <nowiki>dict_name[new_key] = new_value | ||
+ | menu['Spam'] = 2.50</nowiki> | ||
+ | |||
+ | ==deleting from dictionary== | ||
+ | ===single=== | ||
+ | to delete a single entry its easy. | ||
+ | <nowiki>del dict_name[key_name] | ||
+ | ie. del num_list[num_1]</nowiki> | ||
+ | ===multiple=== | ||
+ | Alternatively, if you need to delete multiple entries from a dictionary, it becomes a bit trickier as you can't loop using the dictionary you are modifying. If you do, you'll encounter an error because the dictionary size changes during iteration. <br> | ||
+ | A solution to this is creating a list of the items to be deleted. | ||
+ | <nowiki>ie. | ||
+ | zoo_animals = { 'Unicorn' : 'Cotton Candy House', | ||
+ | 'Sloth' : 'Rainforest Exhibit', | ||
+ | 'Bengal Tiger' : 'Jungle House', | ||
+ | 'Atlantic Puffin' : 'Arctic Exhibit', | ||
+ | 'Rockhopper Penguin' : 'Arctic Exhibit'} | ||
+ | |||
+ | dead_animals = ('Sloth', 'Bengal Tiger') | ||
+ | for animal in dead_animals: | ||
+ | if zoo_animals.has_key(animal): | ||
+ | del zoo_animals[animal]</nowiki> | ||
+ | The above will loop through the list called '''dead_animals''', then look in the '''zoo_animals''' dictionary for any matching keys, and if found, delete the key from '''zoo_animals'''. | ||
+ | |||
+ | =Examples= | ||
+ | ==Is Integer== | ||
+ | determine if X is an integer | ||
+ | <nowiki>def is_int(x): | ||
+ | absolute = abs(x) | ||
+ | rounded = round(absolute) | ||
+ | if absolute - rounded == 0: | ||
+ | return True | ||
+ | else: | ||
+ | return False | ||
+ | |||
+ | print is_int(10) | ||
+ | print is_int(10.5)</nowiki> | ||
+ | |||
+ | ==Add digits== | ||
+ | Take each individual number from a number and add them together (ie. 1234 = 1+2+3+4 = 10) | ||
+ | <nowiki>def digit_sum(n): | ||
+ | total = 0 | ||
+ | print "number: " + str(n) | ||
+ | for i in str(n): | ||
+ | print i | ||
+ | total += int(i) | ||
+ | print "total: " + str(total) | ||
+ | return total</nowiki> | ||
+ | |||
+ | ==Determine Factorial== | ||
+ | Calculate the factorial of a non-negative integer. | ||
+ | <nowiki>def factorial(x): | ||
+ | total = 1 | ||
+ | while x>0: | ||
+ | total *= x | ||
+ | x-=1 | ||
+ | return total | ||
+ | |||
+ | print factorial(5)</nowiki> | ||
+ | |||
+ | ==Prime number== | ||
+ | Determine if x is a prime number. | ||
+ | <nowiki>def is_prime(x): | ||
+ | if x < 2: | ||
+ | return False | ||
+ | else: | ||
+ | for n in range(2,x-1): | ||
+ | if x % n == 0: | ||
+ | return False | ||
+ | else: | ||
+ | return True</nowiki> | ||
+ | |||
+ | ==reverse letters in word== | ||
+ | <nowiki>def reverse(text): | ||
+ | print "text: " + str(text) | ||
+ | for letter in range(len(text)-1,-1,-1): | ||
+ | if letter == len(text)-1: | ||
+ | output = text[letter] | ||
+ | else: | ||
+ | output += str(text[letter]) | ||
+ | print output | ||
+ | return output</nowiki> | ||
+ | |||
+ | ==strip vowels from string== | ||
+ | <nowiki>def anti_vowel(text): | ||
+ | vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"] | ||
+ | newString = "" | ||
+ | for i in range(len(text)): | ||
+ | if text[i] not in vowels: | ||
+ | newString += text[i] | ||
+ | return newString</nowiki> | ||
+ | |||
+ | ==scrabble score== | ||
+ | Using a dictionary list for letters and their corresponding values, take a word, make the letters lowercase, then determine the total score of the word. | ||
+ | <nowiki>score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, | ||
+ | "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, | ||
+ | "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, | ||
+ | "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, | ||
+ | "x": 8, "z": 10} | ||
+ | |||
+ | def scrabble_score(word): | ||
+ | result = 0 | ||
+ | for letter in word: | ||
+ | letter = letter.lower() | ||
+ | if letter in score: | ||
+ | print "letter found: " + str(letter) + " with score: " + str(score[letter]) | ||
+ | result += int(score[letter]) | ||
+ | print result | ||
+ | return result</nowiki> | ||
+ | |||
+ | ==censor word== | ||
+ | censor word in a string with a series of asterisks that match the word letter count. | ||
+ | <nowiki>def censor(text, word): | ||
+ | censor = "" | ||
+ | if word in text: | ||
+ | for i in range(len(word)): | ||
+ | censor += "*" | ||
+ | result = text.replace(word,censor) | ||
+ | print result | ||
+ | return result</nowiki> | ||
+ | |||
+ | ==median== | ||
+ | determine the median of a list. if even, take the (2) numbers around the median position and average them together. make sure the list is sorted before getting the median. | ||
+ | <nowiki>def median(lst): | ||
+ | lst = sorted(lst) | ||
+ | if len(lst) % 2 == 0: | ||
+ | b = lst[len(lst) / 2] | ||
+ | c = lst[len(lst) / 2 - 1] | ||
+ | return float(b + c) / 2 | ||
+ | else: | ||
+ | if len(lst) == 1: | ||
+ | return lst[0] | ||
+ | else: | ||
+ | return lst[len(lst) / 2]</nowiki> |
Latest revision as of 00:52, 11 May 2021
[edit] reserved words
These are some words that you should not use in python as they are reserved.
- list
- reserved word that should not be used as a variable name.
[edit] variables
- variables can be integers, floats, or boolean. Integers are whole numbers, floats are numbers with remainders, boolean is either True of False.
variable=integer
[edit] float vars
If you want the fraction included in the var, you need to define it as a float, otherwise python will automatically round the result to a whole number.
floating_var = float(7)/2
This will give you the fraction from dividing 7/2.
[edit] convert int to string
age = 13 print str(age)
[edit] convert string to int
n1 = "100" n2 = "10" int_addition = int(n1) + int(n2)
[edit] convert to float
n1 = "7.5" print float(n1)
[edit] verify is alpha (letters) only
variable_name.isalpha() ie. if variable.isalpha():
[edit] arithmetic operators
[edit] add/subtract/multiply/divide/exponentiation/modulo
[edit] exponentiation (exponential, similar to square roots)
2 ** 3=8 (2*2*2)
[edit] modulo (remainder)
5 % 2=1 (5/2 = 2 with a remainder of 1)
[edit] shorthand
+= add vars and update first var ie. sandwich_price += sales_tax -= subtract vars and update first var ie. money_in_wallet -= sandwich_price
[edit] comments
- # for single like quote or """ quote """ for multi line quote
#quote """quote quote"""
[edit] print
[edit] display output
print "Hello World"
[edit] display specific letter, left to right, 0 forward
print "TEST"[0] = "T"
[edit] trailing comma
adding a trailing comma ensures that we keep printing on the same line.
print number,
[edit] strings
[edit] multi-line string
- for strings that span multiple lines, use triple quotes
address_string = """136 Whowho Rd Apt 7 Whosville, WZ 44494"""
[edit] string continuation
- it appears you can continue a string by using
\
though i've only seen this behavior using string concatenation
ie. print "Ah, so your name is %s, your quest is %s, " \ "and your favorite color is %s." % (name, quest, color)
[edit] string methods
- len() ; lower() ; upper() ; str()
[edit] len() = get length of string - applies to anything within the parentheses
len(length) = 6
[edit] lower() = convert to lowercase - applies to only the value after the "." . Dot notation only works on strings
LOWERCASE.lower() = lowercase
[edit] upper() = convert to uppercase - applies to only the value after the "." . Dot notation only works on strings
uppercase.upper() = UPPERCASE
[edit] str() = convert to string - applies to anything within the parentheses
str(3.14) = "3.14"
[edit] String Formatting
- concatenating strings through short hand
string_1 = "Camelot" string_2 = "place" print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)
[edit] define var length
when doing concatenating, you can specify the var length to be displayed. this is especially helpful with numbers when trying to apply formatting.
print '%02d:%02d:%02d' % (now.hour, now.minute, now.second) 21:02:18
notice how the minute is 02
. If this was not defined to be (2) digits, it would have only been a 2 without the preceeding 0.
[edit] user input
by default, raw_input creates a variable defined as a string.
- variable = raw_input("display message")
name=raw_input("display message")
If you want to define another type of variable, such as an int or float, you can wrap the raw_input
function like so:
number = int(raw_input("Enter Number:"))
[edit] slice
- parse certain characters from a variable
x=variable print x[1:3] ari x=variable print [3:len(x)] iable
slicing a string can be tricky too. think about this example [:3]
, this says to slice characters 0 through 3 from the string, however it does not include 3. the key to the logic is the word upto, we are slicing from 0 upto 3. In otherwords, if you think about it as a fraction, we slice from 0 to 2.9999..., so it would NOT be inclusive of the 3rd character.
this is also why if we do [3:]
that would be from, we are slicing from 3 to the end of the string, ie. 3+, so it would be inclusive of the 3rd character.
[edit] Lists
Another data type, lists can be used to store a list of items.
ie. numbers = [5, 6, 7, 8]
Lists can also be empty.
numbers = []
[edit] Access by Index
You can access individual items, starting from 0.
ie. numbers = [5, 6, 7, 8] print numbers[3] >8
[edit] slicing
slicing lists is a bit weird compared to accessing by index. Rather than starting at 0, you actually start at 1 when calling multiple items.
ie. letters = ['a', 'b', 'c', 'd'] first_pair = letters [0:2] second_pair = letters [3:4]
if you try to start at 0, it prints out an empty list.
print letters [0:0] > []
I'm not sure why it behaves like this.
[edit] removing
There are a few different ways to remove items from lists.
[edit] .pop()
returns the item being removed and then removes it from the list.
n = [1, 3, 5] n.pop(1) # Returns 3 (the item at index 1) print n # prints [1, 5]
[edit] .remove()
removes the actual item if found
n.remove(1) # Removes 1 from the list, # NOT the item at index 1 print n # prints [3, 5]
[edit] del()
deletes the item at the given index
del(n[1]) # Doesn't return anything print n # prints [1, 5]
[edit] Generating Examples
Generate a list of even numbers from 0-51
evens_to_50 = [i for i in range(51) if i % 2 == 0]
Double numbers
doubles = [x * 2 for x in range(1, 6)]
[edit] remove character special value
- like with regular expression, you can remove a characters normal value by adding \ in front, however this does not work with all characters in python
'Help! Help! I\'m being repressed!'
[edit] Comparators
[edit] basic comparisons
- ==, !=, <, <=, >, or >=
[edit] Tuple
You can use a tuple as a way to compare against multiple values. I've only used it when doing an equal == comparison.
if type(num) in (int, float): return abs(num)
In other words, if the type of the num parameter is equal to either int or float, then return the absolute value against 0.
[edit] Boolean Operators
- and, or, or not
[edit] true, false
True and True is True True and False is False False and True is False False and False is False True or True is True True or False is True False or True is True False or False is False Not True is False Not False is True this() and not that()
[edit] Conditional Statements
- if, else, and elif.
def clinic(): print "You've just entered the clinic!" print "Do you take the door on the left or the right?" answer = raw_input("Type left or right and hit 'Enter'.").lower() if answer == "left" or answer == "l": print "This is the Verbal Abuse Room, you heap of parrot droppings!" elif answer == "right" or answer == "r": print "Of course this is the Argument Room, I've told you that already!" else: print "You didn't pick left or right! Try again." clinic() clinic()
[edit] not in, or, and, is
some comparisons that can be used are:
[edit] not in
if var not in range(x):
[edit] or
if var == x or var == y:
[edit] and
if var == x and var == y:
[edit] is
if var is x:
[edit] datetime
builtin function within python with date time variable.
[edit] print
print datetime.now()
[edit] manipulate
print datetime.now().year print datetime.now().month print datetime.now().day
[edit] functions
functions are defined using def
ie. def my_function()
[edit] parameters
parameters can be passed into a function inline when it is called.
ie def my_function(var_a, var_b, var_c)
[edit] return
return returns the chosen value from the function, you can chose any value you want. Without return, the function will return None
.
ie. def test_func(num): number = num * 1 return number print test_func(1) >1 def test_func2(num): number = num * 1 print test_func2(1) >None
[edit] Python baked in functions
[edit] max()
returns the largest number from X arguments
ie. def biggest_number(*args): return max(args)
[edit] min()
opposite of max, gives the smallest number from X arguments
ie. def smallest_number(*args): return min(args)
[edit] abs()
absolute value from 0. if the number is a fraction, this will make it whole.
ie. print abs(5) >5
[edit] round()
rounded value of number.
ie. print round(10.5) >11
[edit] type()
returns the type of data in the argument. (ie, is it an int or float or string, etc)
number_ = int(1) float_ = float(4.5) string_ = str("hello") print type(number_) print type(float_) print type(string_)
[edit] append()
append a single (1) item to a list. You cannot use append() to add more than a single item at a time without outside help.
list.append(1)
[edit] extend()
extend the length of a list, you can also add multiple items natively.
suitcase.extend(["bathing suit", "towel", "sunscreen"])
[edit] index()
search for an item in a list
animals = ["ant", "bat", "cat"] print animals.index("bat")
[edit] insert()
insert an item into a specific list position, shifting any existing items.
animals = ["ant", "bat", "cat"] animals.insert(1, "dog") print animals > ["ant", "dog", "bat", "cat"]
[edit] sort()
sort a list smallest to largest, can be either numbers or letters.
function.sort()
[edit] remove()
remove item from a list.
listname.remove('value') ie. backpack.remove('dagger')
[edit] range()
generates a list
[edit] range(stop)
stops at the specified interval
range(6) # => [0, 1, 2, 3, 4, 5]
[edit] range(start,stop)
starts and stops at the specified intervals
range(1, 6) # => [1, 2, 3, 4, 5]
[edit] range(start,stop,step)
starts and stops at the specified intervals within a specific iteration.
range(1, 6, 3) # => [1, 4]
You can also count backwards
range(100,-1,-1) # starts at 100 and goes to 0, stopping at -1
[edit] Modules
[edit] import
you can import functions from modules to make reusing code easier. There are also built-in functions already in python to help save you time.
import math math.sqrt(25) > 5.0
you can also import single functions to save you a bit of typing, albeit not much.
from module import function ie. from math import sqrt
now you can call the function directly without having to put the module in front.
sqrt()
or import all the functions
from module import *
[edit] List all functions from a module
import math print dir(math)
[edit] Loops
[edit] For loops
very similar to other scripting languages. Looping through a list will begin with the 0th element and go to the last.
for future_var in list ie. numbers [1, 2, 3] for x in numbers print x
[edit] dictionary loop
dictionaries are unordered, so every time you loop through, it will go in a different order.
d = {"foo" : "bar"} for key in d: print d[key]
[edit] counted loop
sometimes you need to loop through a list and run a series of actions against each element individually
n = [3, 5, 7] for i in range(0, len(n)): n[i] = n[i] * 2
[edit] implicit loops
Another way to do this is with an implicit count. notice how num
is never defined nor is there a defined method to increase the num value.
hobbies = [] for num in range(3): hobby = raw_input("Tell me one of your favorite hobbies: ") hobbies.append(hobby) print hobbies
You can also do a similar method for printing individual characters in a string.
word = "eggs!" # Your code here! for c in word: print c
[edit] Enumerate
This function supplies a corresponding index to each element in a list.
choices = ['pizza', 'pasta', 'salad', 'nachos'] print 'Your choices are:' for index, item in enumerate(choices): print index, item
[edit] Multiple lists with zip
This allows you to iterate over multiple lists at the same time.
list_a = [3, 9, 17, 15, 19] list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90] for a, b in zip(list_a, list_b): print a + " " + b
[edit] While Loop
Loops until the condition is met.
while True: print count count += 1 if count >= 10: break
[edit] Dictionaries
Dictionaries use key-value pairs which allow a common (or uncommon) association of values. key-value pairs can be any string or number.
You can also add lists into dictionaries.
d = {'key1' : 'value1', 'key2' : 'value2', 'key3' : 'value3'} ie. residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} for animal in residents: if animal in ('Sloth','Burmese Python'): print residents[animal] > 105 > 106
my_dict = { "Crypto": "ETH", "Balance": 3.092, "Value": 4200 } for key in my_dict: print key, my_dict[key] >Balance 3.092 Crypto ETH Value 4200
[edit] keys and values
print an array of tuples with each tuple consisting of a key/value pair.
print dictionary.items()
print the dictionaries keys or values. these will NOT print in any specific order.
print dictionary.keys() print dictionary.values()
[edit] adding to dictionary
to add to an existing dictionary
dict_name[new_key] = new_value menu['Spam'] = 2.50
[edit] deleting from dictionary
[edit] single
to delete a single entry its easy.
del dict_name[key_name] ie. del num_list[num_1]
[edit] multiple
Alternatively, if you need to delete multiple entries from a dictionary, it becomes a bit trickier as you can't loop using the dictionary you are modifying. If you do, you'll encounter an error because the dictionary size changes during iteration.
A solution to this is creating a list of the items to be deleted.
ie. zoo_animals = { 'Unicorn' : 'Cotton Candy House', 'Sloth' : 'Rainforest Exhibit', 'Bengal Tiger' : 'Jungle House', 'Atlantic Puffin' : 'Arctic Exhibit', 'Rockhopper Penguin' : 'Arctic Exhibit'} dead_animals = ('Sloth', 'Bengal Tiger') for animal in dead_animals: if zoo_animals.has_key(animal): del zoo_animals[animal]
The above will loop through the list called dead_animals, then look in the zoo_animals dictionary for any matching keys, and if found, delete the key from zoo_animals.
[edit] Examples
[edit] Is Integer
determine if X is an integer
def is_int(x): absolute = abs(x) rounded = round(absolute) if absolute - rounded == 0: return True else: return False print is_int(10) print is_int(10.5)
[edit] Add digits
Take each individual number from a number and add them together (ie. 1234 = 1+2+3+4 = 10)
def digit_sum(n): total = 0 print "number: " + str(n) for i in str(n): print i total += int(i) print "total: " + str(total) return total
[edit] Determine Factorial
Calculate the factorial of a non-negative integer.
def factorial(x): total = 1 while x>0: total *= x x-=1 return total print factorial(5)
[edit] Prime number
Determine if x is a prime number.
def is_prime(x): if x < 2: return False else: for n in range(2,x-1): if x % n == 0: return False else: return True
[edit] reverse letters in word
def reverse(text): print "text: " + str(text) for letter in range(len(text)-1,-1,-1): if letter == len(text)-1: output = text[letter] else: output += str(text[letter]) print output return output
[edit] strip vowels from string
def anti_vowel(text): vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"] newString = "" for i in range(len(text)): if text[i] not in vowels: newString += text[i] return newString
[edit] scrabble score
Using a dictionary list for letters and their corresponding values, take a word, make the letters lowercase, then determine the total score of the word.
score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, "x": 8, "z": 10} def scrabble_score(word): result = 0 for letter in word: letter = letter.lower() if letter in score: print "letter found: " + str(letter) + " with score: " + str(score[letter]) result += int(score[letter]) print result return result
[edit] censor word
censor word in a string with a series of asterisks that match the word letter count.
def censor(text, word): censor = "" if word in text: for i in range(len(word)): censor += "*" result = text.replace(word,censor) print result return result
[edit] median
determine the median of a list. if even, take the (2) numbers around the median position and average them together. make sure the list is sorted before getting the median.
def median(lst): lst = sorted(lst) if len(lst) % 2 == 0: b = lst[len(lst) / 2] c = lst[len(lst) / 2 - 1] return float(b + c) / 2 else: if len(lst) == 1: return lst[0] else: return lst[len(lst) / 2]