You are on page 1of 37

1- AN INTRODUCTION TO PYTHON

Parham Kazemi
University of Isfahan, Computer Eng. Faculty
ACM Student Chapter
pkazemi3@gmail.com
ABOUT PYTHON

• Interpreted: Python is processed at runtime by the interpreter. You do not


need to compile your program before executing it. This is similar to PERL and
PHP.
• Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
• Object-oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
• High-level dynamic data types, supports dynamic type checking
• Automatic Garbage Collection
• Created during 1985 – 1990
• Supports the development of a wide range of applications from simple text
processing to WWW browsers to games.
2
PYTHON USES AND APPLIC ATIONS

• Famous Applications that use Python: • Web Applications made with Django:
• YouTube • Pinterest
• Dropbox • NASA
• Google • Prezi
• Quora • Pitchfork
• BitTorrent • Disqus
• Spotify • Bitbucket
• Reddit • Instagram
• Yahoo Maps
• Hipmunk

3
STARTING PYTHON

• Download and install: https://www.python.org/


• Latest stable release as of Feb. 2018: Python 3.6.4

• Run the interpreter: open cmd/terminal,‘python’ (or ‘python3’)


• python –c cmd
• Example: python –c “a=2; b=2; print(a+b);”
• python file.py

• Try a simple hello world:


• >>> print(“Hello World!”)

4
PYTHON SYNTAX

