Bu notları Michigan Üniversitesinin Python Kursuna çalışırken almıştım. Belki faydalanan olur diye buraya bırakıyorum. Tüm notlar İngilizcedir.
I took these notes while I was studying to Michigan’s Python course.
print(“text”)
type() → We can ask Python what type something is by using the type() func.
If we want to read a number from the user we must convert it from a string to a number. We’ll use type() function for this.
int()
exit() → Works to end the interactive session
quit()→ Works to end the interactive session
input() → If we want to get a data from user we can use input() function
If we want to call the function of the command we use funcname()
Return Values : Often a function will take its arguments , do some computation , and return a value to be used as the value of the function call in the calling expression. The return keyword is used for this.
We simply add more arguments when we call the function.
We match the number and order of arguments and parameters.
Breaking out of a Loop : The break statement ends the current loop and jumps to the statement immediately the loop.
It is like a loop test that can happen anywhere in the body of the loop.
We make a variable that contains the largest value we have seen so far. If the current number we are looking at is larger , it is the new largest value we have seen so far.
Counting in a Loop : To count how many times we execute a loop , we introduce a counter variable that starts at 0 and we add one to it each time through the loop.
Summing in a Loop : To add up a value we encounter in a loop , we introduce a sum variable that starts at 0 and we add the value to the sum each time through the loop.
Finding the Average in a Loop : An average just combines the counting and sum patterns and divides when the loop is done.
Filtering in a Loop : We use an if statement in the loop to catch/filter the values we are looking for.
Search Using a Boolean Variable : If we just want to search and know if a value was found , we use a variable that starts at False and is set True as soon as we find what we are looking for.
“w” — write — yazma
“a” — append — dosyanın sonuna ekleme yapar
“r+” — read and write — okuma ve yazma
employee_file = open(“employees.txt”) → variable tanımlayıp open fonksiyonuna atayabiliyoruz.
employee_file.close() -> kullandıktan sonra dosyayı kapatmak için close komutunu kullanıyoruz.
print(employee_file.readable()) // print(employee_file.read()) -> bu komutları çalıştırdığımızda dosyada var olan tüm bilgiyi ekrana yazdırırız.
print(employee_file.readline()) → readline komutuyla dosyadaki istediğimiz bir satırı okuyabiliriz.
print(employee_file.readlines()) -> bu komutla birlikte tüm satırları liste şeklinde ekrana yazdırırız.
print(employee_file.readlines()[1]) → spesifik bir satırı okumak için bu komut tarzını kullanıyoruz.
employee_file = open(“employees.txt” , “a”)
employee_file.write(“ “)
Looping Through Strings : Using a while statement and an iteration variable , and the len function , we can construct a loop to look at each of the letters in a string individually.
String Concatenation : When the + operator is applied to strings , it means “concatenation”
Search and Replace : The replace() function is like a “search and replace” operation in a word processor.
Using in to select lines
Lists can be sliced using : Just like in strings , the second number is “ up to but not including”
Counting Pattern : The general pattern to count the words in a line of text is to split the line into words , then loop through the words and use a dictionary to track the count of each word independently.
Definite loops and dictionaries : Even though dictionaries are not stored in order , we can write a for loop that goes through all the entries in a dictionary — actually it goes through all of the keys in the dictionary and looks up the values
Tuples are like lists : Tuples are another kind of sequence that functions much like a list — they have elements which are indexed starting at 0
Tuples are Comparable : The comparison operators work with tuples and other sequences. If the first item is equal , Python goes on to the next element ,and so on, until it finds elements that differ.
Sort by values instead of key
I took these notes while I was studying to Michigan’s Python course.
print(“text”)
type() → We can ask Python what type something is by using the type() func.
If we want to read a number from the user we must convert it from a string to a number. We’ll use type() function for this.
float()example :
inp = input(‘Europe floor?’)
usf = int(inp) + 1
print(‘US floor’ , usf)
int()
exit() → Works to end the interactive session
quit()→ Works to end the interactive session
input() → If we want to get a data from user we can use input() function
example :
nam = input(‘Who are u’)
print(‘Welcome’ , nam)
Form of if/elif/else
Reserved words : We can’t use reserved words as variable names/identifiersif x<4 :
print(‘ ‘)
elif x<8 :
print(‘ ‘)
else :
print(‘ ‘)
- false
- true
- none
- and
- as
- assert
- break
- class
- if
- def
- del
- elif
- else
- except
- return
- for
- from
- global
- try
- import
- in
- is
- lambda
- while
- not
- or
- pass
- raise
- finally
- continue
- nonlocal
- with
- yield
def → If we want to create a function we use def command.example :
astr = ‘bob’
try :
print(‘Hello’)
istr = int(astr)
print(‘There’)
except :
istr = -1
print(‘Done’ , istr)
If we want to call the function of the command we use funcname()
Parameters : Parameters : a parameter is a variable which we use in the function definition. It is a “handle” that allows the code in the function to access the arguments for a particular function invocation.example :
def thing() :
print(‘Hello’)
thing()
greet(‘en’) or greet(‘es’) or greet(‘fr’) we can use all of them. End of the command if we start we will see the result.example :
def greet(lang)
if lang == ‘es’ :
print(‘Hola’)
elif lang == ‘fr’ :
print(‘Bonjour’)
else :
print(‘Hello’)
Return Values : Often a function will take its arguments , do some computation , and return a value to be used as the value of the function call in the calling expression. The return keyword is used for this.
Multiple Parameters / Arguments : We can define more than one parameter in the function definition.example :
def greet() :
return”Hello”
print(greet(),”Gleen”)
We simply add more arguments when we call the function.
We match the number and order of arguments and parameters.
Loops : Loops have iteration variables that change each time through a loop. Often these iteration variables go through a sequence of numbers.example :
def addtwo(a,b)
x=addtwo(3,5)
infinite loop is an endless loop.whine n>0 :
print …
Breaking out of a Loop : The break statement ends the current loop and jumps to the statement immediately the loop.
It is like a loop test that can happen anywhere in the body of the loop.
A simple definite loop :example :
while True:
line = input(‘>’)
if line == ‘done’ :
break
print(line)
print(‘Done’!)
Finishing an Iteration with Continue : The continue statement ends the current iteration and jumps to the top of the loop and starts the next iterationfor i in [5,4,3,2,1] :
print(i)
print(‘Blastoff’)
A definite loop with string : Definite loops have explicit iteration variables that change each time through a loop. These iteration variabbles move throught the sequence or set.example :
while True :
line = input(‘>’)
if line(=) == ‘#’ :
continue
if line == ‘done’ :
break
print(line)
print(‘Done!’)
Finding the Largest Value :example :
friends =[‘Joseph’,’Gleen’,’Sally’]
for friend in friends :
print(‘Happy New Year:’ , friend)
print(‘Done’)
We make a variable that contains the largest value we have seen so far. If the current number we are looking at is larger , it is the new largest value we have seen so far.
Looping Through a Setexample :
largest_so_far=-1
print(‘Before’,largest_so_far)
for the_num in [9,41,12,3,74,15] :
if the_num > largest_so_far :
print(largest_so_far,the_num)
print(‘After’,largest_so_far)
print(‘Before’)
for thing in [ 9 , 41 , 12 ,3 ,74 ,15] :
print(thing)
print(‘After’)
Counting in a Loop : To count how many times we execute a loop , we introduce a counter variable that starts at 0 and we add one to it each time through the loop.
example :
zork = 0
print(‘Before’ , zork)
for thing in [ 9, 41 ,12 ,3 ,74, 15] :
zork = zork + 1
print(zork , thing)
print(‘After’ , zork)
Summing in a Loop : To add up a value we encounter in a loop , we introduce a sum variable that starts at 0 and we add the value to the sum each time through the loop.
zork = 0
print(‘Before’, zork)
for thing in [9,41,12,3,74,15] :
zork = zork + thing
print(zork , thing)
print(‘After’ , zork)
Finding the Average in a Loop : An average just combines the counting and sum patterns and divides when the loop is done.
count = 0
sum = 0
print(‘Before’, count, sum)
for value in [9,41,12,3,74,15] :
count = count + 1
sum = sum + value
print(count , sum, value)
print(‘After’ , count , sum , sum/count)
Filtering in a Loop : We use an if statement in the loop to catch/filter the values we are looking for.
print(‘Befoe’)
for value in[9,41,12,3,74,15] :
if value > 20 :
print (‘ Large number ‘, value )
print(‘After’)
Search Using a Boolean Variable : If we just want to search and know if a value was found , we use a variable that starts at False and is set True as soon as we find what we are looking for.
found = False
print(‘Before’, found)
for value in[9,41,12,3,74,15] :
if value == 3 :
found = True
print(found , value)
print(‘After’ , found),
The “is” and “is not” operators
- Python has an is operator that can be used in logical expressions
- Implies “is the same as”
- Similar to , but stronger than ==
- is not also is a logical operator
smallest = None
print(‘Before’)
for value in[3,41,12,9,74,15] :
if smallest is None :
smallest = value
elif value < smallest :
smallest = value
print smallest , value
print(‘After’, smallest)
Creating dictionary :
form of the command -> dictionarysname = {}example :
monthconversions = { “Jan” : “ January” , “Feb” : “February”}
print(monthConversions[“Nov”])
print(monthConversions.get(“Dec”)
File Commands : open(“employees.txt”, “r”)
“r” — read — okuma“w” — write — yazma
“a” — append — dosyanın sonuna ekleme yapar
“r+” — read and write — okuma ve yazma
employee_file = open(“employees.txt”) → variable tanımlayıp open fonksiyonuna atayabiliyoruz.
employee_file.close() -> kullandıktan sonra dosyayı kapatmak için close komutunu kullanıyoruz.
print(employee_file.readable()) // print(employee_file.read()) -> bu komutları çalıştırdığımızda dosyada var olan tüm bilgiyi ekrana yazdırırız.
print(employee_file.readline()) → readline komutuyla dosyadaki istediğimiz bir satırı okuyabiliriz.
print(employee_file.readlines()) -> bu komutla birlikte tüm satırları liste şeklinde ekrana yazdırırız.
print(employee_file.readlines()[1]) → spesifik bir satırı okumak için bu komut tarzını kullanıyoruz.
employee_file = open(“employees.txt” , “a”)
employee_file.write(“ “)
String Data Type :
- A string is a sequence of characters
- A string lireal uses quotes ‘ blbla’ or “blabla”
- For string + means “concatenate”
- When a string contains numbers , it is still a string
- We can convert numbers in a string into a number using int() func
- We can get at any single character in a string using an index specified in square brackets
- The index value must be an integer and starts at zero
- The index value can be an expression that is computed
- The built-in function len gives us the length of string
Looping Through Strings : Using a while statement and an iteration variable , and the len function , we can construct a loop to look at each of the letters in a string individually.
fruit = ‘banana’
index = 0
while index < len(fruit) :
letter = fruit(index)
print(index , letter)
index = index +1
- A definite loop using a for statement is much more elegant
- The iteration variable is comletely taken care of by the for loop
Slicing Strings : We can also look a t any continuous section of a string using a colon operatorfruit = ‘banana’
for letter in fruit :
print(letter)
- The second number is one beyond the end of the slice “up to but not including”
- If the second number is beyond the end of the string , it stops at the end.
String Concatenation : When the + operator is applied to strings , it means “concatenation”
Using in as a Logical Operator
- The in keyword can also be used to check to see if one string is “in” another string
- The in expression is a logical expression that returns True or False and can be used in an if statement
String Library
- Python has a number of string functions which are in the string library
- These functions are already built into every string — we invoke them by appending the function to the string variable
- These functions do not modify the original string , instead they return a new string that has been altered
String Library
str.capitalize()
str.center(width[,fillchar])
str.endswitch(suffix[,start[,end]])
str.find(sub[,start[,end]])
str.lstrip([chars])
str.replace(old, new[,count])
str.lower()
str.rstrip([chars])
str.strip([chars])
str.upper()
Searching a String : We use the find() function to search for a substring within another string- find() finds the first occurrence of the substring
- If the substring is not found , find() return -1
- Remember that string position starts at zero
Search and Replace : The replace() function is like a “search and replace” operation in a word processor.
- It replaces all occurences of the search string with the replacement string
Parsing and Extracting
Stripping Whitespace
- Sometimes we want to take a string and remove whitespace at the beginning and/or end
- lstrip() and rstrip() remove whitespace at the left or right
- strip() removes both beginning and ending whitespace
Opening a File
- Before we can read the contents of the file , we must tell Python which file we are going to work with and what we will be doing with the file
- This is done with the open() function
- open() returns a “file handle” — a variable used to perform operations on the file.
- Similar to “File → Open” in a word processor
The newline Character
- We use a special character called the “newline” to indicate when a line ends
- We represent it as \n in strings
- Newline is still one character — not two
File Handle as a Sequence
- A file handle open for read can be treated as a sequence of string where each line in the file is a string in the sequence
- We can use the for statement to iterate through a sequence
- Remember -a sequence is an ordered set
Counting Lines in a File
- Open a file read-only
- Use a for loop to read each line
- Count the lines and print out the number of lines
Searching Through a File
We can put an if statement in our for loop to only print lines that meet some criteria.Searching Through a File(fixed)
- We can strip the whitespace from the right-hand side of the string using rstrip() from the string library.
- The newline is considered “white space” and is stripped
Skipping with Continue
- We can conveniently skip a line by using the continue statement
Using in to select lines
- We can look for a string anywhere in a line as our selection criteria
Lists are Mutable
- Strings are “immutable” — we cannot change the contents of a string — we must make a new string to make any change
- Lists are “mutable”- we can change an element of a list using the index operator
List Constants
- List constants are surrounded by square brackets and the elements in the list are separated by commas
- A list element can be any Python object — even another list
- A list can be empty
Concatenating Lists Using +
We can create a new list by adding two existing lists togetherUsing the range function
- The range function returns a list of numbers that range from zero to one less than the parameter
- We can construct an index loop using for and an integer iterator
Lists can be sliced using : Just like in strings , the second number is “ up to but not including”
Is something in a list ?
- Python provides two operators that let you check if an item is in a list
- These are logical operators that return True or False
- They do not modify the list
Building a list from scratch
- We can create an empty list and then add elements using the append method
- The list stays in order and new elements are added at the end of the list
Lists are in order
- A list can hold many items and keeps those items in the order until we do something to change the order
- A list can be sorted
- The sort method means “sort yourself”
Built-in Functions and Lists
- There are a number of functions built into Python that take lists as parameters
- Remember the loops we built ? These are much simpler.
Best Friends : Strings and lists
Split breaks a string into parts and produces a list of strings. We think of these as words. We can access a particular word or loop through all the words.- When you don’t specify a delimiter , multiple spaces are treated like one delimiter.
- You can specify what delimiter character to use in the splitting
What is not a “collection” ?
- Most of our variables have one value in them — when we put a new value in the variable — the old value is overwritten
Dictionaries
- Lists index their entries based on the position in the list.
- Dictionaries are like bags- no order
- So we index the things we put in the dictionary with a “lookup tag”
Dictionary Literals (Constants)
- Dictionary literals use curly braces and have a list of key : value pairs.
- You can make an empty dictionary using empty curly braces.
Many counters with a dictionary
- One common use of dictionaries is counting how often we “see” something.
Dictionary Tracebacks
- It is an error to reference a key which is not in the dictionary
- We can use the in operator to see if a key is in the dictionary
When we see a new name
When we encounter a new name , we need to add a new entry in the dictionary and if this the second or later time we have seen the name , we simply add one to the count in the dictionary under that name.The get method for dictionaries
- The pattern of checking to see if a key is already in a dictionary and assuming a default value if the key is not there is so common that there is a method called get() that does this for us
Simplified counting with get()
We can use get() and provide a default value of zero when thhe key is not yet in the dictionary — and then just add oneCounting Pattern : The general pattern to count the words in a line of text is to split the line into words , then loop through the words and use a dictionary to track the count of each word independently.
Definite loops and dictionaries : Even though dictionaries are not stored in order , we can write a for loop that goes through all the entries in a dictionary — actually it goes through all of the keys in the dictionary and looks up the values
Retrieving lists of Keys and values
- You can get a list of keys , values or items from a dictionary
Tuples are like lists : Tuples are another kind of sequence that functions much like a list — they have elements which are indexed starting at 0
but Tuples are immutable
- Unlike a list , once you crate a tuple , you cannot alter its contents — similar to string
Tuples are more efficient
- Since Python does not have to build tuple structures to be modifiable , they are simpler and more efficient in terms of memory use and performance than lists
- So in our program when we are making “temporary variables” we prefer tuples over lists.
Tuples and Assignment
- We can also put a tuple on the left-hand side of an assignment statement
- We can even omit the parentheses
Tuples and Dictionaries
- The items() method in dictionaries returns a list of tuples
Tuples are Comparable : The comparison operators work with tuples and other sequences. If the first item is equal , Python goes on to the next element ,and so on, until it finds elements that differ.
Sorting lists of tuples
- We can take advantage of the ability to sort a list of tuples to get a sorted version of a dictionary
- First we sort the dictionary by the key using the items() method and sorted() function
Using sorted()
We can do this even more directly using the built-in function sorted that takes a sequence as a parameter and returns a sorted sequence.Sort by values instead of key
- If we could construct a list of tuples of the form we could sort by value
- We do this with a for loop that creates a list of tuples