Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
203 views

Udacity Python Course

The document provides information on various Python concepts including: - Print is a built-in function that displays output values as text. - Arithmetic operators include addition, subtraction, multiplication, division, modulo, exponentiation, and integer division. - Integers and floats are numeric data types where int is for whole numbers and float is for decimal values. - Strings can be defined using single or double quotes and various string methods like lower(), upper(), split() are described.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
203 views

Udacity Python Course

The document provides information on various Python concepts including: - Print is a built-in function that displays output values as text. - Arithmetic operators include addition, subtraction, multiplication, division, modulo, exponentiation, and integer division. - Integers and floats are numeric data types where int is for whole numbers and float is for decimal values. - Strings can be defined using single or double quotes and various string methods like lower(), upper(), split() are described.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Things to remember

1. Case sensitive language


2. Spacing is important (indentation)

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

.  4.445e8  is equal to  4.445 * 10 ** 8  which is equal to  444500000.0 .

Integers and Floats


There are two Python data types that could be used for numeric values:

 int - for integer values


 float - for decimal or floating point values
You can create a value that follows the data type by using the following syntax:

x = int(4.7) # x is now an integer 4


y = float(4) # y is now a float of 4.0
You can check the type by using the  type  function:
>>> print(type(x))
int
>>> print(type(y))
float
Because the float, or approximation, for 0.1 is actually slightly more than 0.1,
when we add several of them together we can see the difference between the
mathematically correct answer and the one that Python creates.

>>> print(.1 + .1 + .1 == .3)


False
Documentation of python : https://docs.python.org/3/contents.html

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:

>>> this_string = 'Simon's skateboard is in the garage.'


File "<ipython-input-20-e80562c2a290>", line 1
this_string = 'Simon's skateboard is in the garage.'
^
SyntaxError: invalid syntax
The color highlighting is also an indication of the error you have in your string in this
second case. There are a number of other operations you can use with strings as
well. In this video you saw a few:

>>> first_word = 'Hello'


>>> second_word = 'There'
>>> print(first_word + second_word)

HelloThere

>>> print(first_word + ' ' + second_word)

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() .

String methods : https://docs.python.org/3/library/stdtypes.html#string-methods

Another important string method:  split()


A helpful string method when working with strings is the .split method. This
function or method returns a data container called a list that contains the words
from the input string. We will be introducing you to the concept of lists in the
next video.
The split method has two additional arguments (sep and maxsplit).
The sep argument stands for "separator". It can be used to identify how the
string should be split up (e.g., whitespace characters like space, tab, return,
newline; specific punctuation (e.g., comma, dashes)). If the sep argument is not
provided, the default separator is whitespace.
True to its name, the maxsplit argument provides the maximum number of
splits. The argument gives maxsplit + 1 number of elements in the new list, with
the remaining string being returned as the last element in the list. You can read
more about these methods in the Python documentation too.
Here are some examples for the  .split()  method.
1. A basic split method:
2. new_str = "The cow jumped over the moon."
3. new_str.split()
Output is:

['The', 'cow', 'jumped', 'over', 'the', 'moon.']


4. Here the separator is space, and the maxsplit argument is set to 3.
5. new_str.split(' ', 3)
Output is:

['The', 'cow', 'jumped', 'over the moon.']


6. Using '.' or period as a separator.
7. new_str.split('.')
Output is:

['The cow jumped over the moon', '']


8. Using no separators but having a maxsplit argument of 3.
9. new_str.split(None, 3)
Output is:

['The', 'cow', 'jumped', 'over the moon.']

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 = [1, 3.4, 'a string', True]


This is a list of 4 elements. All ordered containers (like lists) are indexed in python
using a starting index of 0. Therefore, to pull the first value from the above list, we
can write:

>>> 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)]

IndexError: list index out of range


However, you can retrieve the last element by reducing the index by 1. Therefore,
you can do the following:

>>> 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

Slice and Dice with Lists


You saw that we can pull more than one value from a list at a time by using slicing.
When using slicing, it is important to remember that the  lower  index is  inclusive  and
the  upper  index is  exclusive .
Therefore, this:

>>> list_of_random_things = [1, 3.4, 'a string', True]


>>> list_of_random_things[1:2]
[3.4]
will only return 3.4 in a list. Notice this is still different than just indexing a single
element, because you get a list back with this indexing. The colon tells us to go from
the starting value on the left of the colon up to, but not including, the element on
the right.
If you know that you want to start at the beginning, of the list you can also leave out
this value.

>>> 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.

Are you  in  OR  not in ?


You saw that we can also use  in  and  not in  to return a bool of whether an element
exists within our list, or if one string is a substring of another.
>>> 'this' in 'this is a string'
True
>>> 'in' in 'this is a string'
True
>>> 'isa' in 'this is a string'
False
>>> 5 not in [1, 2, 3, 4, 6]
True
>>> 5 in [1, 2, 3, 4, 6]
False

