Advertisement
Guest User

Untitled

a guest
Nov 11th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.46 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. print "Python Examples\n --By The Tutorial Doctor\n"
  3.  
  4. ## PRINTING
  5.  
  6. print 'Hello'
  7.  
  8. print 'Hello','Editorial'
  9.  
  10. # Concatenate/Append text (gives errors if not strings)
  11. print 'Hello' + 'Folks'
  12.  
  13. print 'Hello' + ' Folks' # have to add your own space
  14.  
  15. print 27
  16.  
  17.  
  18. # VARIABLES
  19. #There are different types of variables: character, string, integer, float, boolean, array/list, dictionary, and a few others.
  20.  
  21. # A character
  22. at = "@"
  23.  
  24. # A string
  25. name = 'Jackie'
  26.  
  27. # An integer
  28. favorite_number = 4
  29.  
  30. # A float
  31. height = 6.5
  32.  
  33. # A boolean
  34. IamCool = True
  35.  
  36. # You can assign a new value to a variable
  37. IamCool = False
  38.  
  39. # An array
  40. array_of_colors = ['red','orange','yellow','green','blue','indigo','violet']
  41. array_of_numbers = [23,13.4,1,782]
  42. mixed_array = ['Zillow',34.9,True,798]
  43.  
  44. # A dictionary
  45. description = {'eyeColor':'brown','physique':'muscled','demeanor':'confident'}
  46. print description['eyeColor']
  47. print description['physique']
  48. print description['demeanor']
  49.  
  50. # EXTRA
  51.  
  52. # ID of a variable
  53. print id(name)
  54.  
  55. #####
  56.  
  57. # STRINGS
  58. # A string is string of characters
  59.  
  60. ## Empty string
  61. first_name = ""
  62. last_name = ""
  63.  
  64.  
  65. ## Asign a value to a string
  66. first_name = "joe"
  67. last_name = "shmo"
  68. occupation = "Truck Driver"
  69.  
  70.  
  71. ## Adding strings (concatenation)
  72. print first_name + last_name
  73.  
  74. ## Adding a space between string variables
  75. print first_name + " " + last_name
  76.  
  77. ## Starting a new line (escape characters)
  78. print first_name + "\n" + last_name
  79.  
  80. ## Adding variables inside of a string (string formatting)
  81. print "Hello %s" %(first_name)
  82.  
  83. ## Multiple variables inside of a string
  84. print "Hello %s %s" %(first_name,last_name)
  85.  
  86. ## There is another way to format strings
  87. greeting = 'Hello {name}, my name is {myname}'
  88. print greeting.format(name='Joseph',myname='Joey')
  89.  
  90. ## Print a string several times
  91. print first_name * 4
  92.  
  93. ## Get index of a string
  94. ## Indices begin at 0
  95. print first_name[0]
  96. print first_name[1]
  97. print first_name[2]
  98.  
  99. ## A multi-line string
  100. """Multi-Line strings are sometimes used as multi-line comments, since python doesn't have syntax for multi-line comments."""
  101.  
  102.  
  103. # STRING FUNCTIONS
  104. print first_name.capitalize()
  105. print len(occupation)
  106.  
  107. #####
  108.  
  109. # INTEGERS
  110. # An integer is a whole number
  111.  
  112. number1 = 12
  113. number2 = 144
  114. number3 = "67" #not an integer
  115.  
  116. #Add
  117. print number1 + number2
  118.  
  119. #Subtract
  120. print number2 - number1
  121.  
  122. #Multiply
  123. print number1 * number2
  124.  
  125. #Divide
  126. print number2/number1
  127.  
  128. #Exponents
  129. print number2**number1
  130. #Same
  131. print pow(number2,number1)
  132.  
  133. #Square root
  134. print number2**(1/2.0)
  135.  
  136. #Order of operations
  137. print (number1 + number2) * 3 + (number1**3)
  138.  
  139. # Increment an integer
  140. number1 = number1 + 1
  141. print number1
  142.  
  143. # Convert a string to an integer
  144. number3 = int(number3)
  145.  
  146. #####
  147.  
  148. #FLOAT
  149. # A float is a decimal. Many of the integer operations can be applied to floats.
  150. pi = 3.14
  151. print pi
  152. #####
  153.  
  154. # TUPLES
  155. ## Tuples are like lists, but cannot be changed (they are immutable).
  156.  
  157. x = 0
  158. y = 1
  159.  
  160.  
  161. ## Create a Tuple
  162. position = (50,200)
  163.  
  164.  
  165. ## Get tuple index
  166. print position[x]
  167.  
  168. #####
  169.  
  170. # LISTS/Array
  171. # Called a list in python.
  172.  
  173. # Create a list
  174. Clients = ['Cierra','Lisa','Ibrahim','Eric','Nancy','Terry','Sarah']
  175. print Clients
  176.  
  177. Employees = ['Eric','Margaret','Paul','Ole','Yul']
  178. print Employees
  179.  
  180. ### LIST FUNCTIONS
  181. # List Index
  182. print Clients[0]
  183.  
  184. # List index range
  185. print Clients[0:4]
  186.  
  187. # Append to a list
  188. Clients.append('Joe')
  189. print Clients
  190. #Same as:
  191. #Clients[len(Clients):] = ['Joe'].
  192.  
  193. # Remove from a list
  194. Clients.remove('Joe')
  195. print Clients
  196.  
  197. # Insert item into a list at a location
  198. Clients.insert(0,'Lee')
  199. print Clients
  200.  
  201. # Reverse a list
  202. Clients.reverse()
  203. print Clients
  204.  
  205. # Sort a list
  206. Clients.sort()
  207. print Clients
  208.  
  209. # Remove an item at a location
  210. Clients.pop(0)
  211. print Clients
  212.  
  213. # Return the index of an item in the list
  214. print Clients.index('Lee# Extend a list with another list
  215. Clients.extend(Employees)
  216. print Clients
  217. # Same as:
  218. #Clients[len(Clients):] = Clients
  219.  
  220. # Count how many times an item appears in a list
  221. print Clients.count('Lisa
  222. ### EXTRA
  223.  
  224. # Loop through a list
  225. for item in Clients:
  226. print item
  227.  
  228. #Remove a list from a list
  229. for i in Clients:
  230. if i in Employees:
  231. Clients.remove(i)
  232. print Clients
  233.  
  234. #####
  235.  
  236. ### DICTIONARIES/Associative array
  237.  
  238. # Create a dictionary (dictionary_name = {key:value})
  239. inventory = {'light':'flashlight'}
  240. print inventory
  241.  
  242.  
  243. # Print the value of a key
  244. print inventory['light']
  245.  
  246.  
  247. # Update Dictionary
  248. inventory.update({'map':'New York'})
  249. inventory.update({'phone':'Flip Phone'})
  250. print inventory
  251.  
  252.  
  253. # Update the key if it is already in the dictionary
  254. inventory.update({'map':'Atlanta'})
  255. inventory.update({'map':'New York'})
  256. print inventory['map']
  257.  
  258.  
  259. # Get all keys (outputs as a list)
  260. print inventory.keys()
  261.  
  262.  
  263. # Get all values (ouptuts as a list)
  264. print inventory.values()
  265.  
  266.  
  267. # Copy dictionary items as a list of tuples
  268. # Basically converts a dictionary to a a list of tuples.
  269. print inventory.items()
  270.  
  271.  
  272. # Length of a dictionary
  273. print len(inventory)
  274.  
  275.  
  276. # Delete inventory item
  277. del inventory['map']
  278. print inventory
  279.  
  280.  
  281. # Iterate over dictionary
  282. #print iter(inventory)
  283. #print inventory.iterkeys()
  284. #print inventory.itervalues()
  285.  
  286. # Remove item, and returns its value
  287. inventory.pop('phone Alternately: inventory.popitem()
  288. print inventory
  289.  
  290. # View keys of a dictionary
  291. print inventory.viewkeys()
  292.  
  293. # View values of a dictionary
  294. print inventory.viewvalues()
  295.  
  296. # View all items in a dictionary
  297. print inventory.viewitems()
  298.  
  299. #####
  300.  
  301. ### CONDITIONALS
  302.  
  303. on = True
  304. number = 51
  305.  
  306. # If equal to
  307. if on == True:
  308. print on
  309.  
  310. # Same (for booleans)
  311. if on:
  312. print on
  313.  
  314. # If not equal to
  315. if on != False:
  316. print on
  317.  
  318. # If greater than
  319. if number > 23:
  320. print number
  321.  
  322. # If less than
  323. if number < 77:
  324. print number
  325.  
  326. #####
  327.  
  328. ## BOOLEANS (BEG)
  329. # if, else, and else if(elif)
  330.  
  331. location = 0
  332.  
  333. if location == 50:
  334. print 'Halfway there.'
  335. elif location > 50 and location < 100:
  336. print 'More than halfway there.'
  337. elif location < 50 and location > 0:
  338. print 'Less than halfway there.'
  339. elif location == 100:
  340. print "You are there!"
  341. elif location < 0:
  342. print "You're moving in the wrong direction!"
  343. elif location > 100:
  344. print "You've gone too far."
  345. elif location == 0:
  346. print "You aren't moving!"
  347.  
  348. #####
  349.  
  350. ### WHILE LOOP
  351. age = 0
  352. old_age = 30
  353.  
  354. while age < old_age:
  355. print 'Still young @ ' + str(age)
  356. age = age + 1
  357. if age == old_age:
  358. print "You've reached the pinnacle @ " + str(age)
  359.  
  360. #####
  361.  
  362. ### FUNCTIONS
  363. # A function is a group of statements
  364.  
  365. IamCool = True
  366. ### BUILT-IN FUNCTIONS
  367. # print() - Prints values to the screen
  368. print(name)
  369. print(favorite_number)
  370.  
  371. # Two ways to print
  372. print height
  373. print IamCool,",I am cool"
  374.  
  375. print array_of_colors
  376. print array_of_numbers
  377.  
  378.  
  379. # raw_input() - Gets input from the user
  380. occupation = raw_input('What is your occupation? ')
  381. print 'You are a ' + occupation
  382.  
  383. # len() - Gets the length of a string
  384. print(len(name))
  385.  
  386. # type() - Gets the type of a value
  387. print(type(height))
  388.  
  389. # str() - Converts a value to a string
  390. print(type(str(height)))
  391.  
  392. # int() - Converts a value to an integer
  393. print(type(int(height)))
  394.  
  395. # list() - Converts a value to a list
  396.  
  397. # float() - Converts a value to a float
  398.  
  399. # round() - Rounds a number to a given percision
  400. print(round(height,2))
  401. print(round(height,1))
  402.  
  403.  
  404. # pow() - Raises a number or integer to a power
  405. power = pow(height,favorite_number)
  406. print(power)
  407.  
  408. # sum()- sum of all elements in an iterable
  409. print 'sum of array is',sum(array_of_numbers)
  410.  
  411. # help() - prints Python help information
  412. #help() commented out for now
  413.  
  414.  
  415. # Create a function
  416. def MyFunction():
  417. print name
  418. print height
  419. print favorite_number
  420.  
  421. # Use/Call a function
  422. MyFunction()
  423.  
  424. ## Function arguments
  425. # One argument
  426. def Write(first_name):
  427. print first_name
  428.  
  429. Write('Ole')
  430.  
  431. # More than one argument (separated by commas)
  432. def Add(a,b):
  433. print 'The sum is ' + str(a + b)
  434.  
  435. Add(2,3)
  436. Add(2.89,34.2)
  437.  
  438. # Function return
  439. def Multiply(a,b):
  440. product = a*b
  441. return product
  442.  
  443. print 'The product is',Multiply(2,89)
  444.  
  445. #####
  446.  
  447. ### FOR LOOP
  448.  
  449. print range(0,10)
  450.  
  451. # Loop over a range
  452. for i in range(0,10):
  453. print i
  454. # For each element inside of the range, print the element.
  455.  
  456. # Loop over a string
  457. name = 'Joseph'
  458. for letter in name:
  459. print letter
  460.  
  461. # Loop over a list
  462. my_list = ['eggs','milk','bread']
  463. for item in my_list:
  464. print item
  465.  
  466. #####
  467.  
  468. # WHILE LOOP
  469. i = 1
  470. while i<11:
  471. print "uh",i, "and"
  472. i = i + 1 #increment i
  473.  
  474. ### CLASSES
  475.  
  476. # A class
  477. class Fruit():
  478. def __init__(self,color,taste,type='Fruit'):
  479.  
  480. # Member Variables
  481. self.color = color
  482. self.taste = taste
  483. self.type = type
  484.  
  485. # A Method
  486. def eat(self, item):
  487. print "Eating " + item
  488.  
  489. # An object
  490. apple = Fruit("red","sweet")
  491.  
  492. # Accessing member variables
  493. print(apple.color)
  494. print(apple.taste)
  495. print(apple.type) # default value. a non-required argument.
  496.  
  497. # Using methods
  498. apple.eat("vegetables####
  499.  
  500. # Try to do something, and if there is an error, do something else
  501. try:
  502. print "Hello World"
  503. except:
  504. print('Goodbye World')
  505.  
  506. # Types of exceptions
  507. exceptions= """except IOError:
  508. print('An error occured trying to read the file.')
  509.  
  510. except ValueError:
  511. print('Non-numeric data found in the file.')
  512.  
  513. except ImportError:
  514. print "NO module found"
  515.  
  516. except EOFError:
  517. print('Why did you do an EOF on me?')
  518.  
  519. except KeyboardInterrupt:
  520. print('You cancelled the operation.')
  521.  
  522. except:
  523. print('An error occured.')
  524. """
  525.  
  526. #####
  527.  
  528. ### PART 2 ###
  529.  
  530. # -*- coding: utf-8 -*-
  531. # BOOLEANS
  532.  
  533. cold = False
  534. hot = False
  535. normal = False
  536.  
  537. cloudy = False
  538. partly_cloudy = False
  539. sunny = False
  540.  
  541.  
  542. temp = 12
  543. overcast = 68
  544.  
  545.  
  546. if temp < 65:
  547. cold = True
  548.  
  549.  
  550. if temp > 85:
  551. hot = True
  552.  
  553.  
  554. if temp > 65 and temp < 85:
  555. normal = True
  556.  
  557.  
  558. if overcast > 55:
  559. cloudy = True
  560.  
  561.  
  562. if overcast < 30:
  563. sunny = True
  564.  
  565.  
  566. if overcast > 30 and overcast < 55:
  567. partly_cloudy = True
  568.  
  569.  
  570. if (cold and cloudy) and (cold and partly_cloudy):
  571. print 'Its gonna be a yucky day'
  572. else:
  573. print 'Its an okay day out!'
  574.  
  575.  
  576. if (cold and cloudy) or (cold and partly_cloudy):
  577. print 'Its gonna be a yucky day'
  578. else:
  579. print 'Its an okay day out!'
  580.  
  581.  
  582. if hot and sunny:
  583. print 'Its gonna be steaming!!'
  584.  
  585. class Animal():
  586. # two underscores mean the variable is private
  587. __name = ""
  588. __height = 0
  589. __weight = 0
  590. __sound = ''
  591. def __init__(self,name):
  592. self.__name = name
  593.  
  594. def get_name(self):
  595. print self.__name
  596.  
  597. a = Animal('a')
  598.  
  599. a.get_name()
  600.  
  601. # CONDITIONALS
  602.  
  603. adult = False
  604. miniumum_age = 18
  605.  
  606. def CheckAge():
  607. age = int(raw_input('How old are you: '))
  608. if age >= miniumum_age:
  609. adult = True
  610. print 'You are legal'
  611. elif age < miniumum_age:
  612. print 'That is not old enough'
  613. adult = False
  614.  
  615. if not adult:
  616. CheckAge()
  617. CheckAge()
  618.  
  619. # FUNCTIONS (INTERMEDIATE)
  620. welcome = 'Welcome to Editorial! '
  621. response = raw_input('How are you today? ')
  622. computer_response = 'It seems you are ' + response
  623.  
  624. # Create a function
  625. def PrintSomething():
  626. print 'Hi'
  627.  
  628. # Call the function
  629. PrintSomething()
  630.  
  631. # Function arguments/parameters
  632. def PrintArgument(argument):
  633. print argument
  634.  
  635. PrintArgument(welcome)
  636. PrintArgument(computer_response)
  637.  
  638. def push_argument(*argparams):
  639. print argparams
  640. push_argument('a','b')
  641.  
  642.  
  643. def push_keys(**keyparams):
  644. print keyparams
  645. push_keys(ok='right')
  646.  
  647.  
  648. def default_parameters(a='A',b='B'):
  649. print a,b
  650. default_parameters(a='Not A',b='Not B')
  651.  
  652.  
  653. def fixed_passed_parameters(a,b):
  654. print a,b
  655. fixed_passed_parameters('a','b')
  656.  
  657.  
  658. #String Funtions
  659. import string
  660.  
  661. name = 'john jacob jingleheimer schmidt'
  662.  
  663. place = 'Wasington D.C.'
  664. print place
  665.  
  666. place = place.lower()
  667. print place
  668.  
  669. place = place.upper()
  670. print place
  671.  
  672. ## FOMATTING
  673. formatted_string ='My name is %s' % ('Mr Editorial')
  674. print formatted_string
  675.  
  676. multiVariable_formatted_string = "He crossed the %(blank)s at %(time)d o'clock" % {'blank':'street','time':12}
  677. print multiVariable_formatted_string
  678.  
  679.  
  680. ## CLASSES
  681. place = string.capitalize(place)
  682. print place
  683.  
  684. split_name = string.split(name,None,-1)
  685. print split_name
  686.  
  687. joined_split_name = string.join(split_name)
  688. print joined_split_name
  689.  
  690. print string.capwords(joined_split_name,None)
  691.  
  692. # -*- coding: utf-8 -*-
  693.  
  694. # BETTER WAY
  695.  
  696. temperature = -10
  697.  
  698. initial_position = 0
  699. final_destination = 100
  700. halfway_point = (final_destination-initial_position)/2
  701. location = ''
  702.  
  703. while temperature < final_destination:
  704. diff = final_destination-temperature
  705. temperature = temperature + 1
  706. if temperature == halfway_point:
  707. location= 'Halfway there.'
  708. print str(temperature) + ' is ' + location + str(diff) + ' More to go!'
  709. elif temperature > halfway_point and temperature < final_destination:
  710. location= 'More than halfway there.'
  711. print str(temperature) + ' is ' + location + str(diff) + ' More to go!'
  712. elif temperature < halfway_point and temperature > initial_position:
  713. location= 'Less than halfway there.'
  714. print str(temperature) + ' is ' + location + str(diff) + ' More to go!'
  715. elif temperature == final_destination:
  716. location= "There!"
  717. print str(temperature) + ' is ' + location + ' No more to go!'
  718. elif temperature < initial_position:
  719. location= "Negative!"
  720. print str(temperature) + ' is ' + location + str(diff) + ' More to go!'
  721. elif temperature > final_destination:
  722. location= "Too far."
  723. print str(temperature) + ' is ' + location + str(diff) + ' More to go!'
  724. if temperature >= (temperature-1):
  725. print 'going in the right direction'
  726. else:
  727. print 'Wrong way Josè!'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement