Introduction to Python. Basic data types, syntax and operators

Simple program

Try to guess what will be the output of this simple program.

names = ["Vlad Dracula", "Vladimir Putin", "Samwise Gamgee", "Ryan Rossam"] for name in names: if "Vlad" in name: print(name)

Structure of Python's program

  1. Programs are composed of modules.
  2. Modules contain statements.
  3. Statements contain expressions.
  4. Expressions create and process objects.

Variables

a = 3

Variables of certain data type used to code their literals. Variables are simply names—created by you or Python—that are used to keep track of information in your program. A variable (i.e., name), like a, is created when your code first assigns it a value. Future assignments change the value of the already created name.

A variable never has any type information or constraints associated with it. The notion of type lives with objects, not names. Variables are generic in nature; they always simply refer to a particular object at a particular point in time.

Term literal simply means an expression whose syntax generates an object.

  • Variables are created when they are first assigned values.
  • Variables are replaced with their values when used in expressions.
  • Variables must be assigned before they can be used in expressions.
  • Variables refer to objects and are never declared ahead of time.
a = 'spam' # Now it's a string
a = 3 # Name created: not declared ahead of time b = 4 c = a + b c
7
3 + 4
7

I’ve also used a comment here. Recall that in Python code, text after a # mark and continuing to the end of the line is considered to be a comment and is ignored by Python. Comments are a way to write human-readable documentation for your code.

Core data types its operators

Data type Example literals/creation
Numbers 1234, 3.1415, 3+4j
Strings 'spam', "Bob's"
Lists [1, [2, 'three'], 4.5], list(range(10))
Dictionaries {'food': 'spam', 'taste': 'yum'}, dict(hours=10)
Tuples (1, 'spam', 4, 'U'), tuple('spam')
Sets set('abc'), {'a', 'b', 'c'}
Other core types Booleans, types, None

Numbers

  • integers that have no fractional part. Integers are written as strings of decimal digits.
  • floating-point numbers have a decimal point and/or an optional signed exponent introduced by an e or E and followed by an optional sign.
  • complex. Python complex literals are written as realpart+imaginarypart, where the imaginarypart is terminated with a j or J.
integer = 1234
integer_negative = -24
float_number = 1.23
float_engineer = 3.14e-10
complex_num = 3+4j

Operations with numbers

Operators Description
x + y Addition
x – y Subtraction
x * y Multiplication;
x % y Remainder
x / y, x // y Division: true and floor
−x Negation
x ** y Power

When you write an expression with more than one operator, Python groups its parts according to what are called precedence rules, and this grouping determines the order in which the expression’s parts are computed. Table is ordered by operator precedence: operators lower in the table have higher precedence.

You can forget about precedence completely if you’re careful to group parts of expressions with parentheses. When you enclose subexpressions in parentheses, you override Python’s precedence rules; Python always evaluates expressions in parentheses first before using their results in the enclosing expressions.

2.3 * 5
11.5

Notice how mixed types are allowed in numeric expressions. In mixed-type numeric expressions, Python first converts operands up to the type of the most complicated operand, and then performs the math on same-type operands

10 // 4 # truncates remainder
2

Calculate the following expression: 41268324510000\frac{4^{12}}{6^8}⋅\sqrt{3245} - 10000

# write a code

Comparisons

1 < 2 # Less than
True
2.0 >= 1 # Greater than or equal: mixed-type 1 converted to 1.0
True
2.0 == 2
True
2.0 == 2.0 # Equal value
True
2.0 != 2.0 # Not equal value
False

Boolean

Python Boolean type, bool, is numeric in nature because its two values, True and False, are just customized versions of the integers 1 and 0 that print themselves differently.

Because True is just the integer 1 with a custom display format, True + 4 yields integer 5 in Python!

type(True)
bool
isinstance(True, int)
True
bool(0)
False
bool(1)
True
True == 1 # Same value
True
True + 4 # (Hmmm)
5
Operators Description
x if y else z Ternary selection (x is evaluated only if y is true)
x or y Logical OR (y is evaluated only if x is false)
x and y Logical AND (y is evaluated only if x is true);
not x Logical negation
x in y, x not in y Membership
x is y, x is not y Object identity tests

Practical assignment

You promised to visit you granny on holydays if weather will not be rainy and temperature will be above 15°C or if she fall ill.

Now you have following conditions:

holyday = True weather = "cloudy" temperature = 22 ill = False

Will you go to your lovely granny? To answer this question write a propram in Python using logical operations.

# write your code here

While you have written the code the temperature has changed to 19°C. Will you change the decision?

temperature = 19 # write your code here

Strings

Python string is an ordered collection of characters used to store and represent text- and bytes-based information.

Operators Interpretation
S = '' Empty string
S = "spam's" Double quotes, same as single
S = 's\np\ta\x00m' Escape sequences. Escape sequences let us embed characters in strings that cannot easily be typed on a keyboard. The character , and one or more characters following it in the string literal, are replaced with a single character in the resulting string object, which has the binary value specified by the escape sequence.
S = """...multiline...""" Triple-quoted block strings, that is a syntactic convenience for coding multiline text data.
S1 + S2 Concatenate
S * 3 Repeat
S[i] Index
S[i:j:k] Slice
len(S) Length

Indexing and Slicing

Because strings are defined as immutable ordered collections of characters, we can access their components by position. In Python, characters in a string are fetched by indexing— providing the numeric offset of the desired component in square brackets after the string.

Python offsets start at 0 and end at one less than the length of the string.

Python also lets you fetch items from sequences such as strings using negative offsets. Technically, a negative offset is added to the length of a string to derive a positive offset.

S = 'spam' S = str("spam") S[0]
's'
S[-2] # fetches the second item from the end (like S[len(S)−2])
'a'
S = 'abcdefghijklmnop'
S[1:10:2] # Skipping items
'bdfhj'
S[::2]
'acegikmo'

String Conversion

"42" + 1
TypeError: must be str, not int
"42" + str(1)
'421'

String Methods

Methods Interpretation
S.split() Split on delimiter
S.rstrip() Remove whitespace
S.replace('pa', 'xx') Replacement
S.split(',') Split on delimiter
S.isdigit() Content test
S.lower(), S.upper() Case conversion
S.startswith('spam') Start test
S.endswith('spam') End test
S.find('spam') Search. -1 if no, index if yes

Practical assignment

That is a song by Nirvana.

song = """Rape me, rape me my friend Rape me, rape me again I'm not the only one I'm not the only one I'm not the only one I'm not the only one Hate me Do it and do it again Waste me Rape me, my friend I'm not the only one I'm not the only one I'm not the only one I'm not the only one My favorite inside source I'll kiss your open sores Appreciate your concern You're gonna stink and burn Rape me, rape me my friend Rape me, rape me again I'm not the only one I'm not the only one I'm not the only one I'm not the only one Rape me (rape me) Rape me (rape me) Rape me (rape me) Rape me (rape me) Rape me (rape me) Rape me (rape me) Rape me (rape me) Rape me (rape me) Rape me"""
  1. What is the length of this song?

  2. Split the song by lines (lines delimitered by \n). How many lines it has?

  3. This song sounds a bit depressive, isn't it? Make it more positive by replacing phrase "rape me" to "kiss me".

  4. Print this song from end to begining. Try to sing it.

# write code here
from IPython.display import HTML HTML('<details><summary>🎉Good job!🎉 Enjoy you prize!</summary><iframe width="560" height="315" src="https://www.youtube.com/embed/Ax0C6rlo-54?start=82" frameborder="0" allowfullscreen></iframe></details>')
🎉Good job!🎉 Enjoy you prize!

Lists

Lists are Python’s most flexible ordered collection object type. Unlike strings, lists can contain any sort of object: numbers, strings, and even other lists. Also, unlike strings, lists may be changed in place by assignment to offsets and slices, list method calls, deletion statements, and more—they are mutable objects.

l = [] # An empty list l
[]
l = list('spam') # List of an iterable’s items l
['s', 'p', 'a', 'm']
l = [123, 'abc', 1.23, {}] # Four items: indexes 0..3 l
[123, 'abc', 1.23, {}]
l = ['Sasha', 40.0, ['analyst', 'manager']] # Nested sublists
l[1] = 3 # Index assignment l
['Sasha', 3, ['analyst', 'manager']]
l.append(4) l
['Sasha', 3, ['analyst', 'manager'], 4]
l.extend([5,6,7]) l
['Sasha', 3, ['analyst', 'manager'], 4, 5, 6, 7]
l = list('spam') l.sort() # Methods: sorting l
['a', 'm', 'p', 's']
l = list('spam') + [5,6,7] l
['s', 'p', 'a', 'm', 5, 6, 7]
l.remove("p") # remove by literal l
['s', 'a', 'm', 5, 6, 7]
del l[0] l
['a', 'm', 5, 6, 7]

