Udacity Python Course
Udacity Python Course
Print : A BUILT IN FUNCTION that displays input values as a text in the output.
Arithmetic operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Mod (the remainder after dividing)
** Exponentiation (note that ^ does not do this operation, as you might
have seen in other languages)
// Divides and rounds down to the nearest integer
For more operators:
https://www.programiz.com/python-programming/operators
Strings
Strings in Python are shown as the variable type str . You can define a string with
either double quotes " or single quotes ' . If the string you are creating actually has
one of these two values in it, then you need to be careful to assure your code
doesn't give an error.
>>> my_string = 'this is a string!'
>>> my_string2 = "this is also a string!!!"
You can also include a \ in your string to be able to include one of these quotes:
>>> this_string = 'Simon\'s skateboard is in the garage.'
>>> print(this_string)
Simon's skateboard is in the garage.
If we don't use this, notice we get the following error:
HelloThere
Hello There
>>> print(first_word * 5)
HelloHelloHelloHelloHello
>>> print(len(first_word))
5
Unlike the other data types you have seen so far, you can also index into strings, but
you will see more on this soon! For now, here is a small example. Notice Python
uses 0 indexing - we will discuss this later in this lesson in detail.
>>> first_word[0]
H
>>> first_word[1]
e
The len() function
len() is a built-in Python function that returns the length of an object, like a string.
The length of a string is the number of characters in the string. This will always be
an integer.
There is an example above, but here's another one:
print(len("ababa") / len("ab"))
2.5
You know what the data types are for len("ababa") and len("ab"). Notice the data
type of their resulting quotient here.
String Methods
In this video you were introduced to methods. Methods are like some of
the functions you have already seen:
1. len ("this")
2. type (12)
3. print ("Hello world")
These three above are functions - notice they use parentheses, and accept one or
more arguments. Functions will be studied in much more detail in a later lesson!
A method in Python behaves similarly to a function. Methods actually are functions
that are called using dot notation. For example, lower() is a string method that can be
used like this, on a string called "sample string": sample_string.lower() .
Methods are specific to the data type for a particular variable. So there are some
built-in methods that are available for all strings, different methods that are
available for all integers, etc.
Below is an image that shows some methods that are possible with any string.
Each of these methods accepts the string itself as the first argument of the method.
However, they also could receive additional arguments, that are passed inside the
parentheses. Let's look at the output for a few examples.
>>> my_string.islower()
True
>>> my_string.count('a')
2
>>> my_string.find('a')
3
You can see that the count and find methods both take another argument. However,
the .islower() method does not accept another argument.
No professional has all the methods memorized, which is why understanding how
to use documentation and find answers is so important. Gaining a strong grasp of
the foundations of programming will allow you to use those foundations to use
documentation to build so much more than someone who tries to memorize all the
built-in methods in Python.
One important string method: format()
We will be using the format() string method a good bit in our future work in Python,
and you will find it very valuable in your coding, especially with your print statements.
We can best illustrate how to use format() by looking at some examples:
Example 1
print("Mohammed has {} balloons".format(27))
Example 1 Output
Mohammed has 27 balloons
Example 2
animal = "dog"
action = "bite"
print("Does your {} {}?".format(animal, action))
Example 2 Output
Does your dog bite?
Example 3
maria_string = "Maria loves {} and {}"
print(maria_string.format("math", "statistics"))
Example 3 Output
Maria loves math and statistics
Notice how in each example, the number of pairs of curly braces {} you use inside
the string is the same as the number of replacements you want to make using the
values inside format() .
Lists!
Data structures are containers that organize and group data types together in
different ways. A list is one of the most common and basic data structures in
Python.
You saw here that you can create a list with square brackets. Lists can contain any
mix and match of the data types you have seen so far.
>>> list_of_random_things[0]
1
It might seem like you can pull the last element with the following code, but this
actually won't work:
>>> list_of_random_things[len(list_of_random_things)]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-34-f88b03e5c60e> in <module>()
----> 1 lst[len(lst)]
>>> list_of_random_things[len(list_of_random_things) - 1]
True
Alternatively, you can index from the end of a list by using negative values, where -1
is the last element, -2 is the second to last element and so on.
>>> list_of_random_things[-1]
True
>>> list_of_random_things[-2]
a string
>>> list_of_random_things[:2]
[1, 3.4]
or to return all of the elements to the end of the list, we can leave off a final
element.
>>> list_of_random_things[1:]
[3.4, 'a string', True]
This type of indexing works exactly the same on strings, where the returned value
will be a string.
1. Are they mutable?
2. Are they ordered?
Order is about whether the position of an element in the object can be used to
access the element. Both strings and lists are ordered. We can use the order to
access parts of a list and string.
However, you will see some data types in the next sections that will be unordered.
For each of the upcoming data structures you see, it is useful to understand how
you index, are they mutable, and are they ordered. Knowing this about the data
structure is really useful!
Additionally, you will see how these each have different methods, so why you would
use one data structure vs. another is largely dependent on these properties, and
what you can easily do with it!
Lambda functions
In this tutorial, we will see how to declare Anonymous functions and how
to return values from them.
These functions help reduce the number of lines of the code when
compared to named Python functions.
The Python language, like other programming languages, can sort data.
Parameter Values:-
Parameters Values
In the key parameter, we specify a function that is called on each
key
list element before making comparisons.
This is optional. False will sort the list in ascending order, and
true will sort the list in descending order.
reverse
Default is reverse=False.
Sort() does not return any value, but it changes from the original
list.
p=1
def foo(l):
return l[p]
l.sort(key = foo)
print(l)
Python has a built-in operation that we can access with the % operator.
This will help us to do simple positional formatting. If anyone knows a
little bit about C programming, then they have worked with printf
statement, which is used to print the output. This statement uses the %
operator. Similarly, in Python, we can perform string formatting using the
% operator. For Example:
name="Jack”
print(n)
#2 Using Tuple ()
Syntax: {}.format(values)
For Example,
str = "This article is written in {} "
print (str.format("Python"))
Copy
Output: This article is written in Python.
#4 Using f-Strings ( f ):
str1="Python”
str2="Programming”
Time Module:-
me = "Harry"
a1 =3
# a = "this is %s %s"%(me, a1)
# a = "This is {1} {0}"
# b = a.format(me, a1)
# print(b)
a = f"this is {me} {a1} {math.cos(65)}"
# time
print(a)
Positional and Keyword Arguments in Python
So far, we have understood how to define simple functions and pass arguments to the functions
and print them during the execution. Now, let’s take a step further and understand the two
important types of arguments in python – the positional and the keyword arguments. The
positional arguments are defined by the single asterisk before the parameter name, e.g. “*args”.
The keyword arguments are defined by placing a double asterisk in front of the parameter name,
e.g. “**kwargs”. An important point worth mentioning here is that the names args and kwargs are
just placeholders and can be replaced with any other meaningful names. However, as a best
practice, it is left as the same so that it’s easier for others to understand that the function accepts
a positional or a keyword argument.
As you can see in the output above, the arguments are printed in the order they are passed into
the function. If you alter the position of the arguments while calling the function, then the output
will change.
Also, in this case, you need to provide all three arguments while calling the function. In case, one
or more arguments are missing, the function will throw an error during execution as there are no
optional parameters defined. Let us now try to make the function a bit more flexible by making
all three parameters optional. This can be done by assigning default values to the function as
follows.
When you run the above code, all the three users passed as arguments in the main function are
iterated and the message is displayed for each of the users separately.
Python provides many built-in functions that are predefined and can be
used by the programmers by just calling them. These functions not only
ease our work but also create a standard coding environment. In this
tutorial, we will learn about three important functions: map(),
filter, and reduce() in Python. These functions are most commonly used
with Lambda function. "Lambda functions are functions that do have
any name". These functions are used as parameters to other functions.
If you do not know what lambda functions are, then I recommend you to
check Anonymous/Lambda Functions In Python tutorial first to avoid
any confusion.
These three methods expect a function object as the first argument. This
function object can be a normal or predefined function. Most of the time,
functions passed to map(), filter(), and reduce() are the ones we only use
once, so there's often no point in defining a named function(def
function).To avoid defining a new function, we write an anonymous
function/lambda function that we will only use once and never again.
map():
The iterable could be a list, tuple, set, etc. It is worth noting that the
output in the case of the map is also an iterable i.e., a list. It is a built-in
function, so no import statement required.
SYNTAX:
map(function, iterable)
Copy
A map function takes two parameters:
Example:
items = [1, 2, 3, 4, 5]
a=list(map((lambda x: x **3), items))
print(a)
#Output: [1, 8, 27, 64, 125]
Copy
The map()function passes each element in the list to a lambda function
and returns the mapped object.
filter():-
SYNTAX:
filter(function, iterable)
Copy
It also takes two parameters:
First one is the function for which the condition should satisfy
The second one is the iterable
Example:
a = [1,2,3,4,5,6]
b = [2,5,0,7,3]
c= list(filter(lambda x: x in a, b))
print(c) # prints out [2, 5, 3]
Copy
reduce():
Unlike the previous two functions (Filter and Map), we have to import the
reduce function from functools module using the statement:
Import functools
SYNTAX:
reduce(function, iterable)
Copy
Example:
from functools import reduce
a=reduce( (lambda x, y: x * y), [1, 2, 3, 4] )
print(a)
#Output: 24
Copy
Like the previous two, it also takes two-parameter. First one is the
function and the second one is the iterable
Its working is very interesting as it takes the first two elements of the
iterable and performs the function on them and converts them into a
single element. It proceeds further, taking another element and
performing the function of that one and the new element. For example, if
we have four digits and the function wants to multiply them, then we can
first multiply the first two and then multiply the third one in their resultant
and then the forth and so on. The reduce is in the functools in Python
3.0. It is more complex. It accepts an iterator to process, but it is not an
iterator itself. It returns a single result.
# for i in range(len(numbers)):
# numbers[i] = int(numbers[i])
# numbers[2] = numbers[2] + 1
# print(numbers[2])
# def sq(a):
# return a*a
#
# num = [2,3,5,6,76,3,3,2]
# square = list(map(sq, num))
# print(square)
# num = [2,3,5,6,76,3,3,2]
# square = list(map(lambda x: x*x, num))
# print(square)
# def square(a):
# return a*a
#
# def cube(a):
# return a*a*a
#--------------------------FILTER------------------------------
# list_1 = [1,2,3,4,5,6,7,8,9]
#
# def is_greater_5(num):
# return num>5
#
# gr_than_5 = list(filter(is_greater_5, list_1))
# print(gr_than_5)
#--------------------------REDUCE------------------------------
from functools import reduce
list1 = [1,2,3,4,2]
num = reduce(lambda x,y:x*y, list1)
# num = 0
# for i in list1:
# num = num + i
print(num)