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

Python Tutorial

The document provides explanations of several Python concepts: 1. Functions can return None by default if no return statement is specified. Local variables are destroyed when the function exits, while global variables declared inside functions can be modified by declaring them global. 2. The print() function's default separator is a space and end is a newline, but these can be changed. Local and global variables operate independently unless a variable is declared global. 3. Lists, tuples, and dictionaries are covered, including their syntax, indexing, slicing, methods for modifying them like append(), insert(), remove(), and more. Concepts like mutable vs immutable, copying lists, and using references are also explained.

Uploaded by

Data Heaven
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python Tutorial

The document provides explanations of several Python concepts: 1. Functions can return None by default if no return statement is specified. Local variables are destroyed when the function exits, while global variables declared inside functions can be modified by declaring them global. 2. The print() function's default separator is a space and end is a newline, but these can be changed. Local and global variables operate independently unless a variable is declared global. 3. Lists, tuples, and dictionaries are covered, including their syntax, indexing, slicing, methods for modifying them like append(), insert(), remove(), and more. Concepts like mutable vs immutable, copying lists, and using references are also explained.

Uploaded by

Data Heaven
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

RETURN FUNCTION (insightful, not much useful)

>>> spam = print('Hello!')
Hello!
>>> None == spam
True

Behind the scenes, Python adds return None to the end of any function
definition with no return statement. This is similar to how
a while or for loop implicitly ends with a continue statement. Also, if you
use a return statement without a value (that is, just the return keyword by
itself), then None is returned.

PRINT SEP,END FUNCTION (excessive detail, not much


useful)
Defaults in print function
End = newline
Sep = space [i.e. print(‘hello’,’world’) = hello world]

We can change it. For eg


print('Hello', end='')
print('World')

>> HelloWorld {bcs first print ends with ‘nothing’ instead of ‘newline’)

ANOTHER EG:
print('cats', 'dogs', 'mice', sep=',')
>>>cats,dogs,mice [comma used as separator instead of default ‘space’]

>>> print() prints a new line


print(\n\n\n) for 4 new lines

LOCAL AND GLOBAL VARIABLE (useful)


>See the rock, paper, scissors game to understand better
>A local variable contains its value only as long as the
function is still running. The moment the function ends
executing, the value is destroyed. It’s not carried forward.
For eg,
What is value of egg returned by following code:
 def spam():
    eggs = 99
bacon()
    print(eggs)

  def bacon():
     ham = 101
    eggs = 0

 spam()

It will return 99

>>> If a variable name is used both within the function and globally, then
both of them will behave individually without affecting each other However,
to avoid confusion, try naming them differently. For eg
def spam():
    ➊ eggs = 'spam local'
       print(eggs)    # prints 'spam local'

   def bacon():
    ➋ eggs = 'bacon local'
       print(eggs)    # prints 'bacon local'
       spam()
       print(eggs)    # prints 'bacon local'

➌ eggs = 'global'
   bacon()
   print(eggs)        # prints 'global'

will return
bacon local
spam local
bacon local
global

>>> Now, to both “USE” & “MODIFY” the value of a global variable from
within a function itself, declare the variable as global within the function.
Now, the variable will act as if not within a function but globally. The
function will be able to use its global value as well as modify its global value.
>>> Suppose there’s a global variable, and you can use its value within a
function but you can’t modify the global variable without declaring it as
global first. Because the line of code that would modify its value would
actually create a local variable (since you haven’t declared it global).
For eg.
def spam():
    print(eggs)
eggs = 42
spam()

would return 42. But the following code


def spam():
       print(eggs)
     eggs = 'spam local'

eggs = 'global'
spam()

would return an error because the third line of code declares a local variable
named eggs and the 2nd line prints the value of a ‘local’ variable that has not
been assigned a value till that line of code. Hence, error.

RANGE FUNCTION (useful)


Range(start,stop,step)
The output would include ‘start’ but exclude ‘stop’ just like
discreet frequency distribution. Start is optional.
For eg, range(4) will return 0,1,2,3
For eg, the following code will return

x = range(3, 6)
for n in x:
  print(n)
>>>3,4,5
On a side note, if statement is not a loop. For & while are loops. They
have functions such as continue (to start from beginning) and break (to
break out of the loop)
>>>NOTE : To continue Python codes in next line, end the line with a \
and continue typing in next line.

TRY & EXCEPT (useful)


It’s just like the if else of error. ‘Try’ means “keep executing
this until error occurs” and the moment error is occurred, the code
jumps to the immediate ‘except’. After the error occurs, the rest of
the code within ‘try’ is not executed and only the code within
‘except’ is executed. For eg, in the following code

def spam(divideBy):
    return 42 / divideBy

try:
    print(spam(2))
    print(spam(12))
    print(spam(0))
    print(spam(1))
except ZeroDivisionError:
    print('Error: Invalid argument.')

the return is

21.0
3.5
Error: Invalid argument.

LISTS(useful):

1) spam = ['cat', 'bat', 'rat', 'elephant']

   spam[0] is ‘cat’

spam[-1] is ‘elephant’

spam[0:2] is [‘cat’,’bat’]

spam[0:-1] is [‘cat’,’bat’,’rat’]

spam[:2] is [‘cat’,’bat’]

Even a string is just a list of its individual characters. So, all these
functions would apply on a string as well. But unlike lists, strings are not
mutable, ie they cant be amended like lists. Only data can be extracted from
them.

A list can contain lists

 2)Ammend, concatenate, and delete :

 Spam[1] = ‘hooter’

Print(spam) is ['cat', 'hooter', 'rat', 'elephant']

 del spam[2]

print(spam) is ['cat', 'hooter','elephant']

 Spam + [‘bat’,’loot’]
Print(spam) is ['cat', 'hooter', 'rat', 'elephant', ‘bat’,’loot’]

3)Misc

>>>> cat = ['fat', 'gray', 'loud']


>>> size, color, disposition = cat

Now size is fat, color is gray and disposition is loud. This would work
only when the number of variables being assigned a value and len(list) is same,
otherwise an error will occur. If numbers are diff, then do like this

Size=cat[0]

4)Enumerate function

It returns 2 values. Index and item.

>For x,y in enumerate(spam):

Print(‘index is ‘+str(x)+’ and item is’+y)

>>> index is 1 and item is cat

Index is 2 and item is bat……………

5)random.choice(some list) chooses some random item from list

Random.shuffle(some list) reshuffles the list.

6)> spam=spam+1 is same as, spam += 1


>spam.index(‘bat’) would return 1. If there are duplicate items, it would
return the index of first occurrence of item
> spam.append(‘hola’) would make spam as ['cat', 'bat', 'rat', 'hola']

> spam.insert(2,’BYE’) would make spam ['cat', 'bat',’BYE’, 'rat',]

> spam.remove(‘cat’) makes spam as ['bat', 'rat']

>spam.sort() sorts either a number or alphabet list. To short in descending


order, type spam.sort(reverse=True)

In its default sort, Big letters are placed before smaller letter. i.e A<a.

To make small case come first while ascending, type


spam.sort(key=str.lower)

>spam.reverse() reverses the list.

>List items can continue on next line. It wont hamper the code.

#NOTE : remember that all the aforementioned things are just


methods that ‘ammends the list in place’ and they ‘don’t have a
return value’. So typing some thing like legit=spam.append(‘hola’)
would cause an error because it has no return value that legit list
can take up. Instead, it just amends the spam list.

TUPPLES(useful):
Same as list except they are typed in () instead of []
And they are IMMUTABLE.

If you have only one value in your tuple, you can indicate this by placing a
trailing comma after the value inside the parentheses. Otherwise, Python will
think you’ve just typed a value inside regular parentheses. See yourself.
>>> type(('hello',))
<class 'tuple'>
>>> type(('hello'))
<class 'str'>

>>List(tupple_1) returns tupple_1 as a list.