Practical assignment

  1. Create a shopping list with 🍎apple, 🍓strawberry, 🥕carrot, 🍌banana.

  2. What is the length of this list? Print it.

  3. Add 🍚rice to the end of this list.

  4. Sort shopping list alphabetically for a to z.

  5. Print last two items of this list.

  6. You just have remembered that you have allergy on 🍓strawberry. Replce it with 🍊orange.

  7. Bon appétit!

Dictionaries

Dictionaries are sometimes called associative arrays or hashes (especially by users of other scripting languages). They associate a set of values with keys, so you can fetch an item out of a dictionary using the key under which you originally stored it.

Unlike in a list, items stored in a dictionary aren’t kept in any particular order.

You can change dictionaries in place by assigning to indexes (they are mutable), but they don’t support the sequence operations that work on strings and lists. Because dictionaries are unordered collections, operations that depend on a fixed positional order (e.g., concatenation, slicing) don’t make sense.

D = {} # Empty dictionary
D = {'name': 'Sergey', 'age': 22} # Two-item dictionary D = dict(name='Sergey', age=22) # Alternative construction techniques
D['name'] # Indexing by key
'Sergey'
E = {'food': {'name': 'pizza', 'price': 10}} # Nesting
E["food"]["price"]
10
D.update(E) # merge by keys
D
{'name': 'Sergey', 'age': 22, 'food': {'name': 'pizza', 'price': 10}}
'age' in D # Membership: key present test
True
D.keys() # Method: all keys
dict_keys(['name', 'age', 'food'])
D.values() # Method: all values
dict_values(['Sergey', 22, {'name': 'pizza', 'price': 10}])
D.items() # Method: all key+value tuples
dict_items([('name', 'Sergey'), ('age', 22), ('food', {'name': 'pizza', 'price': 10})])
D["surname"] = "Ivanov" D
{'name': 'Sergey',
'age': 22,
'food': {'name': 'pizza', 'price': 10},
'surname': 'Ivanov'}
del D["surname"] D

Practical assignment

Create a data structue, to store this information:

User Sasha Berg ordered a one pepperoni pizza and two bottles of Coca-cola.

# write a code

Then he changed the changed his mind and replace Pepperoni pizza by two Margherita pizzas. Update our data to reflect the changes.

# write a code

Statements

  1. Programs are composed of modules.
  2. Modules contain statements.
  3. Statements contain expressions.
  4. Expressions create and process objects.

Programs written in the Python language are composed of statements and expressions. Expressions process objects and are embedded in statements. Statements code the larger logic of a program’s operation—they use and direct expressions to process the objects we studied in the preceding chapters.

name = "Yuri" # simple assignment statement

All Python compound statements — statements that have other statements nested inside them — follow the same general pattern of a header line terminated in a colon, followed by a nested block of code usually indented underneath the header line, like this:

Header line:
    Nested statement block

The colon is required, and omitting it is probably the most common coding mistake among new Python programmers.

There is no universal standard on this: four spaces or one tab per level is common, but it’s generally up to you to decide how and how much you wish to indent, but you probably shouldn’t mix tabs and spaces.

Although statements normally appear one per line, it is possible to squeeze more than one statement onto a single line in Python by separating them with semicolons:

a = 1; b = 2; print(a + b) # Three statements on one line
3

This is the only place in Python where semicolons are required: as statement separators.

The other special rule for statements is essentially the inverse: you can make a single statement span across multiple lines. To make this work, you simply have to enclose part of your statement in a bracketed pair—parentheses (()), square brackets ([]), or curly braces ({})

( 1 + 10 * 20 )
201

if Statements

if statement selects actions to perform. It represents much of the logic a Python program.

General format:

if test1:          # if test
    statements1
elif test2:        # Optional elifs
    statements2
else:              # Optional else
    statements3
i = 3
if i < 5: print(True) i = i + 1

To handle a false result, code the else:

if i < 5: print(True) i = i + 1 else: print(False)
False
if i < 0: print(i/5) elif i > 0: print(i/3) else: pass
Positive
if i < 0: print(i/5) else: if i > 0: print(i/3) else: print("error") # pass

Practical assignment

What is the other way to write the same program with one-leve indent and without elif? (do nothing if 0)

# write your code here

Write a simple program which will receive user input and print it in uppercase if it is a string and set it to the power of 2 if it is an odd number and to the power of 3 otherwise. Use input function to recive an user input.

inp = input()
3
# write your code here

for loops

for can step through the items in any ordered sequence or other iterable object. The for statement works on strings, lists, tuples, and other iterables.

General format:

for target in object:
    statements
names = ["Sasha Robinovich", "Bob Smith", "Sasha Grey", "Max"] for name in names: print(name)
Sasha Robinovich
Bob Smith
Sasha Grey
Max
names = ["Sasha Robinovich", "Bob Smith", "Sasha Grey", "Max"] for name in names: if "Sasha" in name: print(name)
Sasha Robinovich

More complete format:

for target in object:
    statements
else:                   # Optional else part
    statements          # If we didn't hit a 'break'

Else statement executes if the loop exits without running into a break statement.

The break statement causes an immediate exit from a loop. Because the code that follows it in the loop is not executed if the break is reached, you can also sometimes avoid nesting by including a break.

The continue statement causes an immediate jump to the top of a loop. It also sometimes lets you avoid statement nesting.

The pass statement does nothing at all: it’s an empty statement placeholder.

Practical assignment 1

Print odds numbers from a range from 0 to 50 and save them in a list.

Hint: use function range() to create a range.

# write your code here

Practical assignment 2

Previously we saw that dictionaries are unordered collections. Write a for loop that prints a dictionary’s items in sorted (ascending) order. (Hint: use the dictionary keys and list sort methods, or the newer sorted built-in function.)

# write your code here

List Comprehensions

List comprehensions provide a concise way to create lists.

As list comprehension returns list, they consists of brackets containing the expression which needs to be executed for each element along with the for loop to iterate over each element.

Practical assignment

Rewrite "6.2.1 Practical assignment 1" using list Comprehensions

# write your code here

while loop

It repeatedly executes a block of (normally indented) statements as long as a test at the top keeps evaluating to a true value.

while test:
    statements
else:
    statements
i = 0 while i != 5: print(i) i += 1
0
1
2
3
4

Modules

  1. Programs are composed of modules.
  2. Modules contain statements.
  3. Statements contain expressions.
  4. Expressions create and process objects.

Python module is the highest-level program organization unit, which packages program code and data for reuse, and provides self-contained namespaces that minimize variable name clashes across your programs.

import math # import lets a client (importer) fetch a module as a whole
math
math.pi # constants
3.141592653589793
math.cos(math.pi)
-1.0
import math as m # The `as` keyword is used for aliasing in Python.
from math import log, e # `from` allows clients to fetch particular names from a module
log(e)
1.0
from math import factorial as fct # `import`, `as` and `from` can be used together
fct(10)
3628800

Files

The last major built-in object type that we’ll examine on our object types tour provides a way to access files inside Python programs.

In short, the built-in open function creates a Python file object, which serves as a link to a file residing on your machine. After calling open, you can transfer strings of data to and from the associated external file by calling the returned file object’s methods.

Compared to the types you’ve seen so far, file objects are somewhat unusual. They are considered a core type because they are created by a built-in function, but they’re not numbers, sequences, or mappings, and they don’t respond to expression operators; they export only methods for common file-processing tasks.

To open a file, a program calls the built-in open function, with the external filename first, followed by a processing mode. The call returns a file object, which in turn has methods for data transfer:

========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r'       open for reading (default)
'w'       open for writing, truncating the file first
'x'       create a new file and open it for writing
'a'       open for writing, appending to the end of the file if it exists
'b'       binary mode
't'       text mode (default)
file_obj = open("data.txt", "wt", encoding="utf8")
file_obj.write("First line\n") # Write a line of text: string file_obj.write("Second line\n") file_obj.close() # Close the file
file_obj = open("data.txt")
file_obj.readlines()
['First line\n', 'Second line\n']
file_obj.seek(0)
0
for line in file_obj: print(line.upper(), end="")
FIRST LINE
SECOND LINE
file_obj.close()

Practical assignment

