- CPU is always wondering "what to do next", runs program
- Input devices: keyboard, mouse, touch screen
- output devices: screen, speakers, dvd burner
- main memory:fast geçici, reboot da gider RAM
- secondary memory: yavaş büyük, silinene kadar, disk drive, memory stick
- Yazılan kodlar main memorye eklenir, CPU çalıştıracağı zaman oradan çeker
- Linux'da python kodu çalıştırmak için:
- python hello.py
- Değişken:Represent a named location in computer memory the programmer uses to store various values to keep track of for use later. Variables can then be retrieved and acted on at any time using the assigned variable "name."
- value has a memory address,
- a variable contains memory address,
- a variable refers to a value and points a value
- değişkenleri adlandırırken harf ya da _ kullan, sayı kullanma
- Case sensitive
- İşlem sırası:
- Parenthesis
- Exponents / Roots
- Multiplication / Division
- Addition / Subtraction
- Left to right
- // işareti sayıları integer olarak böler
- bir int ve float olan işlem yaptığında sonuç float olur.
- bir sayı ile stringi toplayamazsın
- raw_input kullanıcının klavyeden girdiği değeri bir değişkene atar, string değeridir. int ya da float olarak kullanmak istiyorsun çevirmen lazım
- python da comment # ile yazılır
- print 'Hi2*5 kodu aşağıdaki çıktıyı verir.
- HiHiHiHİHİ
- bir fonksiyonda ilk önce parantez içindeki argument lar değerlendirilir soldan sağa sonra fonk çağırılır.
- def: a keyword indicating a function definition
- rules for executing an assignment statement:
- = işaretinin sağındaki ifadeyi bir değer üretmek için değerlendir
- = işaretinin solundaki değerin memory adresini tut
- rules for executing a function call:
- memory adresi üretmek için argument ları değerlendir
- bu memory adresleri ilgili parametrelerde tut
- funk nun body sini çalıştır
- When a
return
statement executes, the expression is evaluated to produce a memory address. -
What is passed back to the caller?
That memory address is passed back to the caller. -
What is displayed?
Nothing! - When a
print
function call is executed, the argument(s) are evaluated to produce memory address(es). -
What is passed back to the caller?
Nothing! -
What is displayed?
The values at those memory address(es) are displayed on the screen. Escape Sequence Name Example Output \n
newline (ASCII linefeed - LF) print('''How
are
you?''')How
are
you?\t
tab (ASCII horizontal tab - TAB) print('3\t4\t5')
3 4 5
\\
backslash ( \
)print('\\')
\
\'
single quote ( '
)print('don\'t')
don't
\"
double quote ( "
)print("He says, \"hi\".")
He says, "hi".
storm_greeting = 'Wow, you\'re dripping wet.'
storm_greeting = "Wow, you\'re dripping wet."
"Wow, you're dripping wet." bundaki \ işareti ' diğer tırnaktan ayırıyor
- Bir fonk tanımladığında aşağıdaki gibi tanımlamalısın.
def convert_to_celsius(fahrenheit): ''' (number) -> number Return the number of Celsius degrees equivalent to fahrenheit degrees. >>> convert_to_celsius(32) 0 >>> convert_to_celsius(212) 100 ''' return (fahrenheit - 32) * 5 / 9
- Daha sonra help(convert_to_ celcius) yazdığında yukarıdaki açıklamayı getirir.
- call stack: the stack of frames for functions currently being executed . foksiyondan çıkılırsa bu stack silinir.
- The order of precedence for logical operators is:
not
,and
, thenor
. Modules
Python contains many functions, but not all of them are immediately available as builtin functions. Instead of being available as builtins, some functions are saved in different modules. A module is a file containing function definitions and other statements.
We may also define our own modules with our own functions.
import
The general form of an import statement is:
import module_name
To access a function within a module, we use:
module_name.function_name
For example, we can import the Python modulemath
and call the functionsqrt
from it:
import math def area2(side1, side2, side3): semi = semiperimeter(side1, side2, side3) area = math.sqrt(semi * (semi - side1) * (semi - side2) * (semi - side3)) return area
In addition to importing Python's modules, we can also import the modules that we write. For example, to use the functions fromtriangle.py
(from the video) in another module, we wouldimport triangle
. A module being imported should be in the same directory as the module importing it.
- The
else
clause must be the last part of theif
statement.
The body of anif
statement must be indented. if expression1: body1 [elif expression2: 0 or more clauses body2] [else: 0 or 1 clause bodyN]
- The
def is_even(num): """ (int) -> bool Return whether num is even. """ if num % 2 == 0: return True else: return False
This works, but is stylistically questionable. It's also more typing and reading than is necessary!
num % 2 == 0
already producesTrue
orFalse
, so that expression can be used with thereturn
statement:
def is_even(num): """ (int) -> bool Return whether num is even. """ return num % 2 == 0
Capitalization matters, and capital letters are less than lowercase letters: >>> 'a' != 'A' True >>> 'a' < 'A' False Every letter can be compared: >>> ',' < '3' True
>>>'' in'abc'
True
>>> len('Bwa' + 'ha' * 10) 23
Description Operator Example Result of example equality ==
'cat' == 'cat'
True
inequality !=
'cat' != 'Cat'
True
less than <
'A' < 'a'
True
greater than >
'a' > 'A'
True
less than or equal <=
'a' <= 'a'
True
greater than or equal >=
'a' >= 'A'
True
contains in
'cad' in 'abracadabra'
True
length of str
slen(s)
len("abc")
3
- Fonksiyon Tarifi:
- Examples
- What should your function do?
- Type a couple of example calls.
- Pick a name (often a verb or verb phrase): What is a short answer to "What does your function do"?
-
Type Contract
- What are the parameter types?
- What type of value is returned?
-
Header
- Pick meaningful parameter names.
-
Description
- Mention every parameter in your description.
- Describe the return value.
-
Body
- Write the body of your function.
-
Test
- Run the examples.
>>> s[0:5] 'Learn' >>> s[6:8] 'to' >>> s[9:16] 'Program'
More generally, the end of the string can be represented using its length: >>> s[9:len(s)] 'Program' The end index may be omitted entirely and the default is
len(s)
: >>> s[9:] 'Program' Similarly, if the start index is omitted, the slice starts from index 0: >>> s[:] 'Learn to Program' >>> s[:8] 'Learn to' Negative indices can be used for slicing too. The following three expressions are equivalent: >>> s[1:8] 'earn to' >>> s[1:-8] 'earn to' >>> s[-15:-8] 'earn to''Learned to Program'
:s[:5] + 'ed' + s[5:]
>>> s = 'yesterday' >>> for char in s: ... print(char) ... y e s t e r d a y
def count_vowels(s): """ (str) -> int Return the number of vowels in s. Do not treat letter y as a vowel >>> count_vowels('Happy Anniversary!') 5 >>> count_vowels('xyz') 0 """ num_vowels = 0 for char in s: if char in 'aeiouAEIOU': num_vowels = num_vowels + 1 return num_vowels
********************************
def collect_vowels(s): """ (str) -> str Return the vowels from s. Do not treat the letter y as a vowel. >>> collect_vowels('Happy Anniversary!') 'aAiea' >>> collect_vowels('xyz') '' """ vowels = '' for char in s: if char in 'aeiouAEIOU': vowels = vowels + char return vowels
**********************************
In the example above, there are 6 iterations: the loop body executes 6 times.>>> num = 2 >>> while num < 100: num = num * 2 print(num) 4 8 16 32 64 128
************************************
>>> i = 0 >>> s = 'xyz' >>> while not (s[i] in 'aeiouAEIOU'): print(s[i]) i = i + 1 x y z Traceback (most recent call last): File "<pyshell#73>", line 1, in <module> while not (s[i] in 'aeiouAEIOU'): IndexError: string index out of range
In the code above, the error occurs whens
is indexed ati
andi
is outside of the range of valid indices. To prevent this error, add an additional condition is added to ensure thati
is within the range of valid indices fors
:
>>> i = 0 >>> s = 'xyz' >>> while i < len(s) and not (s[i] in 'aeiouAEIOU'): print(s[i]) i = i + 1 x y z
grades = [80, 90, 70]
>>> grades[0:2] [80, 90]
>>> 90 in grades True >>> 60 in grades False
Several of Python's built-in functions can be applied to lists, including:
-
len(list)
: return the length oflist
. -
min(list)
: return the smallest element inlist
. -
max(list)
: return the largest element inlist
. -
sum(list)
: return the sum of elements oflist
(where list items must be numeric).
>>> len(grades) 3 >>> min(grades) 70 >>> max(grades) 90 >>> sum(grades) 240
>>> for grade in grades: print(grade) 80 90 70
Method Description Example list.append(object)
Append object
to the end of list.>>> colours = ['yellow', 'blue'] >>> colours.append('red') >>> print(colours) ['yellow', 'blue', 'red']
list.extend(list)
Append the items in the list parameter to the list. >>> colours.extend(['pink', 'green']) >>> print(colours) ['yellow', 'blue', 'red', 'pink', 'green']
list.pop([index])
Remove the item at the end of the list; optional index to remove from anywhere. >>> colours.pop() 'green' >>> print(colours) ['yellow', 'blue', 'red', 'pink'] >>> colours.pop(2) 'red' >>> print(colours) ['yellow', 'blue', 'pink']
list.remove(object)
Remove the first occurrence of the object; error if not there. >>> colours.remove('green') Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> colours.remove('green') ValueError: list.remove(x): x not in list >>> colours.remove('pink') >>> print(colours) ['yellow', 'blue']
list.reverse()
Reverse the list. >>> grades = [95, 65, 75, 85] >>> grades.reverse() >>> print(grades) [85, 75, 65, 95]
list.sort()
Sort the list from smallest to largest. >>> grades.sort() >>> print(grades) [65, 75, 85, 95]
list.insert(int, object)
Insert object at the given index, moving items to make room. >>> grades.insert(2, 80) >>> print(grades) [65, 75, 80, 85, 95]
Method Description Example list.count(object)
Return the number of times object occurs in list. >>> letters = ['a', 'a', 'b', 'c'] >>> letters.count('a') 2
list.index(object)
Return the index of the first occurrence of object; error if not there. >>> letters.index('a') 0 >>> letters.index('d') Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> letters.index('d') ValueError: 'd' is not in list
-
>>> lst1 = [11, 12, 13, 14, 15, 16, 17] >>> lst2 = lst1 >>> lst1[-1] = 18 >>> lst2 [11, 12, 13, 14, 15, 16, 18]
After the second statement executes,lst1
andlst2
both refer to the same list. When two variables refer to the same objects, they are aliases. If that list is modified, both oflst1
andlst2
will see the change.
for i in range(10): print (i) The form ofrange
is:
range([start,] stop[, step]): return a virtual sequence of numbers from start to stop by steps = 'computer science' for i in range(len(s)): print(i)
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for i in range(1, len(s)): print(i)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
range
. The default stepping size is 1, which means that numbers increment by 1. The example below starts at index 1 and its step size is there (goes to every third index).
for i in range(1, len(s), 3): - print(i)
print 3.1415926535897932384626433832795028841971
# If both operands are ints, the answer is an int (rounded down)
print 1 / 3, 5 / 2, -7 / 3
>>> grades = [['Assignment 1', 80], ['Assignment 2', 90], ['Assignment 3', 70]] >>> grades[0] ['Assignment 1', 80] >>> grades[1] ['Assignment 2', 90] >>> grades[2] ['Assignment 3', 70]To access a nested item, first select the sublist, and then treat the result as a regular list.
For example, to access
'Assignment 1'
, we
can first get the sublist and then use it as we would a
regular list:
>>> sublist = grades[0] >>> sublist ['Assignment 1', 80] >>> sublist[0] 'Assignment 1' >>> sublist[1] 80Both
sublist
and grades[0]
contain the memory address of the ['Assignment
1', 80]
nested list.
We can access the items inside the nested lists like this:
>>> grades[0][0] 'Assignment 1' >>> grades[0][1] 80 >>> grades[1][0] 'Assignment 2' >>> grades[1][1] 90 >>> grades[2][0] 'Assignment 3' >>> grades[2][1] 70
Here is a nested loop involving 2
for
loops:
for i in range(10, 13):Here is the output:
for j in range(1, 5): print(i, j)
10 1 10 2 10 3 10 4 11 1 11 2 11 3 11 4 12 1 12 2 12 3 12 4 Notice that when
i
is 10, the inner loop
executes in its entirety, and only after j
has ranged from 1 through 4 is i
assigned
the value 11
.
Example of Nested Loops
def calculate_averages(grades): ''' (list of list of number) -> list of float Return a new list in which each item is the average of the grades in the inner list at the corresponding position of grades. >>> calculate_averages([[70, 75, 80], [70, 80, 90, 100], [80, 100]]) [75.0, 85.0, 90.0] ''' averages = [] # Calculate the average of each sublist and append it to averages. for grades_list in grades: # Calculate the average of grades_list. total = 0 for mark in grades_list: total = total + mark averages.append(total / len(grades_list)) return averages Incalculate_averages
, the outer
for
loop iterates through each sublist in
grades
. We then calculate the average of
that sublist using a nested, or
inner, loop, and add the average to the
accumulator (the new list, averages
).Writing To A File Within A Python Program
In order to write to a file, we usefile.write(str)
. This method
writes a string to a file. Method write
works like Python's print
function, except
that it does not add a newline character.
File dialogs
Moduletkinter
has a submodule called
filedialog
. We import it like this:
import tkinter.filedialogFunction
askopenfilename
asks the user to
select a file to open:
tkinter.filedialog.askopenfilename()This function returns the full path to the file, so we can use that when we call function
open
to
open that file.
from_filename = tkinter.filedialog.askopenfilename()Function
asksaveasfilename
asks the user
to select a file to save to, and provides a warning if
the file already exists.
to_filename = tkinter.filedialog.asksaveasfilename()
Example
Below is a program that copies a file, but puts"Copy"
as the first line of the copied
file.
In order to prompt a user for a file.
Now we can open the file we want to read from and get the contents:
from_file = open(from_filename, 'r') contents = from_file.read() from_file.close()And we can open the file we want to write to and write the contents:
to_file = open(to_filename, 'w') to_file.write('Copy\n') # We have to add the newline ourselves. to_file.write(contents) # Now write the contents of the file. to_file.close()
Yorumlar
Yorum Gönder