{remember, it’s not a method. It doesn’t make
tupple_1 a list.
Tupple_1 is still a tupple. This functions returns a list that
acrries all the elements of tupple_1
Similarly, tupple(list_1) returns a tupple with all elements of
list_1

REFERENCES(very logical & useful):


You must have assumed that typing x=5 means that x
has stored the value of 5. But that’s wrong. Instead,
Python has stored the value 5 somewhere in the
computer memory, given it an ID (for eg. 54864561)
and the variable x has been given this ID as a
reference. So, x stores the ID number of 5 but not
the value 5 itself.

Now, we know that strings or integers are immutable.


I.e. the value 5 can’t be changed. I.e, in the ID
number 54864561, no other value than 5 can exist. So,
suppose if we type x=8 in next line, the value 8 will
be stored n anew place in the memory, the ID of which
will be assigned to x. 5 remains intact at its
designated ID. [Don’t worry about memory. Python has
also garbage collection function for deleteing values
to which no variables refer to]
For eg,
>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam
100
>>> cheese
42

Here, in the 2nd line, the ID number that spam contains


has been given to cheese as well. However, in the 3rd
line, since, a new value is assigned to spam, its ID
stored changes, but cheese still stores the old ID.
That’s why both giving different results.

Now, we have learned that Lists and dictionaries are


mutable. I.e. the values stored at an ID can change.
When they are amended, a new ID isn’t created, unlike
strings and integers. Rather, the values of that ID
itself change.

>>> spam = [0, 1, 2, 3, 4, 5]
➋ >>> cheese = spam # The reference is being copied, not the list.
➌ >>> cheese[1] = 'Hello!' # This changes the list value.
   >>> spam
   [0, 'Hello!', 2, 3, 4, 5]
   >>> cheese # The cheese variable refers to the same list.
   [0, 'Hello!', 2, 3, 4, 5]

That’s why lists behave like this. Cheese and Spam


contain same ID. Now, when cheese is amending, a new ID
is not being created. Rather, the values at the same ID
is being edited. That’s why even spam is giving this
result.

Now, the problem that I face is supposed, I want to


create a new list cheese with a ll the same items as
spam. But whenever I do, cheese = spam, only the
reference is being copied and any edit in cheese also
edits spam which I don’t want. I want cheese to create
a new ID and refer to that and not refer to the same ID
as spam. Solution is
>>>import copy
>>> cheese=copy.copy(spam)
Now, if the list spam itself contains lits, then we
need to use copy.deepcopy(spam).

Dictionaries(useful) :

These are same as list, except one thing. In lists, we type


values and default key is “Index”, which starts from 0.
However, in dictionaries, even key is provided by us. For eg
Dictionary_1= {‘colour’:’yellow’,’height’:’six
feet’,’weight’:’40’}
Since, index is not the key in this case, unlike lists,
dictionaries are unordered. i.e
>>>[‘hello’,’tata’,’bye’] = [‘hello’,’bye’,’tata’] is False
>>>{‘colour’:’yellow’,’height’:’six feet’,’weight’:’40’} =
{‘colour’:’yellow’ ,’weight’:’40’,’height’:’six feet’} is True

Unlike list, here slice functions( e.g. dictionary_1(1:4))


wouldn’t be able to extract any value since dictionaries
doesn’t have index as keys.
However, dictionary_1[‘colour’] would produce yellow.
Dictionary.keys(), Dictionary.values(), &
Dictionary.items() [this one creates a list of tupples
of key-vale pair] creates temporary immutable lists for
loop purpose. If you wanna store it as permanent list
then,
X = list(Dictionary.keys())
‘name’ in Dictionary.keys() [ returns true or false] is
same as ‘name’ in Dictionary but different from ‘name’
in Dictionary.values()
If I wanna retrieve Dictionary[‘name’], it will return
error if there’s no key by that name. So,

Dictionary.get(‘name’,’vin’) will get the value of key


‘name’ and if there’s no such key, it will return
‘vin’, but remember it won’t add a new key-value to the
dictionary.
 Dictionary.setdefault(‘name’,’vin’). It too returns
value like get() except it ALSO appends the dictionary.
However, if the key already exists, it WON’T UPDATE the
value. A programme example :

>>> spam = {'name': 'Pooka', 'age': 5}


>>> spam.setdefault('color', 'black')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
>>> spam.setdefault('color', 'white')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}

message = 'It was a bright cold day in April, and the clocks were
striking
thirteen.'
count = {}

for character in message:


➊ count.setdefault(character, 0)
➋ count[character] = count[character] + 1

print(count)
    
Import pprint
Pprint.pprint(Dictionary) gives a better print view
A program to count total fruits brought by various
guests :

allGuests = {'Alice': {'apples': 5, 'pretzels': 12},


             'Bob': {'ham sandwiches': 3, 'apples': 2},
             'Carol': {'cups': 3, 'apple pies': 1}}

def totalBrought(guests, item):


    numBrought = 0
  ➊ for v in guests.values():
      ➋ numBrought = numBrought + v.get(item, 0)
     return numBrought

print('Number of things being brought:')


print(' - Apples         ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups           ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes          ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham
sandwiches')))
print(' - Apple Pies     ' + str(totalBrought(allGuests, 'apple
pies')))

You might also like