Some guys scraped tweets from 100+ pro-ISIS fanboys from all over the world since the November 2015 Paris Attacks.

Example of such tweet:

RT @maaj19: سَمِعْنَا وَ أطَعْنَا #gd #gd#fdfd @allah

I saved random sample of these tweets in a file "tweets_IS.txt", one tweet per line. Read the file and do the following tasks:

  1. Calculate the distribution of hashtags. What is the most populat hashtag in these tweets?
  2. Calculate the distribution of mentions. What is the most populat user mentioned in these tweets?
  3. What is the longest tweet?
# write your code here

Function

Function is a device that groups a set of statements so they can be run more than once in a programa packaged procedure invoked by name. Functions also can compute a result value and let us specify parameters that serve as function inputs and may differ each time the code is run.

Functions are also the most basic program structure Python provides for maximizing code reuse. As we’ll see, functions let us split complex systems into manageable parts. By implementing each part as a function, we make it both reusable and easier to code.

General format:

def name(arg1, arg2,... argN):
    statements
    return value # optional part

As with all compound Python statements, def consists of a header line followed by a block of statements, usually indented (or a simple statement after the colon). The statement block becomes the function’s body — that is, the code Python executes each time the function is later called.

The Python return statement can show up anywhere in a function body; when reached, it ends the function call and sends a result back to the caller.

Lets define a function:

def times(x, y): # Create and assign function return x * y # Body executed when called
times(2, 4) # Arguments in parentheses
8
x = times("lo", 4) # Save the result object x
'lolololo'

Functions can accept default arguments. These arguments can either be specified by the caller or left blank to automatically receive a predefined value.

def power(x, power=2): # to the power of 2 by default return x ** power # Body executed when called
power(3)
9
power(3, 1)
3

Lambda functions

Besides the def statement, Python also provides an expression form that generates function objects, it’s called lambda.

Like def, this expression creates a function to be called later, but it returns the function instead of assigning it to a name. This is why lambdas are sometimes known as anonymous (i.e., unnamed) functions. In practice, they are often used as a way to inline a function definition.

The lambda’s general form is the keyword lambda, followed by one or more arguments (exactly like the arguments list you enclose in parentheses in a def header), followed by an expression after a colon:

lambda argument1, argument2,... argumentN : expression using arguments
def power(x, power=2): return x ** power
power = lambda x, power=2: x**power

There are a few differences that make lambdas useful in specialized roles:

  1. lambda is an expression, not a statement. Because of this, a lambda can appear in places a def is not allowed by Python’s syntax—inside a list literal or a function call’s arguments, for example. With def, functions can be referenced by name but must be created elsewhere. As an expression, lambda returns a value (a new func- tion) that can optionally be assigned a name. In contrast, the def statement always assigns the new function to the name in the header, instead of returning it as a result.

  2. lambda’s body is a single expression, not a block of statements.

Why Use lambda?

Take a look at the sorted function. It returns a new list containing all items from the iterable in ascending order.

sorted()

Lets create a list of random numbers with module random.

import random # Return a k sized list of population elements chosen with replacement. random_list = random.choices(range(100), k=10) random_list
[28, 61, 3, 11, 96, 73, 33, 28, 93, 32]
sorted(random_list)
[3, 11, 28, 28, 32, 33, 61, 73, 93, 96]

sorted function has an argument key, which accept a custom key function can be supplied to customize the sort order. It is useful when we want to sort by nested element.

orders = [ { "name": "pizza pepperoni", "price": 12, "amount": 1 }, { "name": "Coca-cola", "price": 4, "amount": 2 }, { "name": "Cupcake", "price": 3, "amount": 10 } ]
sorted(orders, key=lambda el: el["price"])
[{'name': 'Cupcake', 'price': 3, 'amount': 10},
{'name': 'Coca-cola', 'price': 4, 'amount': 2},
{'name': 'pizza pepperoni', 'price': 12, 'amount': 1}]
# it is the same as def sort_function(el): return el["price"] sorted(orders, key=sort_function)
[{'name': 'Cupcake', 'price': 3, 'amount': 10},
{'name': 'Coca-cola', 'price': 4, 'amount': 2},
{'name': 'pizza pepperoni', 'price': 12, 'amount': 1}]

Practical assignment

There is a mistake in a previous example. Orders must be sorted in another way. Why? Write correct answer.

Комментарии