FUNCTIONS AND CHARACTERS USED IN PYTHON PROGRAMMING, Study notes of Programming Languages

6.0 FUNCTIONS AND CHARACTERS USED IN PYTHON PROGRAMMING LANGUAGE

Typology: Study notes

2024/2025

Available from 03/19/2025

MENJA.ONLINE
MENJA.ONLINE 🇰🇪

7 documents

1 / 12

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
FUNCTIONS/ CHARACTERS USED IN PYTHON
PROGRAMMING
1. %d
Converts a signed integer decimal
2. %s
Converts String (converts any Python object using str())
3. %r
String (converts any Python object using repr())
4. \n
moves whatever's after it to a new ling
5. """
to display things as they're written in the .txt file
6. {}.format(something)
Is the new string.format in Python 3. This is how indexing works: "My first
name is {0} and my last name is {1}. You can call me
{0}".format("John","Doe").
7. list_name.append("")
appends thing to lists
8. for loops
"for x in list_name" ... applies something to every item in a list
9. my_list.sort()
sorts a list from lowest to highest, or alphabetical
10. len(my_list)
finds the length of a list
11. len[2] = 3
The 2nd term of the list is now equal to 3
12. my_list.insert(4, "cat")
Inserts the string "cat" at the 4th position in a list
13. my_list[:]
gives you the entire list
14. my_list[0:]
gives you the whole list, starting at the 0 position
15. my_list[1:3]
gives you the list starting at the 1st position and ending at the 2nd position
16. my_list[-1]
gives you the last term in the list
17. %r is used for...
debugging and display
18. %s is used for
display
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download FUNCTIONS AND CHARACTERS USED IN PYTHON PROGRAMMING and more Study notes Programming Languages in PDF only on Docsity!

FUNCTIONS/ CHARACTERS USED IN PYTHON

PROGRAMMING

1. %d Converts a signed integer decimal 2. %s Converts String (converts any Python object using str()) 3. %r String (converts any Python object using repr()) 4. \n moves whatever's after it to a new ling 5. """ to display things as they're written in the .txt file 6. {}.format(something) Is the new string.format in Python 3. This is how indexing works: "My first name is {0} and my last name is {1}. You can call me {0}".format("John","Doe"). 7. list_name.append("") appends thing to lists 8. for loops "for x in list_name" ... applies something to every item in a list 9. my_list.sort() sorts a list from lowest to highest, or alphabetical 10.len(my_list) finds the length of a list 11.len[2] = 3 The 2nd term of the list is now equal to 3 12.my_list.insert(4, "cat") Inserts the string "cat" at the 4th position in a list 13.my_list[:] gives you the entire list 14.my_list[0:] gives you the whole list, starting at the 0 position 15.my_list[1:3] gives you the list starting at the 1st position and ending at the 2nd position 16.my_list[-1] gives you the last term in the list 17.%r is used for... debugging and display 18.%s is used for display