Mutability and Order


Mutability is about whether or not we can change an object once it has been
created. If an object (like a list or string) can be changed (like a list can), then it is
called mutable. However, if an object cannot be changed with creating a completely
new object (like strings), then the object is considered immutable.
>>> my_lst = [1, 2, 3, 4, 5]
>>> my_lst[0] = 'one'
>>> print(my_lst)
['one', 2, 3, 4, 5]
As shown above, you are able to replace 1 with 'one' in the above list. This is
because lists are mutable.
However, the following does not work:

>>> greeting = "Hello there"


>>> greeting[0] = 'M'
This is because strings are immutable. This means to change this string, you will
need to create a completely new string.
There are two things to keep in mind for each of the data types you are using:

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

Anonymous/Lambda Functions In Python


As we have studied function in the previous lecture, we know that if a
program has a large piece of code that is required to be executed
repeatedly, then it will be better to implement that piece of code as a
function. Functions improve code reusability, modularity, and integrity.

In this tutorial, we will see how to declare Anonymous functions and how
to return values from them.

As we have studied in the previous lecture, the syntax for function


declaration is as follows:
def function_name ():
Copy

What is Anonymous function?

In Python programming, an anonymous function or lambda expression


is a function definition that is not bound to an identifier (def).

The anonymous function is an inline function. The anonymous functions


are created using a lambda operator and cannot contain multiple
expressions.

 The following example will show how anonymous functions work: 


result = lambda n1, n2, n3: n1 + n2 + n3;
print ("Sum of three values : ", result( 10, 20, 25 ))
Copy
In the above code, we have created an anonymous function that adds
three numbers. The function is stored in a variable named result. The
function can then be called using this variable. In the above code, the
function has been called with three different parameter values for the
function call.

Anonymous functions can accept inputs and return the outputs, just


like other functions do.

Why do we use Python Lambda Functions?

The main objective of anonymous functions is that, when we need a


function just once, anonymous functions come in handy. Lambda
operator is not only used to create anonymous functions, but there are
many other uses of the lambda expression. We can create anonymous
functions wherever they are needed. Due to this reason, Python Lambda
Functions are also called as throw-away functions which are used along
with other predefined functions such as reduce(), filter(), and map(). 

These functions help reduce the number of lines of the code when
compared to named Python functions.

Significant Differences Between Lambda Expressions And Simple Functions.

1. Can be passed immediately with or without variables.


2. They are inline functions.
3. Automatic return of results.
4. There is neither a document string nor a name.

Python List sort():

Sorting means arranging data systematically. If the data we want to work


with is not sorted, we will face problems finding the desired element.

The Python language, like other programming languages, can sort data.

Python has an in-built method i.e. sort(), which is used to sort the


elements of the given list in a specified ascending or descending order.
There is also a built-in function i.e. sorted(), that builds a new sorted list
from an iterable like list, dictionary, etc.

The syntax of the sort() method is:


list.sort(key=myFunc ,reverse=True|False)
Copy

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.

Code file as described in the video


# Lambda functions or anonymous functions
# def add(a, b):
# return a+b
#
# # minus = lambda x, y: x-y
#
# def minus(x, y):
# return x-y
#
# print(minus(9, 4))

a =[[1, 14], [5, 6], [8,23]]


a.sort(key=lambda x:x[1])
print(a)

sort without lambda function:

l =[[2,7,34] , [23,56,74], [6,2,4]]

p=1
def foo(l):
    return l[p]
l.sort(key = foo)
print(l)

F-Strings & String Formatting In Python


String formatting is used to design the string using formatting techniques
provided by the particular programming language. From the % formatting
to the format() method, to format string literals, there is no limit as to the
potential of string crafting. There are four significant ways to do string
formatting in Python. In this tutorial, we will learn about the four main
approaches to string formatting in Python.

#1 String Formatting (% Operator)

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”

n="%s My name is %s” %name

print(n)

Output: "My name is Jack."


Copy
The problem with this method is when we have to deal with large strings.
If we specify the wrong type of input type operator, then it will throw an
error. For Example, %d will throw a TypeError if the input is not an
integer.

#2 Using Tuple ()

The string formatting syntax, which uses % operator changes slightly if


we want to make multiple substitutions in a single string. The % operator
takes only one argument, to mention more than one argument, use
tuples. Tuples are better than using the old formatting string method.
However, it is not an ideal way to deal with large strings. For Example:
name=”Jack”
class=5
s=”%s is in class %d”%(name,class)
print(s)
Copy
Output: Jack is in class 5.

#3   String Formatting (str.format)

Python 3 introduced a new way to do string formatting. format() string


formatting method eliminates the %-operator special syntax and makes
the syntax for string formatting more regular. str.format() allows multiple
substitutions and value formatting. We can use format() to do simple
positional formatting, just like you could with old-style formatting:

