1 - Python Basics
1 - Python Basics
Parham Kazemi
University of Isfahan, Computer Eng. Faculty
ACM Student Chapter
pkazemi3@gmail.com
ABOUT PYTHON
• 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
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
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, …)
9
IMMUTABLE NUMBERS
10
VARIABLE ASSIGNMENT
as elif if or yield
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
• 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.
>>> 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.
• 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]]
• 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]
21
LISTS
• LIST OPERATIONS
• List concatenation (using +):
>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> l1 + l2
[1, 2, 3, 4, 5, 6]
22
LISTS
LIST FUNCTIONS
• >>> l = [1, 2, 3, 4, 5]
• Length of a list:
>>> len(l)
5
LIST METHODS
METHOD DESCRIPTION
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 = t + [4]
TypeError: can only concatenate tuple (not "list") to tuple
25
ARITHMETIC OPERATORS
>> a = 2
>> a **= 4
>> a
16 26
BITWISE AND LOGIC AL OPERATORS
>>> l1 = [1, 2, 3, 4]
>>> l2 = [1, 2, 5, 4]
>>> l1 < l2
True
>>> l1 > l2
False 28
MEMBERSHIP AND IDENTITY OPERATORS
>>> 2 in [1, 2]
a in b True if a is found in b
True
29
GETTING INPUT
• Creating lists using single line loops (generators), more about generators in the functions section
while EXPRESSION:
STATEMENTS
else:
STATEMENTS
a = 0
while a <= 10:
if a % 2 == 0:
print(a)
a += 1 # no ++a in python!
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
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