Define a variable my_variable=10; Booleans my_bool=True; my_new_bool=False; Comment # Put the “#” symbol at the start of the line to define a comment Whitespace matters # This will NOT run! def spam(): eggs = 12 return eggs print spam() 5) Proper Whitespace def spam(): eggs = 12 #This line is indented because it is in the spam method return eggs print spam() 6) Multi-Line Comments - use Triple Quote (“””) """ This is a multi-line comment ok""" 7) Print Stuff to the console a=1 print a 8) Math “”” + , -, /, * ** is exponent % is modulo - remainder - 6%5 is 6/5, which is 1 remainder 1, so the answer is 1 9) Here’s an example meal = 44.50 tax = 0.0675 tip = 0.15 meal = meal + meal * tax total=meal+meal*tip print("%.2f" % total) # We’ll get into print formatting further down 10) String Definition: brian="Hello life!" 11) Use a backslash for special characters 'This isn't flying, this is falling with style!' # THIS DOESN’T work because python sees the single quotes and tries to make something out of it 'This isn\'t flying, this is falling with style!' # The backslash makes it work 12) Indexing string characters +---+---+---+---+---+---+ | P | Y | T | H | O | N | +---+---+---+---+---+---+ 0 1 2 3 4 5 “PYTHON”[3] #Returns “H” 13) String lengths my_string=”PYTHON” print len(my_string) # returns 6 14) Lower-case String Conversions my_string = “PYTHON” my_lower_string = my_string.lower() # returns “python”, but my_string is still "PYTHON" 15) Upper-case String Conversions my_string = “python” my_string.lower() # returns “PYTHON” 16) Number to String pi=3.14 pistr=str(pi) print pistr 17) Dot notation - use len() and str() for general types of objects (not just strings), but “upper()” and “lower()” are methods of the string object, so they are expressed as my_str.upper() 18) Concatenation - use a “+” print "Spam "+"and "+"eggs" # returns “Spam and eggs” 19) Concatenate numbers into a string: print "The value of pi is around " + str(3.14) 20) String formatting with variable placement string_1 = "Camelot" string_2 = "place" print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2) # Returns “Let's not go to Camelot. 'Tis a silly place.” 21) Gather Input and another string formatting example name = raw_input("What is your name?") quest = raw_input("What is your quest?") color = raw_input("What is your favorite color?") print "Ah, so your name is %s, your quest is %s, " \ "and your favorite color is %s." % (name, quest, color) 22) Datetime Library from datetime import datetime now = datetime.now() print now # Returns 2016-01-16 03:49:53.687654 23) Extract Specific Date and Time Elements from datetime import datetime now = datetime.now() print now # 2016-01-16 03:49:53.687654 print now.year # 2016 print now.month # 1 print now.day # 16 24) Date / String Formatting from datetime import datetime now = datetime.now() print '%s/%s/%s' % (now.year, now.month, now.day) “Returns 2016/1/16 25) Time Formatting from datetime import datetime now = datetime.now() print '%s:%s:%s' % (now.hour, now.minute, now.second) # Returns 3:53:22 26) Conditionals and Flow 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() 27) Comparators return True or False “””Equal to (==) Not equal to (!=) Less than (<) Less than or equal to (<=) Greater than (>) Greater than or equal to (>=)””” 28) And / Or / Not a=True b=False a and b # False a or b #True not b #True 29) ELSE answer = "'Tis but a scratch!" def black_knight(): if answer == "'Tis but a scratch!": return True else: return False # Make sure this returns False 30) ELSE IF: def greater_less_equal_5(answer): if answer>5: return 1 elif answer<5: return -1 else: return 0 print greater_less_equal_5(4) print greater_less_equal_5(5) print greater_less_equal_5(6) 31) IS ALPHA: tmp = "TEMP" tmp2 = "TEMP2" tmp.isalpha() #returns true tmp2.isalpha() #returns false 32) Fully functional pig latin coverter: pyg = 'ay' original = raw_input('Enter a word:') if len(original) > 0 and original.isalpha(): print original word=original.lower() first=word[0] new_word=word+first+pyg new_word=new_word[1:len(new_word)] print new_word else: print 'empty' 33) FUNCTIONS example: def tax(bill): # accepts bill as an input """Adds 8% tax to a restaurant bill.""" bill *= 1.08 print "With tax: %f" % bill return bill # returns bill as a result to be stored in the new variable def tip(bill): # This is the definition of the function "tip". Note that the function doesn't have an end - return ends the function """Adds 15% tip to a restaurant bill.""" bill *= 1.15 print "With tip: %f" % bill return bill meal_cost = 100 meal_with_tax = tax(meal_cost) meal_with_tip = tip(meal_with_tax) 34) FUNCTIONS must be CALLED! def square(n): """Returns the square of a number.""" squared = n**2 print "%d squared is %d." % (n, squared) return squared # Here is the function call: square(10) #call the function 'square' with the parameter 10 35) Functions can call other functions def one_good_turn(n): return n + 1 def deserves_another(n): return one_good_turn(n) + 2 print deserves_another(3) 36) IMPORT LIBRARIES import math print math.sqrt(25) 37) IMPORT A METHOD FROM A LIBRARY (SO YOU CAN CALL "sqrt" instead of "math.sqrt") from math import sqrt print sqrt(25) 38) UNIVERSAL IMPORT - BRING IN ALL FUNCTIONS from math import * 39) GET A LIST OF ALL IMPORTED METHODS import math # Imports the math module everything = dir(math) # Sets everything to a list of things from math print everything # Prints 'em all! 40) Other built-in functions - max(), min(), abs() def biggest_number(*args): #NOTE THE "(*args)". This tells python to expect an unspecified number of arguments print max(args) return max(args) def smallest_number(*args): print min(args) return min(args) def distance_from_zero(arg): print abs(arg) return abs(arg) biggest_number(-10, -5, 5, 10) smallest_number(-10, -5, 5, 10) distance_from_zero(-10) 41) Get the type of a variable # Print out the types of an integer, a float, # and a string on separate lines below. print type(4) # <type 'int'> print type(2.2) # <type 'float'> print type ('ABC') # <type 'str'> 42) EXAMPLE FUNCTION WITH DEFINITION, ARGUMENTS, AND CONDITIONAL FLOW: def shut_down(s): if s=="yes": return "Shutting down" elif s=="no": return "Shutdown aborted" else: return "Sorry" #Again, not no end of function line print shut_down('yes') #the function will not run unless called print shut_down('no') print shut_down(12) 43) Sample function that checks variable types: def distance_from_zero(x): if type(x)==int or type(x)==float: return abs(x) else: return "Nope" print distance_from_zero(1) print distance_from_zero(1.1) print distance_from_zero("k") 44) Sample of calculating vacation cost - pull in variables from multiple functionns def hotel_cost(nights): return 140*nights def plane_ride_cost(city): if city=="Charlotte": return 183 elif city=="Tampa": return 220 elif city=="Pittsburgh": return 222 elif city=="Los Angeles": return 475 def rental_car_cost(days): if days>=7: return 40*days-50 elif days>=3: return 40*days-20 else: return 40*days def trip_cost(city,days,spending_money): return hotel_cost(days)+plane_ride_cost(city)+rental_car_cost(days)+spending_money print trip_cost("Los Angeles",5,570) 45) Lists - store multiple datatypes in one variable zoo_animals = ["pangolin", "cassowary", "sloth", "zebra"]; # One animal is missing! if len(zoo_animals) > 3: print "The first animal at the zoo is the " + zoo_animals[0] #The list's first item is at index 0, not 1! print "The second animal at the zoo is the " + zoo_animals[1] print "The third animal at the zoo is the " + zoo_animals[2] print "The fourth animal at the zoo is the " + zoo_animals[3] 46) You can access or assign items to a list(): abc = ["Aa","Bb","Cc"] print abc[0] # returns Aa abc[2]="Dd" # places "Dd" at index 2 (in place of "Cc") 47) Append to a list abc = ["Aa","Bb","Cc"] abc.append("Dd") abc[3] #Will return "Dd" 48) Access a portion of a list abc = ["Aa","Bb","Cc","Dd","Ee"] print abc[1:3] "Returns "Bb", "Cc", and "Dd" 49) Slice a list from the start or end: abc = ["Aa","Bb","Cc","Dd","Ee"] print abc[:3] #Returns "Aa", "Bb", "Cc", and "Dd" print abc[2:] #Returns "Cc", "Dd", and "Ee" 50) List index animals = ["aardvark", "badger", "duck", "emu", "fennec fox"] duck_index = animals.index("duck") # Use index() to find "duck" # would return 2 51) List insert (not append) animals = ["aardvark", "badger", "duck", "emu", "fennec fox"] duck_index = animals.index("duck") # Use index() to find "duck" #duck_index is 2 animals.insert(duck_index,"cobra") #Puts "cobra" before duck_index (makes cobra index 2, the third item in the list, in front of duck print duck_index,animals # duck_index is 2, which now contains cobra, so this will print "cobra" 52) Iterate over each item in a list: my_list = [1,9,3,8,5,7] for number in my_list: # Your code here print 2*number # Returns 2, 18, 6, 16, 10, 14 53) List Sort my_list.sort() # sorts from lowest to highest 54) Dictionaries - like lists, but use a key:value pair to find items (instead of an index as in a list) NOTE THE CURLY BRACES IN A DICTIONARY COMPARED TO THE HARD BRACKETS IN A LIST # Assigning a dictionary with three key-value pairs to residents: residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} #The first item's key is Puffin, and the value is 104 print residents['Puffin'] # Prints Puffin's room number # Your code here! print residents['Sloth'] print residents['Burmese Python'] 55) Dictionaries are mutable - you can add and remove items from them: menu = {} # Empty dictionary menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair print menu['Chicken Alfredo'] # Your code here: Add some dish-price pairs to menu! menu['Sushi']=17 menu['Pasta']=13 menu['Dosa']=10 print "There are " + str(len(menu)) + " items on the menu." print menu 56)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question