Learn Python basics with this tailored course material from Chad Haynes, enhanced by instructors at Kasetsart University. Dive into built-in objects, functions, classes, and more. Explore Python's simplicity, flexibility, and wealth of libraries.
01 / 123Introduction to Python: A Comprehensive Guide for Beginners
1 / 17
Télécharger la présentation
Introduction to Python: A Comprehensive Guide for Beginners
Une image / un lien ci-dessous est fourni (tel quel) pour télécharger la présentation
Politique de téléchargement : le contenu du site vous est fourni TEL QUEL pour votre information et votre usage personnel ; il ne peut être vendu, concédé sous licence ni partagé sur d’autres sites sans l’accord de son auteur.Le contenu vous est fourni TEL QUEL, pour votre information et votre usage personnel uniquement.Téléchargez la présentation en cliquant sur ce lien.Lors du téléchargement, si vous ne parvenez pas à télécharger une présentation, l’éditeur a peut-être supprimé le fichier de son serveur.Pendant le téléchargement, si vous ne parvenez pas à obtenir une présentation, le fichier a peut-être été supprimé par l’éditeur.
F I N
Plus de contenu associé
Transcription de la présentation
Introduction to Python Based on material for the course Programming with Python by Chad Haynes. Modified at Kasetsart University by Chaiporn Jaokaew and James Brucker.
Import a library module Function definition Class definition Comment Object instantiation Calling a function Python At First Glance import math def showArea(shape): print("Area = ", shape.area() ) def widthOfSquare(area): return math.sqrt(area) class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height ###### Main Program ###### r = Rectangle(10, 20) showArea(r)
Why use Python? • Simple syntax: easy to learn and remember • Portable • Flexible • Large standard library • Short development time • Lots of 3rd party tools/add-ons • Many good implementations: CPython, PyPy, IronPython, Jython • Active open-source community
Similarities to Java • Everything inherits from "object" • Has numbers, functions, classes, … • Everything is first-class • Large standard library • Garbage collection • Introspection, serialization, threads, net,…
// this is Java if (x < 10) { x = x + tmp; y = y * x; } System.out.println(y); Java # this is Python if x < 10: x = x + tmp y = y * x print( y ) Python Python vs. Java/C++/C • Typing: strong, but dynamic • Names have no type • Objects have type • No name declarations • Sparse syntax • No { } for blocks, just indentation • No ( ) for if/while conditions • Interactive interpreter • # for comments (like Perl)
GettingStarted • Download from: http://python.org/ Add python to PATH to run scripts from command line • Python is available for most platforms, even mobile. • Most Linux distributions have Python as package(s)
Python 3: print( "hello" ) There are some differences between Python 2.x and Python 3 syntax. • print is a function in Python 3, which uses parenthesis: Python 3.x: Python 2.x: print("hello") print "hello"
Hello, World! C# Python using System; class Hello { static void Main() { Console.WriteLine("Hello, World"); } } print("Hello, World")
Variables >>> x = 23 >>> print(x) 23 >>> x = 'foo' >>> print(x) foo >>> del x >>> print(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined >>> namex means 23 now it means 'foo' x is undefined
Variables Variable is a reference to an object • not a value • more than one variable can refer to the same object Var1 Var1_copy Var2
Strings A sequence of characters enclosed in quotes 3 ways to quote strings: 'Single Quotes' "Double Quotes" """Triple Quotes""" or '''triple quotes''' • Triple quotes can span multiple lines Examples >>> print('This string may contain a "') This string may contain a " >>> print("A ' is allowed") A ' is allowed >>> print("""Either " or ' are OK""") Either " or ' are OK
raw_input for reading input raw_input( [prompt] ) • Print prompt and return user's input as a string • a built-in function Example >>> reply = raw_input('Are you awake? ') Are you awake?not sure >>>print( reply ) not sure
i1 not i1 1 0 0 1 Boolean Operations • Operators: and or not • Standard Boolean Algebra i1 i2 i1and i2 i1or i2 1 1 1 1 1 0 0 1 0 1 0 1 0 0 0 0
Boolean values True: any non-zero, non-null value. False: None (null) empty string empty list 0 s = "hello" if s: print("true") lst = [] if lst: print("list is not empty")
Boolean Expressions >>> 1 == 1 and 2 >= 3 False >>> 1 == 1 or 2 >= 3 True >>> not 5.3 != 2.2 # same as: not (5.3 != 2.2) False >>> 2 and '23' > '11' or 0 True
String Formatting C-Style formatting (extended printf): "format string" % (arg1, arg2, ...) >>> "%i %s in the basket" % (2, "eggs") '2 eggs in the basket' >>> x = 2.0/9.0 >>> "%f to 2 dec places is %.2f" % (x, x) '0.222222 to 2 decimal places is 0.22' >>> length = 5 >>>obj = "fence" >>> "Length of %(obj)s is %(length)i" % vars() 'Length of the fence is 5'
String Format Codes Format codes begin with "%": import math x = 10 "x is %f" % x "pi is %.8f" % math.pi "pi is %12.6f" % math.pi eps = 1.0E-17 "eps is %f (%g)" % (eps, eps)
String Formatting using .format >>> "{0} {1} in the basket".format(2, "eggs") '2 eggs in the basket' >>> x = 2.0/9.0 >>> "{0} to 2 dec places is {0:.2f}".format(x) '0.222222 to 2 decimal places is 0.22' "{0} to {1} dec places is {0:.{1}f}".format(x,3) '0.222222 to 3 decimal places is 0.222' >>> name = "James Bond" >>> id = 7 >>> "{0:12s} is {1:03d}".format(name,id) 'James Bond is 007' Python format mini-language reference: http://docs.python.org/3.1/library/string.html#format-specification-mini-language
type determines type of Object Determine the type of an object Syntax: type(object) Examples >>> type(2.45) <type 'float'> >>> type('x') <type 'str'> >>> type(2**34) <type 'long'> >>> type(3+2j) <type 'complex'>
Adding Elements to a List • >>> list = [ "apple", "banana" ] • Append item to end • >>> list.append( "durian" ) • Append another list • >>> list.extend( list2 ) • Same aslist + list2 • Insert item anywhere • >>> list.insert( 0, "artichoke" ) • >>> list.insert( 2, "carrot" ) • Like Javalist.add( n, item)
Removing Elements from a List • >>> list = [ "a" "b", "c", "b" ] • Remove a matching element (w/o returning it) • >>> list.remove( "b" ) • Throws exception if argument is not in the list • Remove last element and return it • >>> list.pop( ) • 'b' • Remove by position • >>> list.pop( 1 ) # 'b' removed already • 'c'
Indexing • Syntax: list[n] • Positive indices count from the left: list[0] • Negative indices count from the right: list[-1] 0 1 2 3 4 5 6 a b c d e f g -7 -6 -5 -4 -3 -2 -1 list[0] == a sequence[-1] == g list[2] == c sequence[-2] == f list[6] == g sequence[-7] == a
List Slicing: get a sublist list[m:n]return elements m up to n (exclusive) syntax for both strings and lists >>> x = [0, 1, 2, 3, 4, 5, 6, 7] >>> x[1:4] [1, 2, 3] >>> x[2:-1] [2, 3, 4, 5, 6] # Missing Index means start or end of list >>> x[:2] [0, 1] >>> "Hello nerd"[3:] lo Nerd
Sorting a list • List.sort( [comparator] ) • Sort Listin place. Result is applied to the list! • Example: • >>> list3 = [4, 12, 3, 9] >>> list3.sort() >>> list3 [3, 4, 9, 12]
Count or find elements in a list list.count( element ) count number of occurences of element. n = list.index( element ) return index of first occurence of element. Throws ValueError if element is not in list.
Tuples • Immutable list • Syntax: (elem1, elem2, …) • A tuple cannot be changed. • Example: • >>> tuple1 = (1, 5, 10) >>> tuple1[2] = 2 Traceback (most recent call last): File "<pyshell#136>", line 1, in ? tuple1[2] = 2 TypeError: object doesn't support item assignment
len - Length of an object n = len(object) Return the length of object Examples >>> list1 = [1, 2, 3, 4, 5] >>> len(list1) 5 >>> string1 = "length of a string" >>> len(string1) 18 len is not object-oriented.
Multiple assignment using tuples (a,b,c) = (10, 20, 50) >>> b 20 This can be used in for loops. points = [ (1,0), (0.2,0.9), (1,2) ] for (x,y) in points: r = math.hypot(x,y) print("radius of (%f,%f) is %f" % (x,y,r) )
'z' 'ab' 2.1 3 Dictionary: mapping key to value • A mapping of keys to values • Associate a key with a value • Each key must be unique keys 10 [2] (3,8) 'hello' values
Set An unordered collection, without duplicates (like Java). Syntax is like dictionary, but no ":" between key-value. >>> aset = { 'a', 'b', 'c' } >>> aset {'a', 'c', 'b'} >>> aset.add('c") # no effect, 'c' already in set >>> aset {'a', 'c', 'b'}
Test for element in Set item in set >>> aset = { 'a', 'b', 'c' } >>> 'a' in aset True >>> 'A' in aset False
Flow Control ifcondition : body elifcondition : body else: body if x%2 == 0: y = y + x else: y = y - x whilecondition: body while count < 10: count = 2*count fornameiniterable: body for x in [1,2,3]: sum = sum + x
range: create a sequence • range([start,] stop[, step]) • Generate a list of numbers from start to stop stepping every step • start defaults to 0, step defaults to 1 • Example • >>> range(5) [0, 1, 2, 3, 4] >>> range(1, 9) [1, 2, 3, 4, 5, 6, 7, 8] >>> range(2, 20, 5) [2, 7, 12, 17]
for loop using range( ) Use range to generate values to use in for loop >>> for i in range(1,4): print i 1 2 3
Connexion au compte
Connectez-vous pour publier votre contenu sur SlideServe.