Ana içeriğe atla

Python

  • 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, then or.
  • 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

    In order to gain access to the functions in a module, we must import that module.
    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 module math and call the function sqrt 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 from triangle.py (from the video) in another module, we would import 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 the if statement.
      The body of an if statement must be indented.
    • if expression1:    
          body1
      [elif expression2:      0 or more clauses
          body2]
      [else:                  0 or 1 clause
          bodyN]
     
  • 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 produces True or False, so that expression can be used with the return 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 s len(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 
       
      **********************************
       
      >>> num = 2
      >>> while num < 100:
              num = num * 2
              print(num)
      
      
      4
      8
      16
      32
      64
      128
      
              
      In the example above, there are 6 iterations: the loop body executes 6 times.

      ************************************

      >>> 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 when s is indexed at i and i is outside of the range of valid indices. To prevent this error, add an additional condition is added to ensure that i is within the range of valid indices for s:
      >>> 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 of list.
    • min(list): return the smallest element in list.
    • max(list): return the largest element in list.
    • sum(list): return the sum of elements of list (where list items must be numeric).
For example, here are some calls to those built-in functions:
>>> 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 and lst2 both refer to the same list. When two variables refer to the same objects, they are aliases. If that list is modified, both of lst1 and lst2 will see the change.
       
       
       
      The example below will print the integers 0 to 9, inclusive.
      for i in range(10): print (i) The form of range is:
      range([start,] stop[, step]): return a virtual sequence of numbers from start to stop by step
       
      s = '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 
       
       
       
      You can even specify the "step" for 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) 
# approximation of pi, Python displays 12 decimal digits

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]
80
    
Both 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):
for j in range(1, 5): print(i, j)
Here is the output:
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 In calculate_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 use file.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

Module tkinter has a submodule called filedialog. We import it like this:
import tkinter.filedialog
Function 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

Bu blogdaki popüler yayınlar

Selenium WebDriver - Dinamik Web Tablolarla Kod Örnekleri

Verisi sürekli değişen tablolarda XPath kullanılması gerekir. Bunu da tablonun satır ve sütun sayı bilgileriyle yapmak daha doğru olur. Tablo 1: Şirket Grup Kapanış Şimdiki Ücret % Değişim IL&FS Transportation A 337.4 66.5 + 5.4 GRUH Finance Li A 383.8 998.9 + 2.3 IDFC Bank A 351.4 715.9 + 5.1 YES Bank Ltd. A 697.9 669.3 + 3.2 IRB Infrastructure A 271 724.8 + 3.1 Escorts Ltd. A 113.4 890.3 + 5.1 Cox & Kings L A 867 900.8 + 5.5 Bharat Electroni A 176.5 849 + 7.5 Nestle India A 64.8 187.3 + 7.6 Cox & Kings L A 749.4 729.5 + 9.5 JK Tyre & Industries A 687 601.4 + 6 Navin Fluorine Inter A 416.7 865.3 + 8.9 NIIT Technologies A 966.9 117.2 + 9.4 DCB Bank A 853.2 760.2 + 2.4 UCO Bank A 358 719.6 + 9 Coffee Day Enterpris A 53.8 538.6 + 4.1 Kirloskar Oil Engine A 134.1 102.8 + 7.7 Repco Home Finance L A 96.2 449.9 + 8.9 Ajanta Pharma Lt A 161.3 838 + 4.4 CESC Ltd. A 817 490.5 + 4.7 JaiprakashAssociates A 247.3 961.1 + 7.1 Vakrangee A 888.3 652.9 ...

TestNG - Notasyonlar (Annotations), Doğrulamalar (Assertions)

TestNG, JUnit ve NUnit kütüphanelerinden etkilenen ve onlara göre daha fazla yetkinlik barındıran bir test kütüphanesidir. TestNG ait özellikler ve kolaylıklar için şunları örnek verebiliriz: Notasyonlar (Annotations) Testlerin kendine has Thread’lerde koşabilmesi testng.xml dosyasıyla testlerin önceliklendirilmesi, gruplandırılması vb. kolaylıklar Kendi içerisinde loglama, raporlama desteği Notasyonlar sayesinde kodun ve oluşturulan raporun kolaylıkla anlaşılması @DataProvider notasyonu sayesinde veriye dayalı test desteği (Data Driven Test) Maven, Jenkins vb. ide ler için eklenti desteği Parametre desteği Notasyonlar: @Test Notasyonu Yazılan otomasyon kodunda test olarak çalışmasını istediğimiz kod parçasının önüne bu notasyonu ekleriz. Bu notasyonu birden fazla kez kullanabiliriz. Eğer herhangi bir parametre tanımlanmadıysa testler alfabetik olarak çalışır.  Aşağıdaki parametreler, hangi testin hangi sırayla çalışacağının, koşturulup koşturulmayacağın...

Selenium Actions Sınıfını Kullanarak Klavye ve Fare İşlemleri

Karmaşık kullanıcı hareketlerini (sağ tıklama, iki kere tıklama, sürükleme,...) taklit etmek için kullanılan API. Doğrudan Klavye veya Fare kullanmak yerine bu sınıf kullanılır. Build patternini uygular: yöntem çağrıları tarafından belirtilen tüm eylemleri içeren bir CompositeAction oluşturur. Kullanıcı hareketlerini uygulayan fonksiyonları kullanmak için Actions ve Action sınıfını import etmek gerekir: Actions sınıfı ve Action sınıfı, WebDriver API'sinin org.openqa.selenium.Interactions paketinde bulunur. import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.interactions.Action; Yöntemlerini kullanmaya çağırmak için Actions sınıfı nesnesine ihtiyaç vardır.  Actions actions = new Actions(WebDriver nesnesi); Üzerinde işlem yapılacak elementi bulmak gerekiyor. WebElement webElement = driver.findElement(...);  actions.contextClick(webElement).perform(); //contextClick, element üzerinde sağ tıklar. Bu sınıfının bazı fonksiyonl...