19.optparse first command import optparse parser = optparse.OptionParser 20.adding parser options parser.add_option('-n, '--new') 21.after we've added options (in parser) (options, args) = parser.parse_args() 22.github steps

  1. git status
  2. git add (adds to staging)
  3. git commit - m "What you've done"
  4. git push - u origin master 23.raw_input() Raw input prompts the user for an input and then turns that input into a string. In between "(" and ")" the programmer writes the prompt that will prompt the user. When you set raw_input() equal to a variable, that variable becomes what the user inputs. 24.What is sys.argv? It allows you to input parameters from the command line. 25.Control flow statements if, for, while 26.and means that both conditions must be true 27.or means one of the conditions must be true 28.not gives the opposite of the statement; i.e. "Not True is False" 29.Order of Precedence (), (,/,%), (+,-) ^* matches the beginning of a string 30.$ matches the end of a string 31.\b matches a word boundar 32.\d matches any numeric digit 33.\D matches any non-numeric character

51.argv

  • argument variable
  • variable holds arguments passed to script when running it script, first, second, third = argv (line 3)
  • script = name of python script
  • first, second, third = 3 variables arguments assigned to 52.open()
  • function opens a file
  • Required argument is filename
  • Default access_mode is read(r)
  • Does not return actual content; creates/reads fileObject

53.input() Assumes input is valid python expression, returns evaluated result 54.read()

  • method reads a string from an open file
  • fileObject.read([count])
  • Count = # of bytes to read, reads as much as possible if not given 55.close()
  • method flushes unwritten information and closes file object
  • Not necessary, but important best practice 56.readline() Reads one line of text file 57.truncate() Empties the file 58.write(stuff) Writes stuff to file 59.len(input) Return the number of items from a sequence or characters in a string 60.exists() Returns TRUE if file in argument exists, FALSE if not function
  1. Names code like variables name strings/numbers
  2. Takes arguments the way scripts take argv
  3. Using 1 and 2, allows for mini-commands 61.def Defines a function def function1(): print "this is function 1" int()

Convert a string to an integer int(raw_input(> )) x += y ADD AND x = x + y


exponent 5 % 3 Modulo; remainder of the division 5 % 3 = 2 (3 goes into 5 once, remainder 2) 62.split() Method splits a string into separate phrases

  • Default is to split on whitespace split(str, num) str = separator (optional) numb = number of separations (optional) 63.sorted() Sorts a list from smallest to highest or a string alphabetically sorted(str, reverse=True) <- Sorts backwards 64.pop() method removes and returns the last object from a list != not equal 65.floating point numbers
  • Scientific notation in computers
  • Allows very large and small numbers using exponents
  • Made up of: Significand : 5, 1.5, - 2. Exponent : 2, - 2
  • Put decimal after integers to make floating point 1 ~ 1. 66.close()
  • method flushes unwritten information and closes file object
  • Not necessary, but important best practice 67.append() Adds input to the end of a list

84.elif stands for else if. if the first test evaluates to False, continues with the next one 85.else optional. Used after elif to catch other cases not provided for. 86.is tests for object identity 87.not negates a boolean value 88.as if we want to give a module a different alias 89.from for importing a specific variable, class or a function from a module 90.def used to create a new user defined function 91.return exits the function and returns a value 92.lambda creates a new anonymous function 93.global access variables defined outside functions 94.try specifies exception handlers 95.except catches the exception and executes codes 96.finally is always executed in the end. Used to clean up resources. 97.raise create a user defined exception 98.del deletes objects 99.pass does nothing

100. assert used for debugging purposes 101. class - way of producing objects with similar attributes and methods. - used to create new user defined objects - an object is an instance of a class 102. exec executes Python code dynamically

103. yield is used with generators 104. \ backslash () 105. ' Single Quote (') 106. " Double-quote (") 107. \a ASCII Bell - may cause receiving device to emit a bell or warning of some kind 108. \b ASCII Backspace (BS) - Erases last character printed 109. \f ASCII FormFeed (FF) - ASCII Control character. Forces printer to eject current page and continue printing at top of another. 110. \n ASCII LineFeed (LF) - Goes to next line - newline escape 111. \r ASCII Carriage Return (CR) - Resets position to beginning of a line of text 112. \t ASCII Horizontal Tab (TAB) - 8 horizontal spaces; tab 113. \v ASCII Vertical Tab (VT) - 6 vertical lines; 1 inch 114. %d signed integer decimal 115. %i signed integer decimal 116. %o unsigned octal 117. %u unsigned decimal 118. %x Unsigned hexadecimal (lowercase)

Exponent AND. Performs exponential calculation on operators and assigns value to left operand. A* =B ~ A = A *B

135. items() Returns a list of a dict's tuple pairs (key, value) 136. get() Returns a value for the given key. If key is not available, returns default of 'none'. 137. function argument passed in for function parameter function(argument) 138. function parameter Variable name for passed in argment def function(parameter): 139. universal import Imports all functions and variables from a module - Can cause conflicts with user defined functions and vars - Better to import only necessary functions from module import * 140. sort() sorts a list from smallest to greatest "mutable" can be changed after created del keyword deletes key/value pairs from dict 141. .remove() removes items from list 142. range() Returns a list of numbers from start up to (but not including) stop start defaults to 0 and step defaults to 1 range(stop) range(start, stop) range(start, stop, step) Syntax to index 2 nested lists? list[x][y] 143. enumerate() gives an index number to each element in a list

144. zip() Combines two or 3 lists to return all values in for loops tuple An immutable sequence of Python objects - Immutable; can't be changed - Similar to list, but can't be modified - Uses (), ends in ; tuple1 = ('word', 1, False); 145. items() Returns an array of dict key/value pairs 146. keys() Returns an array of dict's keys 147. values() Returns an array of dict's values 148. list comprehension Python rules for creating lists intelligently s = [x for x in range(1:51) if x%2 == 0] [2, 4, 6, 8, 10, 12, 14, 16, etc] 149. list slicing Way to access elements list[start:end:stride] - stride = count by __'s - any term can be omitted, will be set to default - a negative stride progresses through list backwards 150. filter() - filters a list for terms that make the function true filter(function, list) filter(lambda x: x%3 ==0, my_list) - for anonymous (throwaway) functions 151. % Modulus is NOT used as a "percentage" sign in the programming language 152. %d, %i Signed integer decimal 153. %o Signed octal value 154. %x Signed hexidecimal