python english
TRANSCRIPT
-
7/25/2019 Python English
1/17
Python
1. Introduction :
Our first program : helle word
print("Hello, world! My name is "type your name")
comments :
# This is the comment for the comments.py fileprint("Hello!") # this comment is for the second line
print("# this is not a comment")# add new comment here
2. Variables
Variable definition
a = b = 2 # This is called a "chained assignment". It assignsthe value 2 to variables "a" and "b".print("a = " + str(a)) # We'll explain the expression stra!
later in the course. or now it is used to convert thevariable "a" to a string.print("b = " + str(b))
greetings = "greetings"print("greetings = " + str(greetings))greetings = another valueprint("greetings = " + str(greetings))
Undefined variable
variable = 1
print(other variable)
variable type
variable = 1print(other variable)
-
7/25/2019 Python English
2/17
type conversion
type_cast
number = 9
print(type(number)) # print type of variable "number"
float_number = 9.0
print(float_number)print(Convert float_number to integer)
arithmetic_operator
number = 9.0 # float number
result = divide 'number' by to
remainder = !al!ulate the remainder
print("result = " + str(result))print("remainder = " + str(remainder))
assignment
number = 9.0print("number = " + str(number))
number "= 2print("number = " + str(number))
number operator #
print("number = " + str(number))
boolean_operator
to = 2three = $
is_e%ual = to operator three
print(is_e%ual)
-
7/25/2019 Python English
3/17
comparaison_operator
one = 1to = 2three = $
print(one & to & three) # This chained comparison means thatthe one two! and two three! comparisons are performed atthe same time.
is_greater = three operator to
print(is_greater)
3. tring
!oncatenation
hello = "Hello"orld = 'World'
hello_orld = type here
print(hello_orld) # $ote% you should print "&ello World"
string_multiplication
hello = "hello"ten_of_hellos = hello operator 10print(ten_of_hellos)
string_inde"ing
python = "Python"print("h " + python'$) # $ote% string indexing startswith
p_letter = type here
print(p_letter)
negative_inde"ing
long_string = "his is a ery long string!"e!lamation = type hereprint(e!lamation)
-
7/25/2019 Python English
4/17
string slicing
monty_python = "Monty Python"monty = monty_python'*# # one or both index could bedropped. monty(python)%*+ is e,ual to monty(python)%*+
print(monty)python = type hereprint(python)
in_operator
i!e_!ream = "ice cream"print("cream" in i!e_!ream) # print boolean result directly
!ontains = type here
print(!ontains)
string length
len_function
phrase = """t is a really long stringtriple$uoted strings are used
to de%ine multiline strings"""first_half = type hereprint(first_half)
character_escaping
dont_orry = "&on't worry about apostrophes"print(dont_orry)print("he name o% this icecream is "(weeet"")
print('tet')
string_methods
monty_python = "Monty Python"print(monty_python)
print(monty_python.loer()) # print lower-cased version ofthe string
print(upper !ased monty_python)
-
7/25/2019 Python English
5/17
string_formating
name = "*ohn"print("Hello, Py+harm! My name is s!" name) # $ote% sis inside the string/ is after the string
print("'m special symbol years old" years)
#. $ata structure
%ists introduction
s%uares = '1, -, 9, 1, 2# # create new listprint(s%uares)
print(sli!e)
lists operations
animals = ''elephant', 'lion', 'tiger', "gira%%e" # createnew listprint(animals)
animals += '"mon-ey", 'dog' # add two items to the listprint(animals)
animals.append("dino") # add one more item to the list usingappend! methodprint(animals)
repla!e 'dino'with 'dinosaur'print(animals)
list item
animals = ''elephant', 'lion', 'tiger', "gira%%e", "mon-ey",'dog' # create new listprint(animals)
animals'1*$ = ''cat' # replace 2 items -- 'lion' and'tiger' with one item -- 'cat'print(animals)
animals'1*$ = ' # remove 2 items -- 'cat' and 'giraffe'from the listprint(animals)
-
7/25/2019 Python English
6/17
!lear list
print(animals)
uple
alphabet = ('a', 'b', 'c', 'd', 'e', '%', 'g', 'h', 'i', '.','-', 'l', 'm', 'n', 'o', 'p', '$', 'r', 's', 't', 'u', '', 'w', '', 'y','/')
print(alphabet length)
&ictionaries
# create new dictionary.phone_boo/ = "*ohn"* 12$, "*ane"* 2$-, "*erard"* $-# #
"0ohn"/ "0ane" and "0erard" are 1eys and numbers are valuesprint(phone_boo/)
# dd new item to the dictionaryphone_boo/'"*ill" = $-#print(phone_boo/)
# 3emove 1ey-value pair from phone(boo1del phone_boo/''*ohn'
print(ane's phone)
$ictionary &eys '( and values'(
phone_boo/ = "*ohn"* 12$, "*ane"* 2$-, "*erard"* $-# #create new dictionaryprint(phone_boo/)
# dd new item to the dictionaryphone_boo/'"*ill" = -#
print(phone_boo/)
print(phone_boo/./eys())
print(phone_boo/ values)
In &ey)ord
gro!ery_list = '"%ish", "tomato", 'apples' # create newlist
print("tomato" in gro!ery_list) # chec1 that grocery(listcontains "tomato" item
-
7/25/2019 Python English
7/17
gro!ery_di!t = "%ish"* 1, "tomato"* , 'apples'* $ #create new dictionary
print(is '%ish' in gro!ery_di!t /eys)
*. !ondition e"pressions
+oolean operators
name = "*ohn"age = 13
print(name == "*ohn" or age == 13) # chec1s that eithername e,uals to "0ohn" 43 age e,uals to 56
print(ohn is not 2$ years old)
+oolean operators order
name = "*ohn"age = 13
print(name == "*ohn" or not age 4 13)
print("name" is "0llis" or not ("name" e%ual "*ohn" and he is13 years old))
If statement
name = "*ohn"age = 13
i% name == "*ohn" or age == 13* # chec1 that name is "0ohn"or age is 56. If so print next 2 lines.
print("name is *ohn") print("*ohn is 12 years old")
tas/s = ''tas-1', 'tas-3' # create new list
!he!/ i% 'tas-s' is empty print("empty")
-
7/25/2019 Python English
8/17
,lse- elif part in if statement
= 25
i% & 0*
print(' 4 5') # executes only if x eli% == 0* print(' is /ero') # if it's not true thatx / chec1 if x 77 eli% == 1* print(' == 1') # if it's not true thatx and x 87 / chec1 if x 77 5else* print('non o% the aboe is true')
name = "*ohn"
!he!/ i% name e%ual to "*ohn" print(6rue)otherise print(7alse)
. %oops
/or loop
%or i in range(#)* # for each number i in range -9.range*! function returns list )/ 5/ 2/ :/ 9+ print(i) # this line is executed * times. irsttime i e,uals / then 5/ ...
primes = '2, $, #, 3 # create new list
iterate over primes using %or loop print(prime)
/or loop using string
hello_orld = "Hello, World!"
%or !h in hello_orld* # print each character fromhello(world print(!h)
length = 0 # initiali;e length variable
!ount ho many !hara!ters are in the hello_orld using loop length += 1 # add 5 to the length on each iteration
-
7/25/2019 Python English
9/17
print(len(hello_orld) == length)
)hile loop
s%uare = 1
while s%uare &= 10* print(s%uare) # This code is executed 5 times s%uare += 1 # This code is executed 5 times
print("6inished") # This code is executed once
s%uare = 0number = 1
print all s%uares %rom 0 to 99 s%uare = number 88 2 print(s%uare) number += 1
brea& &ey)ord
!ount = 0
while 6rue* # this condition cannot possibly be false print(!ount) !ount += 1 i% !ount 4= #* brea- # exit loop if count
-
7/25/2019 Python English
10/17
continue &ey)ord
%or i in range(#)* i% i == $* continue # s1ip the rest of the code inside loop for
current i value print(i)
%or in range(10)* i% Che!/ i% is even* continue # s1ip printx! for this loop print()
0. /unctions
$efinition
de% hello_orld()* # function named my(function print("Hello, World!")
%or i in range(#)* hello_orld() # call function defined above * times
print(' want to be a %unction')print(' want to be a %unction')print(' want to be a %unction')
define a fun!tion named '%un' to repla!e three lines above print(' want to be a %unction')
%or i in range($)* fun()
parameter and call argument
de% foo()* # x is a function parameter print(" = " + str())
foo(#) # pass * to foo!. &ere * is an argument passed tofunction foo.
define a fun!tion named 's$uare' that prints s%uare of passedparameter print( 88 2)
s%uare(-)s%uare(5)
-
7/25/2019 Python English
11/17
s%uare(1#)s%uare(2$)s%uare(-2)
return value
de% sum_to_numbers(a, b)* return a + b # return result to the functioncaller
! = sum_to_numbers($, 12) # assign result of functionexecution to variable 'c'
de% fib(n)*
"""This is documentation string for function. It'll beavailable by fib.((doc((! 3eturn a list containing the ibonacci series up to n.""" result = ' a = 0 b = initialie variable b while a & n* result.append(a) tmp_var = b update variable b update variable a
return result
print(fib(10))
default parameter
de% multiply_by(a, b=2)* return a 8 b
print(multiply_by($, -3))print(multiply_by($)) # call function using default valuefor b parameter
de% hello(add parameters %or fun!tion, set default value %orname)* print("Hello s! My name is s" (sub:e!t, name))
hello("Py+harm", "*ane") # call 'hello' function with"=y>harm as a sub?ect parameter and "0ane" as a name
hello("Py+harm"
) # call 'hello' function with"=y>harm as a sub?ect parameter and default value for the name
-
7/25/2019 Python English
12/17
. !lass and obect
$efinition
class ;yClass*
variable = assign any value to variable
de% foo(self)* # we'll explain self parameter later intas1 9 print("Hello %rom %unction %oo")
my_ob:e!t = ;yClass() # variable "my(ob?ect" holds an ob?ectof the class "@y>lass" that contains the variable and the"foo" function
Variable access
class ;yClass* variable1 = 1 variable2 = 2
de% foo(self)* # we'll explain self parameter later intas1 9 print("Hello %rom %unction %oo")
my_ob:e!t = ;yClass()my_ob:e!t1 = ;yClass()
my_ob:e!t.variable2 = $ # change value stored in variable2in my(ob?ect
print(my_ob:e!t.variable2)print(my_ob:e!t1.variable2)
my_ob:e!t.foo() # call method foo! of ob?ect my(ob?ect
print(value of variable1 %rom my_ob:e!t)
-
7/25/2019 Python English
13/17
Variable access
class Car* !olor = "" de% des!ription(self)*
des!ription_string = "his is a s car7" self.!olor# we'll explain self parameter later in tas1 9 return des!ription_string
!ar1 = Car()!ar2 = !reate ob:e!t of Car
!ar1.!olor = "blue"set !ar2 !olor
print(!ar1.des!ription())
print(!ar2.des!ription())
self e"planation
class Comple* de% !reate(self, real_part, imag_part)* self.r = real_part self.i = imag_part
class Cal!ulator* !urrent = 0
de% add(self, amount)* add number to !urrent
de% get_!urrent(self)* return self.!urrent
special_init_method
class
-
7/25/2019 Python English
14/17
parameter explicitly/ only color parameter
print(!ar.!olor)
. 4odules 5 pac&ages
Import module
!alculator.py
"""This module contains >alculator class"""
class Cal!ulator* de% __init__(self)* self.!urrent = 0
de% add(self, amount)* self.!urrent += amount
de% get_!urrent(self)* return self.!urrent
Import.py
import !al!ulator
!al! = !al!ulator.Cal!ulator() # create new instance of>alculator class defined in calculator module!al!.add(2)
print(!al!.get_!urrent())
here import my_module
!all fun!tion hello_orld %rom my_module
my_module.py
import !al!ulator
!al! = !al!ulator.Cal!ulator() # create new instance of
-
7/25/2019 Python English
15/17
>alculator class defined in calculator module!al!.add(2)
print(!al!.get_!urrent())
here import my_module
!all fun!tion hello_orld %rom my_module
builtin modules
import datetime
print(!urrent date)
from import
calculator.py
"""This module contains >alculator class"""
class Cal!ulator* de% __init__(self)* self.!urrent = 0
de% add(self, amount)* self.!urrent += amount
de% get_!urrent(self)* return self.!urrent
/rom_import.py
%rom !al!ulator import Cal!ulator
!al! = Cal!ulator() # here we can use >alculator classdirectly without prefix calculator.!al!.add(2)
print(!al!.get_!urrent())
import hello_orld %rom my_module
print(hello_orld()) # $ote% hello(world function used
without prefix
-
7/25/2019 Python English
16/17
-
7/25/2019 Python English
17/17
9rite_to_file.py
oo = ''lion', "elephant", 'mon-ey'
i% __name__ == "main"*
f = open("output7tt", add modifier)
%or i in oo* add the hole oo to the output.tt
!lose the file