Key Takeaways - PDV - PRASAD
Key Takeaways - PDV - PRASAD
Key Takeaways - PDV - PRASAD
2. Built-in functions, contrary to user-defined functions, are always available and don't have to
be imported. Python 3.7.1 comes with 69 built-in functions. You can find their full list provided
in alphabetical order in the Python Standard Library.
3. To call a function (function invocation), you need to use the function name followed by
parentheses. You can pass arguments into a function by placing them inside the parentheses. You
must separate arguments with a comma, e.g., print("Hello,", "world!"). An "empty"
print() function outputs an empty line to the screen.
4. Python strings are delimited with quotes, e.g., "I am a string", or 'I am a string,
too'.
6. In Python strings the backslash (\) is a special character which announces that the next
character has a different meaning, e.g., \n (the newline character) starts a new output line.
7. Positional arguments are the ones whose meaning is dictated by their position, e.g., the
second argument is outputted after the first, the third is outputted after the second, etc.
8. Keyword arguments are the ones whose meaning is not dictated by their location, but by a
special word (keyword) used to identify them.
9. The end and sep parameters can be used for formatting the output of the print() function.
The sep parameter specifies the separator between the outputted arguments (e.g., print("H",
"E", "L", "L", "O", sep="-"), whereas the end parameter specifies what to print at the end
of the print statement.
Key takeaways
1. An expression is a combination of values (or variables, operators, calls to functions - you will
learn about them soon) which evaluates to a value, e.g., 1 + 2.
2. Operators are special symbols or keywords which are able to operate on the values and
perform (mathematical) operations, e.g., the * operator multiplies two values: x * y.
4. A unary operator is an operator with only one operand, e.g., -1, or +3.
Exercise 1
Exercise 2
Exercise 3
1. A variable is a named location reserved to store values in the memory. A variable is created
or initialized automatically when you assign a value to it for the first time. (2.1.4.1)
2. Each variable must have a unique name - an identifier. A legal identifier name must be a non-
empty sequence of characters, must begin with the underscore(_), or a letter, and it cannot be a
Python keyword. The first character may be followed by underscores, letters, and digits.
Identifiers in Python are case-sensitive. (2.1.4.1)
3. Python is a dynamically-typed language, which means you don't need to declare variables in
it. (2.1.4.3) To assign values to variables, you can use a simple assignment operator in the form
of the equal (=) sign, i.e., var = 1.
4. You can also use compound assignment operators (shortcut operators) to modify values
assigned to variables, e.g., var += 1, or var /= 5 * 2. (2.1.4.8)
5. You can assign new values to already existing variables using the assignment operator or one
of the compound operators, e.g.: (2.1.4.5)
6. You can combine text and variables using the + operator, and use the print() function to
output strings and variables, e.g.: (2.1.4.4)
Key takeaways
1. Comments can be used to leave additional information in code. They are omitted at runtime.
The information left in source code is addressed to human readers. In Python, a comment is a
piece of text that begins with #. The comment extends to the end of line.
2. If you want to place a comment that spans several lines, you need to place # in front of them
all. Moreover, you can use a comment to mark a piece of code that is not needed at the moment
(see the last line of the snippet below), e.g.:
4. It's important to use comments to make programs easier to understand, and to use readable and
meaningful variable names in code. However, it's equally important not to use variable names
that are confusing, or leave comments that contain wrong or incorrect information!
5. Comments can be important when you are reading your own code after some time (trust us,
developers do forget what their own code does), and when others are reading your code (can
help them understand what your programs do and how they do it more quickly).
Key takeaways
1. The print() function sends data to the console, while the input() function gets data from
the console.
2. The input() function comes with an optional parameter: the prompt string. It allows you to
write a message before the user input, e.g.:
name = input("Enter your name: ") print("Hello, " + name + ". Nice to meet
you!")
3. When the input() function is called, the program's flow is stopped, the prompt symbol keeps
blinking (it prompts the user to take action when the console is switched to input mode) until the
user has entered an input and/or pressed the Enter key.
NOTE
You can test the functionality of the input() function in its full scope locally on your machine.
For resource optimization reasons, we have limited the maximum program execution time in
Edube to a few seconds. Go to Sandbox, copy-paste the above snippet, run the program, and do
nothing - just wait a few seconds to see what happens. Your program should be stopped
automatically after a short moment. Now open IDLE, and run the same program there - can you
see the difference?
Tip: the above-mentioned feature of the input() function can be used to prompt the user to end
a program. Look at the code below:
name = input("Enter your name: ") print("Hello, " + name + ". Nice to meet
you!") print("\nPress Enter to end the program.") input() print("THE END.")
3. The result of the input() function is a string. You can add strings to each other using the
concatenation (+) operator. Check out this code:
num1 = input("Enter the first number: ") # Enter 12 num2 = input("Enter the
second number: ") # Enter 21 print(num1 + num2) # the program returns 1221
Key takeaways
1. The comparison (or the so-called relational) operators are used to compare values. The table
below illustrates how the comparison operators work, assuming that x = 0, y = 1, and z = 0:
!=
returns True if operands' values are not x != y # True x != z # False
equal, and False otherwise
True if the left operand's value is greater
> than the right operand's value, and False x > y # False y > z # True
otherwise
True if the left operand's value is less than
< the right operand's value, and False x < y # True y < z # False
otherwise
True if the left operand's value is greater
x >= y # False x >= z # True
≥ than or equal to the right operand's value, y >= z # True
and False otherwise
True if the left operand's value is less than
x <= y # True x <= z # True y
≤ or equal to the right operand's value, and <= z # False
False otherwise
2. When you want to execute some code only if a certain condition is met, you can use a
conditional statement:
a single if statement, e.g.:
x = 10 if x > 5: # True print("x > 5") if x > 8: # True print("x > 8")
if x > 10: # False print("x > 10") else: print("else will be executed")
Each if is tested separately. The body of else is executed if the last if is False.
If the condition for if is False, the program checks the conditions of the subsequent
elif blocks - the first elif block that is True is executed. If all the conditions are False,
the else block will be executed.
Exercise 1
Exercise 2
Exercise 3
Exercise 4
x = 10 if x == 10: print(x == 10) if x > 5: print(x > 5) if x < 10: print(x <
10) else: print("else")
Exercise 5
Key takeaways
the while loop executes a statement or a set of statements as long as a specified boolean
condition is true, e.g.:
the for loop executes a set of statements many times; it's used to iterate over a sequence
(e.g., a list, a dictionary, a tuple, or a set - you will learn about them soon) or other
objects that are iterable (e.g., strings). You can use the for loop to iterate over a sequence
of numbers using the built-in range function. Look at the examples below:
2. You can use the break and continue statements to change the flow of a loop:
You use continue to skip the current iteration, and continue with the next iteration, e.g.:
text = "pyxpyxpyx" for letter in text: if letter == "x": continue
print(letter, end="")
3. The while and for loops can also have an else clause in Python. The else clause executes
after the loop finishes its execution as long as it has not been terminated by break, e.g.:
4. The range() function generates a sequence of numbers. It accepts integers and returns range
objects. The syntax of range() looks as follows: range(start, stop, step), where:
Example code:
Create a for loop that counts from 0 to 10, and prints odd numbers to the screen. Use the
skeleton below:
Exercise 2
Create a while loop that counts from 0 to 10, and prints odd numbers to the screen. Use the
skeleton below:
Create a program with a for loop and a break statement. The program should iterate over
characters in an email address, exit the loop when it reaches the @ symbol, and print the part
before @ on one line. Use the skeleton below:
Exercise 4
Create a program with a for loop and a continue statement. The program should iterate over a
string of digits, replace each 0 with x, and print the modified string to the screen. Use the
skeleton below:
Exercise 5
Exercise 6
Exercise 7
and → if both operands are true, the condition is true, e.g., (True and True) is True,
or → if any of the operands are true, the condition is true, e.g., (True or False) is
True,
not → returns false if the result is true, and returns true if the result is false, e.g., not
True is False.
2. You can use bitwise operators to manipulate single bits of data. The following sample data:
will be used to illustrate the meaning of bitwise operators in Python. Analyze the examples
below:
& does a bitwise and, e.g., x & y = 0, which is 0000 0000 in binary,
| does a bitwise or, e.g., x | y = 31, which is 0001 1111 in binary,
˜ does a bitwise not, e.g., ˜ x = 240, which is 1111 0000 in binary,
^ does a bitwise xor, e.g., x ^ y = 31, which is 0001 1111 in binary,
>> does a bitwise right shift, e.g., y >> 1 = 8, which is 0000 1000 in binary,
<< does a bitwise left shift, e.g., y << 3 = , which is 1000 0000 in binary,
Exercise 1
Exercise 2
1. The list is a type of data in Python used to store multiple objects. It is an ordered and
mutable collection of comma-separated items between square brackets, e.g.:
3. Lists can be nested, e.g.: myList = [1, 'a', ["list", 64, [0, 1], False]].
You will learn more about nesting in module 3.1.7 - for the time being, we just want you to be
aware that something like this is possible, too.
Again, you will learn more about this in module 3.1.6 - don't worry. For the time being just try to
experiment with the above code and check how changing it affects the output.
6. The len() function may be used to check the list's length, e.g.:
Exercise 2
Exercise 3
Exercise 4
Key takeaways
1. You can use the sort() method to sort elements of a list, e.g.:
2. There is also a list method called reverse(), which you can use to reverse the list, e.g.:
Exercise 1
What is the output of the following snippet?
Exercise 2
Key takeaways
1. If you have a list l1, then the following assignment: l2 = l1 does not make a copy of the l1
list, but makes the variables l1 and l2 point to one and the same list in memory. For example:
2. If you want to copy a list or part of the list, you can do it by performing slicing:
3. You can use negative indices to perform slices, too. For example:
4. The start and end parameters are optional when performing a slice: list[start:end], e.g.:
6. You can test if some items exist in a list or not using the keywords in and not in, e.g.:
myList = ["A", "B", 1, 2] print("A" in myList) # outputs: True print("C" not
in myList) # outputs: True print(2 not in myList) # outputs: False
Exercise 1
Exercise 2
Exercise 3
Exercise 4
l1 = ["A", "B", "C"] l2 = l1[:] l3 = l2[:] del l1[0] del l2[0] print(l3)
Exercise 5
Insert in or not in instead of ??? so that the code outputs the expected result.
myList = [1, 2, "in", True, "ABC"] print(1 ??? myList) # outputs True
print("A" ??? myList) # outputs True print(3 ??? myList) # outputs True
print(False ??? myList) # outputs False
Key takeaways
1. A function is a block of code that performs a specific task when the function is called
(invoked). You can use functions to make your code reusable, better organized, and more
readable. Functions can have parameters and return values.
built-in functions which are an integral part of Python (such as the print() function).
You can see a complete list of Python built-in functions at
https://docs.python.org/3/library/functions.html.
the ones that come from pre-installed modules (you'll learn about them in Module 5 of
this course)
user-defined functions which are written by users for users - you can write your own
functions and use them freely in your code,
the lambda functions (you'll learn about them in Module 6 of this course.)
3. You can define your own function using the def keyword and the following syntax:
You can define a function which doesn't take any arguments, e.g.:
You can define a function which takes arguments, too, just like the one-parameter function
below:
We'll tell you more about parametrized functions in the next section. Don't worry.
Exercise 1
a) user-defined function
b) built-in function
Exercise 2
What happens when you try to invoke a function before you define it? Example:
Exercise 3
Key takeaways
1. You can pass information to functions by using parameters. Your functions can have as many
parameters as you need.
positional argument passing in which the order of arguments passed matters (Ex. 1),
keyword (named) argument passing in which the order of arguments passed doesn't
matter (Ex. 2),
a mix of positional and keyword argument passing (Ex. 3).
3. You can use the keyword argument passing technique to pre-define a value for a given
argument:
Exercise 1
Exercise 2
Exercise 3
Exercise 4
Key takeaways
1. You can use the return keyword to tell a function to return some value. The return
statement exits the function, e.g.:
Exercise 1
Exercise 2
What is the output of the following snippet?
Exercise 3
Exercise 4
Key takeaways
1. A variable that exists outside a function has a scope inside the function body (Example 1)
unless the function defines a variable of the same name (Example 2, and Example 3), e.g.:
Example 1:
Example 2:
Example 3:
2. A variable that exists inside a function has a scope inside the function body (Example 4), e.g.:
Example 4:
def adding(x): var = 7 return x + var print(adding(4)) # outputs: 11
print(var) # NameError
3. You can use the global keyword followed by a variable name to make the variable's scope
global, e.g.:
var = 2 print(var) # outputs: 2 def retVar(): global var var = 5 return var
print(retVar()) # outputs: 5 print(var) # outputs: 5
Exercise 1
What will happen when you try to run the following code?
Exercise 2
Exercise 3
Exercise 4
Key takeaways
1. A function can call other functions or even itself. When a function calls itself, this situation is
known as recursion, and the function which calls itself and contains a specified termination
condition (i.e., the base case - a condition which doesn't tell the function to make any further
calls to that function) is called a recursive function.
2. You can use recursive functions in Python to write clean, elegant code, and divide it into
smaller, organized chunks. On the other hand, you need to be very careful as it might be easy
to make a mistake and create a function which never terminates. You also need to remember
that recursive calls consume a lot of memory, and therefore may sometimes be inefficient.
When using recursion, you need to take all its advantages and disadvantages into consideration.
The factorial function is a classic example of how the concept of recursion can be put in practice:
Exercise 1
What will happen when you attempt to run the following snippet and why?
Exercise 2
1. Tuples are ordered and unchangeable (immutable) collections of data. They can be thought of
as immutable lists. They are written in round brackets:
myTuple = (1, 2, True, "a string", (3, 4), [5, 6], None) print(myTuple)
myList = [1, 2, True, "a string", (3, 4), [5, 6], None] print(myList)
Each tuple element may be of a different type (i.e., integers, strings, booleans, etc.). What is
more, tuples can contain other tuples or lists (and the other way round).
2. You can create an empty tuple like this:
If you remove the comma, you will tell Python to create a variable, not a tuple:
5. Tuples are immutable, which means you cannot change their elements (you cannot append
tuples, or modify, or remove tuple elements). The following snippet will cause an exception:
myTuple = (1, 2.0, "string", [3, 4], (5, ), True) myTuple[2] = "guitar" # a
TypeError exception will be raised
6. You can loop through a tuple elements (Example 1), check if a specific element is (not)present
in a tuple (Example 2), use the len() function to check how many elements there are in a tuple
(Example 3), or even join/multiply tuples (Example 4):
EXTRA
You can also create a tuple using a Python built-in function called tuple(). This is particularly
useful when you want to convert a certain iterable (e.g., a list, range, string, etc.) to a tuple:
1. Dictionaries are unordered*, changeable (mutable), and indexed collections of data. (*In
Python 3.6x dictionaries have become ordered by default.
Each dictionary is a set of key : value pairs. You can create it by using the following syntax:
2. If you want to access a dictionary item, you can do so by making a reference to its key inside a
pair of square brackets (ex. 1) or by using the get() method (ex. 2):
3. If you want to change the value associated with a specific key, you can do so by referring to
the item's key name in the following way:
4. To add or remove a key (and the associated value), use the following syntax:
You can also insert an item to a dictionary by using the update() method, and remove the last
element by using the popitem() method, e.g.:
5. You can use the for loop to loop through a dictionary, e.g.:
polEngDict = { "zamek" : "castle", "woda" : "water", "gleba" : "soil" } for
item in polEngDict: print(item) # outputs: zamek # woda # gleba
6. If you want to loop through a dictionary's keys and values, you can use the items() method,
e.g.:
7. To check if a given key exists in a dictionary, you can use the in keyword:
8. You can use the del keyword to remove a specific item, or delete a dictionary. To remove all
the dictionary's items, you need to use the clear() method:
Exercise 1
Exercise 2
What is the output of the following snippet?
Exercise 3
Complete the code to correctly use the count() method to find the number of duplicates of 2 in
the following tuple.
Exercise 4
Write a program that will "glue" the two dictionaries (d1 and d2) together and create a new one
(d3).
Exercise 5
Exercise 6
Exercise 7
colors = { "white" : (255, 255, 255), "grey" : (128, 128, 128), "red" : (255,
0, 0), "green" : (0, 128, 0) } for col, rgb in colors.items(): print(col,
":", rgb)