TPG Flashcards
What is Python?
Python is a general-purpose programming language created by Guido Van Rossum. Python is most praised for its elegant syntax and readable code, if you are just beginning your programming career Python suits you best.
With Python you can do everything from
GUI (graphical user interface ) development,
Web application,
System administration tasks,
Financial calculation,
Data Analysis,
Visualization
and list goes on…
What doeas it mean that Python is interpreted language?
Język interpretowany – język programowania, w którym interpreter analizuje program linia po linii. Przeciwieństwem języków interpretowanych są języki implementowane w postaci kompilatora (kompilator najpierw kompiluje cały program, a następnie zaczyna działać). Języki interpretowane są nieco wolniejsze od języków kompilowanych, lecz prostsze do napisania (mniej rzeczy o które trzeba się martwić podczas pisaniaskodu)
Python is interpreted language, when you run python program an interpreter will parse python program line by line basis, as compared to compiled languages like C or C++, where compiler first compiles the program and then start running.
Now you may ask, so what’s the difference??
The difference is that interpreted languages are a little bit slow as compared to compiled languages. Yes, you will definitely get some performance benefits if you write your code in compiled languages like C or C++.
But writing codes in such languages is a daunting task for a beginner. Also in such languages, you need to write even most basic functions like calculate the length of the array, split the string etc. For more advanced tasks sometimes you need to create your own data structures to encapsulate data in the program. So in C/C++ before you actually start solving your business problem you need to take care of all minor details. This is where Python comes. In Python, you don’t need to define any data structure, no need to define small utility functions because Python has everything to get you started.
Moreover, Python has hundreds of libraries available at https://pypi.python.org/ which you can use in your project without reinventing the wheel.
What does it mean that Python is Dynamically Typed ?
Python sam automatycznie rozpoznaje typ zmiennych na podstawie kodu.
Python doesn’t require you to define variable data type ahead of time. Python automatically infers the data type of the variable based on the type of value it contains.
For e.g:
myvar = “Hello Python”
The above line of code assigns string “Hello Python” to the variable myvar, so the type of myvar is string.
Note that unlike languages like C, C++ and Java, in Python you do not need to end a statement with a semicolon (;).
Suppose, a little bit later in the program we assign variable myvar a value of 1 i.e
myvar = 1
Now myvar variable is of type int.
What does it mean that Python is strongly typed?
Nie dokonuje on automatycznej konwersji kodu.
If you have programmed in PHP or javascript. You may have noticed that they both convert data of one type to another automatically.
For e.g:
In JavaScript
1 + “2”
will be ‘12’
Here, before addition (+) is carried out, 1 will be converted to a string and concatenated to “2”, which results in ‘12’, which is a string. However, In Python, such automatic conversions are not allowed, so
1 + “2”
will produce an error.
Which code will be longer, the one written in Python or Java?
Programs written in Python are usually 1/3 or 1/5 of the Java code. It means we can write less code in Python to achieve the same thing as in Java.
Who uses Python?
Python is used by many large organizations like Google, NASA, Quora, HortonWorks and many others.
Okay, what I can start building in Python?
Pretty much anything you want. For e.g:
GUI applications.
Web apps.
Scrape data from websites.
Analyse Data.
System administration utilities.
Game Development.
Data Science
and many more …
Do I have to install Python on my PC?
Mac also comes with python 2 and python 3 installed (if not see this link for instructions), but this is not the case with windows. Similarly, most Linux distribution for e.g Ubuntu 14.04 comes with python 2 and 3 installed, bu you have to install Python on Windows
How to install Python on Windows/Ubuntu/Mac?
To install python you need to download python binary from https://www.python.org/downloads/, specifically we will be using python 3.4.3 which you can download from here. While installing remember to check “Add Python.exe to path”
If you are using Ubuntu 14.04 which already comes with python 2 and python 3, you need to enter python3 instead of just python to enter python 3 shell. Also you will need a text editor to write Python programs, you can use text editor like notepad. If you want to use full-fledged text editor then use notepad++ or sublime text. Download and install text editor of you choice.
On Mac is good to check Python version by typing in terminal: ~ % python3 –version
Then to install Python 3 with the Official Installer from: https://www.python.org/downloads/
How to run python programs?
You can run python programs in two ways, first by typing commands directly in python shell:
Np.
print(“Hello World”)
> Hello World
or run program stored in a file. But most of the time you want to run programs stored in a file.
Np. do terminala wpisujemy:
python hello.py
W ten sposób wgrywamy plik z zapisanym tam uprzednio programem.
How many arguments does print() function have?
as many arguments as you provide it with (as many as editor allow). When two or more arguments are passed, the print() function displays each argument separated by space.
Np.
print(“Hello World”)
> Hello World
print(“Hello”, “World”)
> Hello World
Which command is used to change directory?
cd ‘od change directory’
Open terminal and change current working directory to C:\Users\YourUserName\Documents using cd command
What to do when you want to know more about some method or functions?
Type help() into the terminal.
Sooner or later while using python you will come across a situation when you want to know more about some method or functions. To help you Python has help() function, here is how to use it.
Syntax:
To find information about class: help(class_name)
To find more about method belong to class: help(class_name.method_name)
Now suppose you want to know arguments required for index() method of str class, to find out you need to type the following command in the python shell: help(str.index)
What are variables in Python and what are the rules of naming them?
Variables are named locations that are used to store references to the object stored in memory. The names we choose for variables and functions are commonly known as Identifiers. In Python, Identifiers must obey the following rules.
- All identifiers must start with a letter or underscore (_), you can’t use digits. For e.g: my_var is a valid identifier but 1digit is not.
- Identifiers can contain letters, digits and underscores (_). For e.g: error_404, _save are valid identifiers but $name$ ($ is not allowed) and #age (# is not allowed) are not.
- They can be of any length.
- Identifiers can’t be a keyword. Keywords are reserved words that Python uses for special purposes). The following are keywords in Python 3.
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
pass else import assert
break except in raise
Values or literals?
Values = literals
They are basic things that programs work with. For e.g: 1, 11, 3.14, “hello” are all values.
They are also commonly known as literals.
They can be of different types for e.g 1, 11 are of type int, 3.14 is a float and “hello” is a string.
What is a object in Python?
Remember that in Python everything is object even basic data types like int, float, string,
How to assign value to a variable?
To assign value to a variable equal sign (=) is used. The = sign is also known as the assignment operator.
Should I declare types of variables while using Python?
In Python, you don’t need to declare types of variables ahead of time. The interpreter automatically detects the type of the variable by the data it contains.
Show some examples of variable declaration
x = 100 # x is integer
pi = 3.14 # pi is float
sentence = “python is great” # sentence is string
a = b = c = 100 # this statement assign 100 to c, b and a.
What the variable stores?
When a value is assigned to a variable, the variable doesn’t store the value itself. Instead, the variable only stores a reference (address) of the object where it is stored in the memory.
Therefore, in the x = 100, the variable x stores a reference (or address) to the 100 ( an int object ). The variable x doesn’t store the object 100 itself.
Comments
Comments are notes which describe the purpose of the program or how the program works. Comments are not programming statements that Python interpreter executes while running the program. Comments are also used to write program documentation. In Python, any line that begins with a pound sign (#) is considered a comment.
e.g:
#This program prints “hello world”
print(“hello world”)
We can also write comments at the end of a statement:
print(“hello world”) # display “hello world”
What are end-line comments?
Comments that appear in this form:
print(“hello world”) # display “hello world”
simultaneous assignment
The simultaneous assignment or multiple assignment allows us to assign values to multiple variables at once. The syntax of simultaneous assignment is as follows:
var1, var2, …, varn = exp1, exp2, …, expn
e.g:
a, b = 10, 20
print(a)
> 10
print(b)
>20
Simultaneous assignments is quite helpful when you want to swap the values of two variables.
e.g:
x = 1 # initial value of x is 1
y = 2 # initial value of y is 2
y, x = x, y # assign y value to x and x value to y
print(x) # final value of x is 2
print(y) # final value of y is 1
> 2
1
Name Python data types
- Numbers
- String
- List
- Tuple
- Dictionary
- Boolean
List values in Python, which are considered as false
Boolen False
0 - zero , 0.0
[] - empty list ,
() - empty tuple ,
{} - empty dictionary ,
‘ ‘ - empty string
None
How to receive input from the console?
The input() function is used to receive input from the console.
The input() function accepts an optional string argument called prompt and returns a string.
Note that the input() function always returns a string even if you entered a number. To convert it to an integer you can use int() or eval() functions.
eval()
Python’s eval() allows you to evaluate (parse, compile, evaluate and return) arbitrary Python expressions from a string-based or compiled-code-based input.
e.g.
»> eval(“2 ** 8”)
256
Python modules
Python organizes codes using modules. Python comes with many built-in modules ready to use for
e.g
there is a ‘math’ module for mathematical related functions,
‘re’ module for regular expression,
‘os’ module for operating system related functions and so on.
How to import module?
To use a module we first import it using the import statement. Its syntax is as follows:
import module_name
We can also import multiple modules using the following syntax:
import module_name_1, module_name_2
Regular expression
A Regular Expression (RegEx) is a sequence of characters that defines a search pattern. For example:
^a…s$
The above defines a RegEx pattern. The pattern is: any five letter string starting with a and ending with s
Python has a module named re to work with RegEx. Here’s an example:
e.g
import re
pattern = ‘^a…s$’
test_string = ‘abyss’
result = re.match(pattern, test_string)
if result:
print(“Search successful.”)
else:
print(“Search unsuccessful.”)
How to access objects in a module?
e.g
import math, os
print(math.pi)
print(math.e)
print(os.getcwd())
In this listing, the first line imports all functions, classes, variables and constants defined in the math and os module. To access objects defined in a module we first write the module name followed by a dot (.) and then the name of the object itself. (i.e class or function or constant or variable). In the above example, we are accessing two common mathematical constants pi and e from the math math. In the next line, we are calling the getcwd() function of the os module which prints the current working directory.
What numerical types are supported in Python?
Python supports 3 different numerical types.
1) int - for integer values like 1, 100, 2255, -999999, 0, 12345678.
2) float - for floating-point values like 2.3, 3.14, 2.71, -11.0.
3) complex - for complex numbers like 3+2j, -2+2.3j, 10j, 4.5+3.14j.
Complex number
As you may know complex number consists of two parts real and imaginary, and is denoted by j. You can define complex number like this:
> > > x = 2 + 3j # where 2 is the real part and 3 is imaginary
How to determine variable type?
Python has type() inbuilt function which is use to determine the type of the variable.
e.g
x = 12
type(x)
> <class ‘int’>
Name Python operators
Name Meaning Example Rresult
+ Addition. 15+20. >35
- Subtraction. 24-3. >21.0
* Multiplication 15*4 >60
/ Float Division. 4/5. >0.8
// Integer Division. 4//5. >0
** Exponentiation. 4**2 >16
% Remainder. 27%4. >3
Integer division
Integer Division (//) : The // perform integer division i.e it will truncate the decimal part of the answer and return only integer.
Float division
Float Division (/) : The / operator divides and return result as floating point number means it will always return fractional part. e.g
3/2
>1.5
Exponentiation operator
Exponentiation Operator (**) : This operator helps to compute a^b (a raise to the power of b). Let’s take an example:
e.g
2 ** 3 # is same as 2 * 2 * 2
> 8
Remainder operator
Remainder operator (%, reszta) : The % operator also known as remainder or modulus operator. This operator return remainder after division. For e.g:
> 7 % 2
1
Operator precedence
Pierszeństwo operatorów w Pythonie:
1.Parentheses (grouping) ()
2. Function call f(args…)
3.Slicing e.g list, string x[index:index]
4. Subscription x[index]
5. Atribute reference. x.attribute
6. ** Exponentiation (potęga)
7 ~ NOT, also known as bitwise not - inverts all the bits ~x
8. Positive, negative +x -x
9. Multiplication, division, remainder
* / %
10. Addition, subtraction + -
- Bitwise shifts e.g
« Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off
» Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off - Bitwise AND &
Sets each bit to 1 if both bits are 1 - Bitwise XOR ^
Sets each bit to 1 if only one of two bits is 1 - Bitwise OR |
Sets each bit to 1 if one of two bits is 1 - Comparision, membership identity
in, not in, is, is not, <, <=, >, >=, <>, !=, == - Boolean NOT not x
- Boolean AND and
- Boolean OR or
- Lambda expression lambda
If operators have the same precedence then they will be evaluated from left to right, i.e addition will be applied first then subtraction
e.g
3 + 4 - 2
> 5
The only exception to this rule is assignment operator (=) which occur from right to left.
e.g
a = b = c
Augmented Assignment Operators
+= , -=, = , /=, //=, %=, **=
These operators allows you write shortcut assignment statements. For e.g:
count = 1
count += 1
print(count)
> 2
Is the same as:
count = 1
count = count + 1
print(count)
> 2
+=
Addition assignment
Example:
x += 4
Same as:
x = x + 4
-=
Subtraction assignment
Example:
x -= 2
Same as:
x = x - 2
*=
Multiplication assignment
Example:
x *= 5
Same as:
x = 5 * x
/=
Division assignment
Example:
x /= 5
Same as:
x = x / 5
//=
Integer division assignment
Example:
x //= 5
Same as:
x = x // 5
//=
Integer division assignment
Example:
x //= 5
Same as:
x = x // 5
%=
Remainder assignment
Example:
x %= 5
Same as:
x = x % 5
**=
Exponent assignment
Example:
x **= 5
Same as:
x = x ** 5
Strings
Strings in python are contiguous series of characters delimited by single or double quotes. Python doesn’t have any separate data type for characters so they are represented as a single character string.
How to create strings?
name = “tom” # a string
mychar = ‘a’ # a character
You can also use the following syntax to create strings.
name1 = str() # this will create empty string object
name2 = str(“newstring”) # string object containing ‘newstring’
id()
Every object in python is stored somewhere in memory. We can use id() to get that memory address.
e.g
str1 = “welcome”
str2 = “welcome”
id(str1)
>78965411
id(str2)
>78965411
As both str1 and str2 points to the same memory location, hence they both point to the same object.
Are strings mutable?
Strings in Python are Immutable.
What this means to you is that once a string is created it can’t be modified. Let’s take an example to illustrate this point.
e.g
str1 = “welcome”
str2 = “welcome”
id(str1)
>78965411
id(str2)
>78965411
Let’s try to modify str1 object by adding a new string to it.
str1 += “ mike”
print(str1)
>welcome mike
id(str1)
>78965579
As you can see now str1 points to totally different memory location, this proves the point that concatenation doesn’t modify the original string object instead it creates a new string object.
Concatanation
String concatenation is the operation of joining character strings end-to-end.
For example, the concatenation of “snow” and “ball” is “snowball”
Are int type mutable?
Number (i.e int type) is, like string, immutable.
e.g
int1 = 1
int2 = 1
print(id(int1), id(int2))
> 9316800, 9316800
int2 += 3
print(int2)
print(id(int1), id(int2))
> 4
9316800, 9316896
Could I access string characters?
Yes.
String index starts from 0, so to access the first character in the string type:
name = “tom”
print(name[0])
print(name[1])
>t
o
Operator for string contatanation
+
e.g
s = “tom and “ + “jerry”
print(s)
> tom and jerry
Operator for string repetition
*
e.g
s = “spamming is bad “ * 3
print(s)
> ‘spamming is bad spamming is bad spamming is bad ‘
Operator for string slicing
[]
e.g
s = “Welcome”
s[1:3]
> el
Cięcie następuje przed [1] i przed [3]
Some more slicing examples.
s = “Welcome”
s[:6]
> ‘Welcom’
s[4:]
>’ome’
s[1:-1]
>’elcom’
The start index and end index are optional. If omitted then the default value of start index is 0 and that of end is the last index of the string.
ord()
function returns the ASCII code of the character
print(ord(‘a’))
> 97
chr()
chr() - function returns character represented by a ASCII number.
print(chr(97))
> a
Name 3 string function in Python
len() - returns length of the string
max() - returns character having highest ASCII value
min() - returns character having lowest ASCII value
e.g
print(len(“jagoda”))
print(max(“jagoda”))
print(min(“jagoda”))
<6
o
a
ASCII
ASCII (czyt. aski, skrót od ang. American Standard Code for Information Interchange) – siedmiobitowy system kodowania znaków.
Jest używany we współczesnych komputerach oraz sieciach komputerowych, a także innych urządzeniach wyposażonych w mikroprocesor.
Przyporządkowuje liczbom z zakresu 0−127:
- litery alfabetu łacińskiego języka angielskiego,
- cyfry,
- znaki przestankowe
i inne symbole oraz polecenia sterujące.
Na przykład litera „a” jest kodowana jako liczba 97, a znak spacji jest kodowany jako 32.
membership operator
in, not in operators
e.g
s1 = “Welcome”
“come” in s1
>True
“come” not in s1
>False
»>
What is used to compare strings with each other?
Python compares string lexicographically i.e using ASCII value of the characters.
You can use ( > , < , <= , <= , == , != ) to compare two strings.
Suppose you have str1 as “Mary” and str2 as “Mac”. The first two characters from str1 and str2 ( M and M ) are compared. As they are equal, the second two characters are compared. Because they are also equal, the third two characters (r and c ) are compared. And because r has greater ASCII value than c, str1 is greater than str2.
e.g
print(“Mac” == “Mary”)
print(“Mac” < “Mary”)
print(ord(“c”)), print(ord(“r”))
> False
True
99, 114
By default, print() function prints string with a newline, we change this behavior by passing named keyword argument called ____
end
print(“my string”, end=” “)
> my string
print(“my string”, end=”foo”)
>my stringfoo
print(“my string”)
print(“my string”, end=”foo”)
> my string
my stringfoo
print(“my string”, end=””)
print(“my string”, end=”foo”)
> my stringmy stringfoo
Can I use for loop on strings?
String is a sequence type and also iterable using for loop
e.g
word = “hello”
for letter in word:
print(letter)
>h
e
l
l
o
Print na końcu automatycznie dodaje /n. Możemy go jednak zastąpić pustym stringiem
e.g
word = “hello”
for letter in word:
print(letter, end=””)
> hello
Testing strings: isalnum()
Returns True if string is alphanumeric
e.g
s = “welcome to python”
s.isalnum()
> False (bo jest spacja)
txt = “Company12”
x = txt.isalnum()
print(x)
>True
txt = “Company”
x = txt.isalnum()
print(x)
> True
txt = “12”
x = txt.isalnum()
print(x)
>True
Testing strings: isalpha()
Returns True if string contains only alphabets
e.g
s = “welcome”
s.isalpha()
> True
s = “welcome to python”
s.isalpha()
> False
Testing strings: isdigit()
Returns True if string contains only digits
e.g
“2012”.isdigit()
>True
Testing strings: isidentifier()
Return True is string is valid identifier
A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces
Testing strings: islower()
Returns True if string is in lowercase
e.g
s = “welcome’’
s.islower()
>True
Testing strings: isupper()
Returns True if string is in uppercase
e.g
“WELCOME”.isupper()
>True
Testing strings: isspace()
Returns True if string contains only whitespace
e.g
“ \t”.isspace()
> True
Searching for Substrings: endswith(s1: str):
bool
Returns True if strings ends with substring s1
e.g
s = “welcome to python”
print(s.endswith(“thon”))
> True
Searching for Substrings:
startswith(s1: str):
bool
Returns True if strings starts with substring s1
e.g
s = “welcome to python”
print(s.startswith(“good”))
>False
Searching for Substrings:
count(substring):
int
Returns number of occurrences of substring in the string
e.g
s = “welcome to python”
print(s.count(“o”))
>3
Searching for Substrings:
find(s1):
int
Returns lowest index from where s1 starts in the string, if string not found returns -1
(znajduje indeks od którego zaczyna się substring o któy pytamy, jeśli nic nie znajdzie drukuje -1)
e.g
s = “welcome to python”
print(s.find(“come”))
> 3
print(s.find(“become”))
> -1
Searching for Substrings:
rfind(s1):
int
Returns highest index from where s1 starts in the string, if string not found returns -1
(znajduje ostatni index w którym występuje litera lub pierwszy indeks w którym wystepuje dany substring)
e.g
s = “welcometopython”
print(s.rfind(“o”))
print(s.rfind(“top”))
> 13
7
Converting Strings:
capitalize():
str
Returns a copy of this string with only the first character capitalized.
e.g
s = “string in python”
s1 = s.capitalize()
print(s1)
> String in python
Converting Strings:
lower():
str
Return string by converting every character to lowercase
e.g
s = “This Is Test”
s1 = s.lower()
print(s1)
> this is test
Converting Strings:
upper():
str
Return string by converting every character to uppercase
e.g
s = “This Is Test”
s1 = s.upper()
print(s1)
> THIS IS TEST
Converting Strings:
title():
str
This function return string by capitalizing first letter of every word in the string
e.g
s = “this is test”
s1 = s.title()
print(s1)
> This Is Test
Converting Strings:
swapcase():
str
Return a string in which the lowercase letter is converted to uppercase and uppercase to lowercase
e.g
s = “jAgOdA”
s1 = s.swapcase()
print(s1)
> JaGoDa
Converting Strings:
replace(old\, new):
str
This function returns new string by replacing the occurrence of old string with new string
e.g
s = “Jagoda”
s1 = s.replace(“a”, “e”)
print(s1)
> Jegode
How to create a list in Python?
list1 = [1, 2, 3]
other way list1 = list([1,2,3])
empty list:
list1 = []
list1 = list()
Are lists mutable?
Yes, lists are mutable.
How to acces list elements?
list[1]
access second element in the list
Common List Operations:
x in s
True if element x is in sequence s, False otherwise
Common List Operations:
x not in s
True if element x is not in sequence s, False otherwise
Common List Operations:
s1 + s2
Concatenates two sequences s1 and s2
Common List Operations:
n * s
s * n
n copies of sequence s concatenated
Common List Operations:
s [i]
access ith element in sequence s.
Common List Operations:
len(s)
Length (number of elements) of list
Common List Operations:
min(s)
Smallest element in sequence s.
Common List Operations:
max(s)
Largest element in sequence s.
Common List Operations:
sum(s)
Sum of all numbers in sequence s.
Common List Operations:
for loop
Przechodzi elementy od lewej do prawej w pętli for.
Slice operator ([start:end])
Slice operator ([start:end]) allows to fetch sublist from the list. It works similar to string.
e.g
list = [11,33,44,66,788,1]
list[0:5] # this will return list starting from index 0 to index 4
>[11,33,44,66,788]
list[:3]
>[11,33,44]
list[2:]
>[44,66,788,1]
The ___ operator joins the two list.
+
The ___ operator replicates the elements in the list.
*
The __ operator is used to determine whether the elements exists in the list. On success it returns True on failure it returns False.
in
List is a sequence and also iterable - you can use ___ to traverse through all the elements of the list.
for i in
e.g
list = [1,2,3,4,5]
for i in list:
print(i, end=” “)
1 2 3 4 5
Common list methods:
append
append(x:object):None
Adds an element x to the end of the list and returns None.
e.g
list1 = [2, 3, 4, 1, 32, 4]
list1.append(19)
print(list1)
>[2, 3, 4, 1, 32, 4, 19]
Common list methods:
count
count(x:object):int
Returns the number of times element x appears in the list.
e.g
list1 = [2, 3, 4, 1, 32, 4]
list1.count(4) # Return the count for number 4
>2
Common list methods:
extend
extend(l:list):None
Appends all the elements in l to the list and returns None.
e.g
list1 = [2, 3, 4, 1, 32, 4]
list2 = [99, 54]
list1.extend(list2)
print(list1)
> [2, 3, 4, 1, 32, 4, 19, 99, 54]
Common list methods:
index
index(x: object):int
Returns the index of the first occurrence of element x in the list
e.g
list1 = [2, 3, 4, 1, 32, 4]
list1.index(4) # Return the index of number 4
> 2
Common list methods:
insert
insert(index: int, x: object):None
Inserts an element x at a given index. Note that the first element in the list has index 0 and returns None.
e.g
list1 = [2, 3, 4, 1, 32, 4]
list1.insert(1, 25) # Insert 25 at position index 1
print(list1)
> [2, 25, 3, 4, 1, 32, 4, 19, 99, 54]
Common list methods:
remove
remove(x:object):None
Removes the first occurrence of element x from the list and returns None
e.g
list1 = [2, 3, 4, 1, 32, 4]
list1.remove(32) # Remove number 32
print(list1)
>[2, 25, 4, 1, 4, 19, 99]
What ‘returns None’ mean?
that function ends succesfully
Common list methods:
reverse
reverse():None
Reverse the list and returns None
e.g
list1 = [2, 3, 4, 1, 32, 4]
list1.reverse() # Reverse the list
print(list1)
>[4, 32, 1, 4, 3, 2]
Common list methods:
sort
sort(): None
Sorts the elements in the list in ascending order and returns None.
e.g
list1 = [2, 3, 4, 1, 32, 4]
»> list1.sort() # Sort the list
print(list1)
>[1, 2, 4, 4, 19, 25, 99]
Common list methods:
pop
pop(i): object
Removes the element at the given position and returns it. The parameter i is optional. If it is not specified, pop() removes and returns the last element in the list.
e.g
list1 = [2, 25, 4, 1, 32, 4, 19, 99, 54]
list1.pop()
print(list1)
[2, 25, 4, 1, 32, 4, 19, 99]
List comprehension
List comprehension provides a concise way to create list. It consists of square brackets containing expression followed by for clause then zero or more for or if clauses.
> > > list1 = [ x for x in range(10) ]
list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]list2 = [ x + 1 for x in range(10) ]
list2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]list3 = [ x for x in range(10) if x % 2 == 0 ]
list3
[0, 2, 4, 6, 8]list4 = [ x *2 for x in range(10) if x % 2 == 0 ]
[0, 4, 8, 12, 16]
Dictionary
Dictionary is a python data type that is used to store key-value pairs. It enables you to quickly retrieve, add, remove, modify, values using a key. Dictionary is very similar to what we call associative array or hash on other languages.
e.g
friends = {
‘tom’ : ‘111-222-333’,
‘jerry’ : ‘666-33-111’
}
here friends is a dictionary with two items. One point to note that key must be of a hashable type, but the value can be of any type. Each key in the dictionary must be unique.
How to create mepty dictionary?
> > > dict_emp = {} # this will create an empty dictionary
Alternatively:
dict_eml = dict()
How to get an item from the dictionary?
dictionary_name[‘key’]
e.g
friends = {
‘tom’ : ‘111-222-333’,
‘jerry’ : ‘666-33-111’
}
friends[‘tom’]
> ‘111-222-333’
If the key exists in the dictionary, the value will be returned, otherwise a KeyError exception will be thrown.
How to delete items from the dictionary?
dictionary_name[‘newkey’] = ‘newvalue’
e.g
friends = {
‘tom’ : ‘111-222-333’,
‘jerry’ : ‘666-33-111’
}
del friends[‘bob’]
friends
> {‘tom’: ‘111-222-333’, ‘jerry’: ‘666-33-111’}
If the key is found the item will be deleted, otherwise a KeyError exception will be thrown.
How to use for loop to traverse elements in the dictionary?
friends = {
‘tom’ : ‘111-222-333’,
‘jerry’ : ‘666-33-111’
}
for key in friends:
print(key, “:”, friends[key])
> tom : 111-222-333
jerry : 666-33-111
How to find the length of the dictionary?
You can use the len() function to find the length of the dictionary.
friends = {
‘tom’ : ‘111-222-333’,
‘jerry’ : ‘666-33-111’
}
len(friends)
>2
How to check whether key exists in the dictionary?
in and not in operators to check whether key exists in the dictionary.
friends = {
‘tom’ : ‘111-222-333’,
‘jerry’ : ‘666-33-111’
}
‘tom’ in friends
> True
‘tom’ not in friends
> False
How to test whether two dictionaries contains the same items ?
The == and != operators tells whether dictionary contains the same items or not.
d1 = {“mike”:41, “bob”:3}
d2 = {“bob”:3, “mike”:41}
d1 == d2
> True
d1 != d2
> False
Dictionary methods:
popitem()
Returns randomly selected item from the dictionary and also remove the selected item.
e.g
friends = {
‘tom’: ‘111-222-333’,
‘bob’: ‘888-999-666’,
‘jerry’: ‘666-33-111’
}
friends.popitem()
>(‘tom’, ‘111-222-333’)
Dictionary methods:
clear()
Delete everything from a dictionary
e.g
friends = {
‘tom’: ‘111-222-333’,
‘bob’: ‘888-999-666’,
‘jerry’: ‘666-33-111’
}
friends.clear()
friends
> {}
Dictionary methods:
keys()
Return keys in the dictionary as tuples
e.g
friends = {
‘tom’: ‘111-222-333’,
‘bob’: ‘888-999-666’,
‘jerry’: ‘666-33-111’
}
friends.keys()
> dict_keys([‘tom’, ‘bob’, ‘jerry’])
Dictionary methods:
get(key)
Return value of key, if key is not found it returns None, instead of throwing KeyError exception
e.g
friends = {
‘tom’: ‘111-222-333’,
‘bob’: ‘888-999-666’,
‘jerry’: ‘666-33-111’
}
friends.get(‘tom’)
>’111-222-333’
Dictionary methods:
pop(key)
Remove the item from the dictionary, if the key is not found KeyError will be thrown
e.g
friends = {
‘tom’: ‘111-222-333’,
‘bob’: ‘888-999-666’,
‘jerry’: ‘666-33-111’
}
friends.pop(‘bob’)
friends
> {‘tom’: ‘111-222-333’, ‘jerry’: ‘666-33-111’}
Relational operators
Relational operators allows us to compare two objects.
Relational operators
<=
smaller than or equal to
Relational operators
<=
smaller than or equal to
Relational operators
<, >
smaller than
greater than
Relational operators
>=
greater than or equal to
Relational operators
equal to
Relational operators
!=
not equal to
Example of statement with boolean-expression
if boolean-expression:
#statements
else:
#statements
e.g
i = 10
if i % 2 == 0:
print(“Number is even”)
else:
print(“Number is odd”)
Example of nested if statement
today = “holiday”
bank_balance = 25000
if today == “holiday”:
if bank_balance > 20000:
print(“Go for shopping”)
else:
print(“Watch TV”)
else:
print(“normal working day)
Syntax for def
arg = argument/parameter
def function_name(arg1, arg2, arg3, …. argN):
#statement inside function
e.g
def myfunc():
pass
Example of a function that calculates the sum of all the numbers starting from start to end:
def sum(start, end)
result=0
for i in range(start, end+1)
result = result +1
s = sum(10, 50)
print(s)
> 1230
In python, if you do not explicitly return value from a function, then a special value of _____ is always returned.
None
e.g
def test(): # test function with only one statement
i = 100
print(test()
> None
As you can see, the test() function doesn’t explicitly return any value, so None is returned.
Global variables
Global variables: Variables that are not bound to any function , but can be accessed inside as well as outside the function are called global variables.
e.g
global_var = 12
def func():
local_var = 100
print(global_var)
you can access global variables inside function
Local variables
Local variables: Variables which are declared inside a function are called local variables.
e.g
xy = 100
def cool():
xy = 200
print(xy)
cool()
> 200
print(xy)
> 100
W przypadku gdy mamy globalną i lokalna zmienną o takiej samej nazwie i wywołujemy funkcję zawierającą tę lokalną zmienną, to lokalna zmienna bedzie miała pierwszeństwo i nie bedziemy mogli wywołać globalnej zmiennej o tej samej nazwie wewnątrz tej funkcji.
How to convert local variable into global variable?
You can bind local variable in the global scope by using the global keyword followed by the name of variable
e.g
t = 1
def increment():
global t
t = t + 1
print(t)
# now t inside the function is same as t outside the function
In fact there is no need to declare global variables outside the function. You can declare them global inside the function.
e.g
def foo():
global x
x = 100
How to specify default values of argument?
To specify default values of argument, you just need to assign a value using assignment operator.
e.g
def func(i, j = 100):
print(i, j)
Above function has two parameter i and j. The parameter j has a default value of 100, it means that we can omit value of j while calling the function.
i and j are positional argument
Keyword arguments
Keyword arguments allows you to pass each arguments using name value pairs like this name=value. Let’s take an example:
e.g
def named_args(name, greeting):
print(greeting + “ “ + name )
named_args(name=’jim’, greeting=’Hello’)
> Hello jim
Example of mixing positional and keyword arguments
def my_func(a, b, c):
print(a, b, c)
my_func(12, 13, 14)
> 12, 13, 14
my_func(12, c=14, b=13)
> 12, 13, 14
How to return multiple values from the function?
We can return multiple values from function using the return statement by separating them with a comma (,). Multiple values are returned as tuples.
e.g
def bigger(a, b):
if a > b:
return a, b
else:
return b, a
How many loop types of loop Python has?
Python has only two loops:
for loop
while loop
All the statements inside for and while loop must be indented to the same number of spaces. Otherwise, SyntaxError will be thrown.
The for loop Syntax:
for i in iterable_object:
# do something
e.g.
my_list = [1,2,3,4]
for i in my_list:
print(i)
> 1
2
3
4
range(a, b)
for i in range(1, 10):
print(i)
> 1
2
3
4
5
6
7
8
9
We receive the same output, when we type:
for i in range(10):
… print(i)
> 0
1
2
3
4
5
6
7
8
9
range(a, b, c)
The range(a, b) function has an optional third parameter to specify the step size.
e.g
for i in range(1, 20, 2):
print(i)
> 1
3
5
7
9
11
13
15
17
19
The while loop Syntax:
while condition:
# do something
e.g
count = 0
while count < 10:
print(count)
count += 1
> 0
1
2
3
4
5
6
7
8
9
The while loop Syntax:
while condition:
# do something
e.g
count = 0
while count < 10:
print(count)
count += 1
> 0
1
2
3
4
5
6
7
8
9