Vous êtes sur la page 1sur 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 file
print("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 assigns
the value 2 to variables "a" and "b".
print("a = " + str(a))
# We'll explain the expression str(a)
later in the course. For now it is used to convert the
variable "a" to a string.
print("b = " + str(b))
greetings = "greetings"
print("greetings = " + str(greetings))
greetings = another value
print("greetings = " + str(greetings))
Undefined variable
variable = 1
print(other variable)
variable type
variable = 1
print(other variable)

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 two


remainder = calculate the remainder
print("result = " + str(result))
print("remainder = " + str(remainder))
assignment
number = 9.0
print("number = " + str(number))
number -= 2
print("number = " + str(number))
number operator 5
print("number = " + str(number))
boolean_operator
two = 2
three = 3
is_equal = two operator three
print(is_equal)

comparaison_operator
one = 1
two = 2
three = 3
print(one < two < three) # This chained comparison means that
the (one < two) and (two < three) comparisons are performed at
the same time.
is_greater = three operator two
print(is_greater)
3. String
Concatenation
hello = "Hello"
world = 'World'
hello_world = type here
print(hello_world)
# Note: you should print "Hello World"
string_multiplication
hello = "hello"
ten_of_hellos = hello operator 10
print(ten_of_hellos)
string_indexing
python = "Python"
print("h " + python[3])
with 0

# Note: string indexing starts

p_letter = type here


print(p_letter)
negative_indexing
long_string = "This is a very long string!"
exclamation = type here
print(exclamation)

string slicing
monty_python = "Monty Python"
monty = monty_python[:5]
# one or both index could be
dropped. monty_python[:5] is equal to monty_python[0:5]
print(monty)
python = type here
print(python)
in_operator
ice_cream = "ice cream"
print("cream" in ice_cream)

# print boolean result directly

contains = type here


print(contains)
string length
len_function
phrase = """
It is a really long string
triple-quoted strings are used
to define multi-line strings
"""
first_half = type here
print(first_half)
character_escaping
dont_worry = "Don't worry about apostrophes"
print(dont_worry)
print("The name of this ice-cream is \"Sweeet\"")
print('text')
string_methods
monty_python = "Monty Python"
print(monty_python)
print(monty_python.lower())
the string
print(upper cased monty_python)

# print lower-cased version of

string_formating
name = "John"
print("Hello, PyCharm! My name is %s!" % name)
is inside the string, % is after the string

# Note: %s

print("I'm special symbol years old" % years)


4. Data structure
Lists introduction
squares = [1, 4, 9, 16, 25]
print(squares)

# create new list

print(slice)
lists operations
animals = ['elephant', 'lion', 'tiger', "giraffe"]
new list
print(animals)
animals += ["monkey", 'dog']
print(animals)
animals.append("dino")
append() method
print(animals)

# create

# add two items to the list

# add one more item to the list using

replace 'dino' with 'dinosaur'


print(animals)
list item
animals = ['elephant', 'lion', 'tiger', "giraffe", "monkey",
'dog']
# create new list
print(animals)
animals[1:3] = ['cat']
# replace 2 items -- 'lion' and
'tiger' with one item -- 'cat'
print(animals)
animals[1:3] = []
from the list
print(animals)

# remove 2 items -- 'cat' and 'giraffe'

clear list
print(animals)
Tuple
alphabet = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z')
print(alphabet length)
Dictionaries
# create new dictionary.
phone_book = {"John": 123, "Jane": 234, "Jerard": 345}
#
"John", "Jane" and "Jerard" are keys and numbers are values
print(phone_book)
# Add new item to the dictionary
phone_book["Jill"] = 345
print(phone_book)
# Remove key-value pair from phone_book
del phone_book['John']
print(Jane's phone)

Dictionary keys () and values()


phone_book = {"John": 123, "Jane": 234, "Jerard": 345}
create new dictionary
print(phone_book)

# Add new item to the dictionary


phone_book["Jill"] = 456
print(phone_book)
print(phone_book.keys())
print(phone_book values)
In keyword
grocery_list = ["fish", "tomato", 'apples']
list
print("tomato" in grocery_list)
contains "tomato" item

# create new

# check that grocery_list

grocery_dict = {"fish": 1, "tomato": 6, 'apples': 3}


create new dictionary

print(is 'fish' in grocery_dict keys)


5. Condition expressions
Boolean operators
name = "John"
age = 17
print(name == "John" or age == 17)
# checks that either
name equals to "John" OR age equals to 17
print(John is not 23 years old)
Boolean operators order
name = "John"
age = 17
print(name == "John" or not age > 17)
print("name" is "Ellis" or not ("name" equal "John" and he is
17 years old))
If statement
name = "John"
age = 17
if name == "John" or age == 17:
# check that name is "John"
or age is 17. If so print next 2 lines.
print("name is John")
print("John is 17 years old")
tasks = ['task1', 'task2']
check if 'tasks' is empty
print("empty")

# create new list

Else, elif part in if statement


x = 28
if x < 0:
print('x < 0')
0
elif x == 0:
print('x is zero')
x < 0, check if x == 0
elif x == 1:
print('x == 1')
x < 0 and x != 0, check if x == 1
else:
print('non of the above is true')

# executes only if x <


# if it's not true that
# if it's not true that

name = "John"
check if name equal to "John"
print(True)
otherwise
print(False)
6. Loops
For loop
for i in range(5):
# for each number i in range 0-4.
range(5) function returns list [0, 1, 2, 3, 4]
print(i)
# this line is executed 5 times. First
time i equals 0, then 1, ...
primes = [2, 3, 5, 7]

# create new list

iterate over primes using for loop


print(prime)
For loop using string
hello_world = "Hello, World!"
for ch in hello_world:
hello_world
print(ch)
length = 0

# print each character from

# initialize length variable

count how many characters are in the hello_world using loop


length += 1
# add 1 to the length on each iteration

print(len(hello_world) == length)
while loop
square = 1
while square <= 10:
print(square)
square += 1
print("Finished")

# This code is executed 10 times


# This code is executed 10 times
# This code is executed once

square = 0
number = 1
print all squares from 0 to 99
square = number ** 2
print(square)
number += 1
break keyword
count = 0
while True: # this condition cannot possibly be false
print(count)
count += 1
if count >= 5:
break
# exit loop if count >= 5
zoo = ["lion", 'tiger', 'elephant']
while True:
# this condition cannot
possibly be false
animal = zoo.pop()
# extract one element from the
list end
print(animal)
if exit loop if animal is 'elephant':
break
# exit loop

continue keyword
for i in range(5):
if i == 3:
continue
# skip the rest of the code inside loop for
current i value
print(i)
for x in range(10):
if Check if x is even:
continue
# skip print(x) for this loop
print(x)
7. Functions
Definition
def hello_world(): # function named my_function
print("Hello, World!")
for i in range(5):
hello_world()

# call function defined above 5 times

print('I want to be a function')


print('I want to be a function')
print('I want to be a function')
define a function named 'fun' to replace three lines above
print('I want to be a function')
for i in range(3):
fun()
parameter and call argument
def foo(x):
print("x = " + str(x))

# x is a function parameter

foo(5)
# pass 5 to foo(). Here 5 is an argument passed to
function foo.
define a function named 'square' that prints square of passed
parameter
print(x ** 2)
square(4)
square(8)

square(15)
square(23)
square(42)
return value
def sum_two_numbers(a, b):
return a + b
caller
c = sum_two_numbers(3, 12)
execution to variable 'c'

# return result to the function


# assign result of function

def fib(n):
"""This is documentation string for function. It'll be
available by fib.__doc__()
Return a list containing the Fibonacci series up to n."""
result = []
a = 0
b = initialize variable b
while a < n:
result.append(a)
tmp_var = b
update variable b
update variable a
return result
print(fib(10))
default parameter
def multiply_by(a, b=2):
return a * b
print(multiply_by(3, 47))
print(multiply_by(3))
# call function using default value
for b parameter
def hello(add parameters for function, set default value for
name):
print("Hello %s! My name is %s" % (subject, name))
hello("PyCharm", "Jane")
# call 'hello' function with
"PyCharm as a subject parameter and "Jane" as a name
hello("PyCharm")
# call 'hello' function with
"PyCharm as a subject parameter and default value for the name

8. Class and object


Definition
class MyClass:
variable = assign any value to variable
def foo(self):
# we'll explain self parameter later in
task 4
print("Hello from function foo")
my_object = MyClass() # variable "my_object" holds an object
of the class "MyClass" that contains the variable and the
"foo" function
Variable access
class MyClass:
variable1 = 1
variable2 = 2
def foo(self):
# we'll explain self parameter later in
task 4
print("Hello from function foo")
my_object = MyClass()
my_object1 = MyClass()
my_object.variable2 = 3
in my_object

# change value stored in variable2

print(my_object.variable2)
print(my_object1.variable2)
my_object.foo()

# call method foo() of object my_object

print(value of variable1 from my_object)

Variable access
class Car:
color = ""
def description(self):
description_string = "This is a %s car." % self.color
# we'll explain self parameter later in task 4
return description_string
car1 = Car()
car2 = create object of Car
car1.color = "blue"
set car2 color
print(car1.description())
print(car2.description())
self explanation
class Complex:
def create(self, real_part, imag_part):
self.r = real_part
self.i = imag_part
class Calculator:
current = 0
def add(self, amount):
add number to current
def get_current(self):
return self.current
special_init_method
class Square:
def __init__(self):
self.sides = 4

# special method __init__

square = Square()
print(square.sides)
class Car:
def __init__(add parameters here):
self.color = color
car = Car("blue")

# Note: you should not pass self

parameter explicitly, only color parameter


print(car.color)

9. Modules & packages


Import module
Calculator.py
"""
This module contains Calculator class
"""
class Calculator:
def __init__(self):
self.current = 0
def add(self, amount):
self.current += amount
def get_current(self):
return self.current
Import.py
import calculator
calc = calculator.Calculator()
# create new instance of
Calculator class defined in calculator module
calc.add(2)
print(calc.get_current())
here import my_module
call function hello_world from my_module
my_module.py
import calculator
calc = calculator.Calculator()

# create new instance of

Calculator class defined in calculator module


calc.add(2)
print(calc.get_current())
here import my_module
call function hello_world from my_module
builtin modules
import datetime
print(current date)
from import
calculator.py
"""
This module contains Calculator class
"""
class Calculator:
def __init__(self):
self.current = 0
def add(self, amount):
self.current += amount
def get_current(self):
return self.current
From_import.py
from calculator import Calculator
calc = Calculator()
# here we can use Calculator class
directly without prefix calculator.
calc.add(2)
print(calc.get_current())
import hello_world from my_module
print(hello_world())
without prefix

# Note: hello_world function used

my_module.py
""" documentation string for module my_module
This module contains hello_world function
"""
def hello_world():
return "Hello, World!"
10. File input/output
Input.txt
I am a temporary file. Maybe someday, I'll become a real file.
Input1.txt
My first line
My second line
My third line
Read_file.py
f = open("input.txt", "r")
# here we open file "input.txt".
Second argument used to identify that we want to read file
# Note: if you want to write to
the file use "w" as second argument
for line in f.readlines():
print each line

# read lines

f.close()
# It's important to close the file
to free up any system resources.
f1 = open("input1.txt", "r")
print only first line of f1
do not forget to close file
Write to file
This is output file.

Write_to_file.py
zoo = ['lion', "elephant", 'monkey']
if __name__ == "main":
f = open("output.txt", add modifier)
for i in zoo:
add the whole zoo to the output.txt
close the file

Vous aimerez peut-être aussi