In str.format(), we put one or more replacement fields and placeholders


defined by a pair of curly braces { } into a string.

Syntax: {}.format(values)

For Example,
str = "This article is written in {} "

print (str.format("Python"))
Copy
Output: This article is written in Python.

This string formatting method is preferred over %-style formatting. Using


the format() method, we can deal with large strings, and the code will
become more readable.

#4 Using f-Strings ( f ):

Python added a new string formatting approach called formatted string


literals or "f-strings." This is a new way of formatting strings. A much
more simple and intuitive solution is the use of Formatted string literals.f-
string has an easy syntax as compared to previous string formatting
techniques of Python. They are indicated by an "f" before the first
quotation mark of a string. Put the expression inside { } to evaluate the
result. Here is a simple example
## declaring variables

str1="Python”

str2="Programming”

print(f"Welcome to our {str1}{str2} tutorial”)


Copy
Output: Welcome to our Python Programming tutorial.

Time Module:-

The time module provides time-related functions. It handles the time-


related tasks. To use functions that are defined in this module, we need
to import the module first.
import time
Copy
It is mostly used in measuring the time elapsed during program
execution.

Code file as described in the video


# F strings
import math

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.

Positional Arguments in Python


These are the simplest type of arguments to pass in a function in python. You can define as many
parameters in a function and then provide the arguments in the same order as defined in the
function. The python program will read the arguments accordingly and perform the necessary
actions. You can consider the following snippet to understand what a positional argument is used
in a function.

Figure 4 – Positional Argument example in python (SourceCode)

The output from the above code block is as follows.


Figure 5 – Output from the above code block

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.

Figure 6 – Specifying default values for the function parameters

Figure 7 – Output from the above code block


As you can see in the above figure, we have specified the argument for the
parameters a and c but not for b. Notice how we have explicitly mentioned the parameter
name c while assigning the argument. This is done because, by default, the positional argument
will be assigned to the parameter b instead of c.
We can extend this functionality of providing positional arguments by declaring a single asterisk
* operator, also known as the iterable unpacking operator.

Figure 8 – Using the iterable unpacking operator in python (SourceCode)

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.

Figure 9 – Output from the above code block


Although we have defined only one parameter in the greet() function, the * operator takes the
input as a positional argument and is then iterated using the for a loop. This is dynamic in nature
as it can automatically handle multiple argument values and the programmer doesn’t need to
define the parameter separately.

Keyword Arguments in Python


Now that we know what the positional arguments are and how to use those, using the keyword
arguments will be quite easy. This is also something similar to the positional arguments, however,
it is denoted by a **, a double asterisk in front of the parameter name also known as
the dictionary unpacking operator.
Figure 10 – Using the dictionary unpacking operator in python (SourceCode)

The output from the above code block is as follows:

Figure 11 – Output from the above code block


As you can see in the figure above, the dictionary unpacking operator, or in simple words, we
have used the **kwargs as an argument to the function and printed out the values on the
console. It is evident from the above example that you can pass as many items as the arguments
and all those will be unpacked and used by the function. This method is in many complex
applications wherein the function is already developed by providing default values. However, if
the user wants to override the default value, then it can be passed as an argument. This makes
the parameter an optional one and also simplifies the life of the user as they need not worry
about providing arguments to each of the parameters in the function.

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.

Figure 1:Anonymous/Lambda Functions In Python

Why are lambdas relevant to map(), filter() and reduce()?

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():

"A map function executes certain instructions or functionality


provided to it on every item of an iterable."

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:

 First one is the function through which we want to pass the


items/values of the iterable
 The second one is the iterable itself

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():-

"A filter function in Python tests a specific user-defined condition


for a function and returns an iterable for the elements and values
that satisfy the condition or, in other words, return true."

It is also a built-in function, so no need for an import statement. All the


actions we perform using the filter can also be performed by using a for
loop for iteration and if-else statements to check the conditions. We can
also use a Boolean that could take note of true or false, but that would
make the process very lengthy and complex. So, to simplify the code, we
can use the filter function.

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():

"Reduce functions apply a function to every item of an iterable and


gives back a single value as a resultant".

Unlike the previous two functions (Filter and Map), we have to import the
reduce function from functools module using the statement:

from functools import reduce

We can also import the whole functools module by simply writing

Import functools

But in the case of bigger projects, it is not good practice to import a


whole module because of time restraint.

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.

Code file as described in the video


#--------------------------MAP------------------------------
# numbers = ["3", "34", "64"]
# numbers = list(map(int, numbers))

# 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

# func = [square, cube]


# num = [2,3,5,6,76,3,3,2]
# for i in range(5):
# val = list(map(lambda x:x(i), func))
# print(val)

#--------------------------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)

You might also like