• LINE STRUCTURE
• A Python program is divided into a number of logical lines and every logical line is
terminated by the token NEWLINE. A logical line is created from one or more
physical lines.
• A line containing just spaces, tabs, or a comment, is known as a blank line, and
Python’s interpreter ignores it.
• A physical line is a sequence of characters terminated by an end-of-line sequence.
• COMMENTS
• A comment begins with a hash character (#) which is not a part of the string literal and ends at
the end of the physical line.
• It should be noted that Python has no multi-line or block comments.
• >>> # this is a comment
• >>> “# this isn’t a comment”
5
PYTHON SYNTAX

• JOINING LINES
• When you want to write a long code in a single line you can break the logical line in
two or more physical lines using the backslash character (\).
>>> a = 2 + 3 \
... * 4
>>> a
14
• MULTIPLE STATEMENTS ON A SINGLE LINE
• You can write two or more separate statements into a single line using a semicolon
(;) character between two lines.
>>> a = 2; b = 3; print(a + b);
5
6
PYTHON SYNTAX

• INDENTATION
• Python provides no braces to indicate blocks of code for class and function definitions
or flow control.
• Blocks of code are denoted by line indentation, which is rigidly enforced.
• The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount.
• Header lines begin the statement (with a keyword) and terminate with a colon ( : )
and are followed by one or more lines which make up a suite.
if a >= 0: if a >= 0: a = 0 a = 0
print(“yes”) print(“yes”) while a < 10: while a < 10:
else: else: print(a) print(a) # one tab
print(“no”) print(“no”) a += 1 a += 1 # 4 spaces

INCORRECT INCORRECT
CORRECT INCORRECT (Non matching
(Both tabs) (No indentation) Indentation) 7
GETTING HELP IN PYTHON ITSELF

• Use the help function to get help on objects or functions


• Examples:
• >>> help(print)
• >>> help(input)
• >>> help(list)
• >>> help(tuple)
• >>> help(int)
• >>> help(“a string”.find)
• Don’t use help for keywords
• >>> help(for)
File "<stdin>", line 1
help(for)
^
SyntaxError: invalid syntax
8
VARIABLES

• Everything in Python is an object that has:


• An Identitiy (ID), the object’s memory address
• A Value
• Values are either mutable or immutable

Mutable values: When a mutable value is Immutable values: The id changes when the
changed, the id remains the same (Lists, item is altered (Strings, Integers,Tuples, …)
Dictionaries, Floats, …)

>>> l = [1, 2, 3] >>> a = 4


>>> id(l) >>> id(a)
1823670346504 1876061760
>>> l.append(4) >>> a = a + 1
>>> id(l) >>> id(a)
1823670346504 1876061792

9
IMMUTABLE NUMBERS

BENEFITS OF IMMUTABLE NUMBERS >>> a = 4


>>> b = 4
• Saves memory.
• If it's well known that an object is immutable, it can be easily >>> c = 4
copied creating a new reference to the same object. >>> id(a)
• Performance. 1876061760
• Python can allocate space for an immutable object at >>> id(b)
creation time, and the storage requirements are fixed and
unchanging. 1876061760
• It doesn't have to copy each part of the object, only a simple >>> id(c)
reference.
• Easy to be compared, comparing equality by reference is 1876061760
faster than comparing values. >>> id(4)
1876061760

10
VARIABLE ASSIGNMENT

• TARGET0 = TARGET1 = TARGET2 = … = EXPRESSION


• Each target will be assigned the value of EXPRESSION
• >>> a = 2 + 2
• >>> b = ‘a string’
• >>> x = y = z = 3.6
• A Python identifier is a name used to identify a variable, function, class, module or other
object.
• An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero
or more letters, underscores and digits (0 to 9).

• Variable references can be deleted using the del keyword


>>> a = 3
>>> del a
>>> print(a) # NameError
11
VARIABLE ASSIGNMENT

• Targets can also be assigned using an iterator


• TARGET1, TARGET2, … TARGET_N = VALUE1, VALUE2, …, VALUE_N
• OR: TARGET1, TARGET2, … TARGET_N = an iterable object with n values
>>> a, b, c = 1, 2, 3
>>> l = [1, 2, 3]
>>> a, b, c = l
>>> c1, c2, c3 = ‘xyz’
• The number of targets must be the same as the number of values.
• Same as TARGET_i = VALUE_i for each i, but values are first unpacked then assigned:
>>> x = 3
>>> y = 4
>>> x, y = y, x
>>> print(x, y)
4 3
12
RESERVED KEYWORDS

• Python Reserved Words


• The following identifiers are used as reserved words of the language, and cannot be
used as ordinary identifiers.
False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise

13
DATA TYPES

• Numbers
• Strings
• Lists
• Tuples
• Dictionaries
• Sets
• …
You can get the type of a variable using type(var)

14
NUMBERS

• 3 Types of numbers:
• Integers (int): 15, 0xF (hexadecimal), 0b1111 (binary), 0o17 (octal)
• Casting: int(value)
• >>> int(‘0xF’)
• >>> int(3.5)
• >>> int(‘a’)
• ValueError: invalid literal for int() with base 10
• >>> int(‘a’, 16)
• 10
• >>> int(‘110’, 2)
• 6
• >>> int(‘12345’)
• 12345
15
NUMBERS

• Floating points (float): 1.5, 15e-1, 15E1


• Casting: float(value)
• >>> float(‘-1e6’)

• Complex (complex): x + yj
• x and y are both numbers
• Create using complex(x, y)

16
STRINGS

• Create them simply by enclosing characters in quotes. Python treats single quotes the
same as double quotes.
• Python does not support a character type; these are treated as strings of length one.

• >>> s1 = ‘this is a string’


• >>> s2 = “this is a string”

• Use triple quotes to create a paragraph.

>>> s3 = ‘’’this is
a string’’’
>>> print(s3)
'this is\na string'
17
STRINGS

• ACCESSING STRINGS
• To access substrings, use the square brackets for slicing along with the index or indices
to obtain your substring.

>>> s = ‘hello world’


>>> s[3] >>> s[:6]
‘l’ 'hello ‘
>>> s[3:6] >>> s[3:-3]
‘lo ’ 'lo wo’
>>> s[-3]
>>> s[3:] ‘r’
'lo world’

• More on strings and regular expressions in the next presentation.


18
LISTS

• The list is the most versatile datatype available in Python which can be written as a list
of comma-separated values (items) between square brackets.
• Items in a list don’t need to be of the same type.

• CREATING A LIST
• >>> l1 = [1, 2.0, 3+4j, ‘hello’, [1, 2, 3]]

• You can also convert an iterable object to a list:


• >>> l2 = list(‘hello’)
• >>> l3 = list(range(10))

• ACCESSING LISTS
• Just like indexing and slicing in strings.
19
LISTS

• UPDATING LISTS
• Assign a value to an index:
>>> l = [1, 2, 3, 4]
>>> l[0] = 10
>>> l[1:4] = [20, 30, 40]
>>> print(l)
[10, 20, 30, 40]

• Use the append method to add new items:


>>> l.append(50)
>>> l += [60]
>>> print(l)
[10, 20, 30, 40, 50, 60]
20
LISTS

• DELETING LIST ITEMS


• Using either the del keyword or a lists .remove method:
>>> l = [1, 2, 3, 4, 5]
>>> del l[0]
>>> print(l)
[2, 3, 4, 5]
>>> l.remove(3)
>>> print(l)
[2, 4, 5]
>>> l.remove(l[1])
>>> print(l)
[2, 5]

21
LISTS

• LIST OPERATIONS
• List concatenation (using +):
>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> l1 + l2
[1, 2, 3, 4, 5, 6]

• Repetition (using *):


>>> l = [1] * 5
>>> l
[1, 1, 1, 1, 1]

22
LISTS

LIST FUNCTIONS
• >>> l = [1, 2, 3, 4, 5]

• Length of a list:
>>> len(l)
5

• Maximum and minimum values of a list:


>>> max(l)
5
>>> min(l)
1
23
LISTS

LIST METHODS

METHOD DESCRIPTION

l.append(val) Appends val to the list l

l.extend(seq) Appends the contents of seq to the list l

Returns the count of how many times val


l.count(val)
occurs in l

l.index(val) Returns the lowest index in l that val appears

l.insert(index, val) Inserts val into list l at offset index

l.reverse() Reverses list in place

l.sort() Sorts list in place

24
TUPLES

• The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses ()
and cannot be updated.Tuples can be thought of as read-only lists.

>>> t = (1, ‘2’, [3])


>>> t[0] = 2 # error
>>> t = t + (3,) # t = (1, ‘2’, [3], 3)
>>> t[2][0] = 0 # t = (1, ‘2’, [0])

>>> t = t + [4]
TypeError: can only concatenate tuple (not "list") to tuple

25
ARITHMETIC OPERATORS

Operator Description Example


a + b addition 2 + 4 = 6
a – b subtraction 2 – 4 = -2
a * b multiplication 2 * 4 = 16
a / b division 7 / 2 = 3.5
a % b modulus 8 % 3 = 2
a ** b exponent 2 ** 4 = 16
a // b floor division 7 // 2 = 3

All arithmetic operators can be used with an assignment operator:

>> a = 2
>> a **= 4
>> a
16 26
BITWISE AND LOGIC AL OPERATORS

Operator Description Example


a and b Logical AND ( && ) a > 2 and b < 3
a or b Logical OR ( || ) a > 2 or b < 3
not a Logical NOT ( ! ) not a > 2
a & b Bitwise AND 12 & 10 = 8
a | b Bitwise OR 12 | 10 = 14
a ^ b Bitwise XOR 12 ^ 10 = 6
~ a Bitwise Ones Complement ~12 = -13
a << b Binary Shift Left 1 << 4 = 16
a >> b Binary Shift Right 16 >> 4 = 1
• Notice the capital T in True and F in False
• All bitwise operators can be used with an assignment operator:
>> a = 16
>> a ^= 12
>> a
27
28
RELATIONAL OPERATORS

Operator Description Example


==
!=
<
<=
>
>=

• For sequences, < and > use lexicographical ordering:

>>> l1 = [1, 2, 3, 4]
>>> l2 = [1, 2, 5, 4]
>>> l1 < l2
True
>>> l1 > l2
False 28
MEMBERSHIP AND IDENTITY OPERATORS

Operator Description Example

>>> 2 in [1, 2]
a in b True if a is found in b
True

>>> 3 not in [1, 2]


a not in b True if a is not found in b
True

True if a and b point to the >>> x = 4


>>> y = 4
a is b same object
>>> x is y
(id(a) == id(b)) True

True if a and b don’t point to >>> a = [1, 2, 3]


>>> b = [1, 2, 3]
a is not b the same object
>>> a is not b
(id(a) != id(b)) True

29
GETTING INPUT

• Use the input(prompt) function to get input


• input() gets the whole line
• >>> s = input(“Enter your name: “)
• Enter your name: My Name
• >>> s
• ‘My Name’
• Split the input string to get multiple values in one line:

>>> nums = input() >>> list(map(int, nums.split()))


1 2 3 [1, 2, 3]
>>> nums
‘1 2 3’ list(map(int, input().split()))
>>> list(nums.split())
[‘1’, ‘2’, ‘3’]
30
DECISION MAKING

if EXPRESSION: a = [1, 2, [3]]


STATEMENTS if 3 in a:
elif EXPRESSION: print(“Block A”)
STATEMENTS elif [3] in a:
else: print(“Block B”)
STATEMENTS elif (3,) in a:
print(“Block C”)

• Single line decision making:


• val = (STMT_TRUE if EXPRESSION else STMT_FALSE)
• Same as (EXPRESSION ? STMT_TRUE : STMT_FALSE) in other languages
• Example:
• s = input()
• print(“Number” if s.isdecimal() else “Not a number”) 31
FOR LOOPS

for VARS in SEQUENCE: for i in range(start=0, stop, step=1):


STATEMENTS STATEMENTS
else: else:
STATEMENTS STATEMENTS

• Else block is executed when the loop has exhausted


• Else is not executed if a break statement is reached during the loop
• Start is inclusive but stop isn’t
for i in range(11): for c in ‘Python’:
if i % 2 == 0: print(c)
print(i)

for i in range(0, 11, 2): print(i)

• Creating lists using single line loops (generators), more about generators in the functions section

• l1 = [x for x in ‘1a2b3c4d’ if x.isdecimal()] 32


• l2 = list(x for x in range(4, 0, -1))
WHILE LOOPS

while EXPRESSION:
STATEMENTS
else:
STATEMENTS

a = 0
while a <= 10:
if a % 2 == 0:
print(a)
a += 1 # no ++a in python!

• The pass statement does nothing (a.k.a NOP)


• It acts as an empty block:

while not input().isdecimal():


pass
print(‘You entered a number’)
33
EXAMPLES

• Write a python program that:

A. Calculates the average of some given numbers


B. Checks if a string is a palindrome
C. Prints the nth Fibonacci number
D. Checks if a list is a subset of another
E. Finds the parity bit of a given integer
F. Removes all duplicated values from a list

34
CODEFORCES 673A

Bear Limak likes watching sports on TV. He is going to watch a game today. The game
lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then
Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for
how many minutes Limak will watch the game.

Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting
minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the
increasing order.

Output
Print the number of minutes Limak will watch the game.

35
CODEFORCES 779B

Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that
is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2).
In this case, the result is 3000 that is divisible by 103 = 1000.
Write a program that prints the minimum number of digits to be deleted from the given integer
number n, so that the result is divisible by 10k. The result should not start with the unnecessary
leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one
digit).
It is guaranteed that the answer exists.

Input
The only line of the input contains two integer numbers n and k (0 ≤ n ≤ 2 000 000 000, 1 ≤ k ≤ 9).
It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of
integers, that is, without any extra leading zeros.

Output
Print w — the required minimal number of digits to erase. After removing the appropriate w digits
from the number n, the result should have a value that is divisible by 10k. The result can start with
digit 0 in the single case (the result is zero and written by exactly the only digit 0).
36
CODEFORCES 831A

An array of integers is unimodal, if:


• it is strictly increasing in the beginning;
• after that it is constant;
• after that it is strictly decreasing.
The first block (increasing) and the last block (decreasing) may be absent. It is allowed
that both of this blocks are absent.
For example, the following three arrays are unimodal: [5, 7, 11, 11, 2, 1], [4, 4, 2], [7], but
the following three are not unimodal: [5, 5, 6, 6, 1], [1, 2, 1, 2], [4, 5, 5, 6].
Write a program that checks if an array is unimodal.

Input
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1 000) — the elements of the
array.

Output
Print "YES" if the given array is unimodal. Otherwise, print "NO".
You can output each letter in any case (upper or lower). 37

You might also like