Python Basics Notes
Python Basics Notes
Why Python?
Presence of Third Party Module
Extensive Support Libraries.
Open Source and Community Development.
Learning Ease and Support Available.
User-friendly Data Structures.
Productivity and Speed.
A Python identifier is a name used to identify a variable, function, class, module or other object.
An identifier
starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits
(0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers.Python is a case sensitive
programming language. Thus, Manpower and manpower are two different identifiers in Python.
Valid identifiers:
Invalid identifers:
Let's see
In [2]:
# Run this cell and see the answer in boolean way(True, False) and don't worry if you don't
# Just keep in mind, there's a way to cross check the identifier.
print("abc".isidentifier()) # True
print("99a".isidentifier()) # False
print("_".isidentifier()) # True
print("for".isidentifier()) # True - wrong output
True
False
True
True
Reserved words (also called keywords) are defined with predefined meaning and syntax in the language. These
keywords have to be used to develop programming instructions. Reserved words can’t be used as
identifiers for
other programming elements like name of variable, function etc.
and, except, lambda, with, as, finally, nonlocal, while, assert, false, None, yield, break, for, not, class, from, or,
continue
,global, pass, def, if, raise, del, import, return, elif, in, True, else, is, try
To see what each keyword means here, you can refer this link
Click here
(https://www.w3schools.com/python/python_ref_keywords.asp)
In [1]:
# Run this command and you will see reserved keywords in a list(list is a data structure yo
import keyword
keyword.kwlist
Out[1]:
['False',
'None',
'True',
'and',
'as',
'assert',
'async',
'await',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield']
Variables
In [6]:
# creation of a variable
# You can use either single or double quote while defining string variable
x = 5 # int type(default)
y = "CloudyML" # string type
print(x)
print(y)
print(type(x)) # to check type of variable
print(type(y))
CloudyML
<class 'int'>
<class 'str'>
In [1]:
# You can also assign multiple variables at the same time like this
a, b, c = 'Hack', 'weekly', 'group'
print(a)
print(b)
print(c)
Hack
weekly
group
In [2]:
Python
Java
C++
In [7]:
# Casting of a variable
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
3.0
<class 'str'>
<class 'int'>
<class 'float'>
In [10]:
cloud
In [11]:
# If you define variable with same name then the variable's old value will be replaced by n
A = "ML"
print(A) # previously it was A = "cloud"
ML
In [4]:
# Would you like to add two variables ? Obviously it's gonna happen so let's learn what can
Python is awesome
In [10]:
# suppose if I want to type cast integer to string and then add?? How will I do this??
num1_str = str(num1)
num2_str = str(num2)
print("After type casting integer to string, and then adding two numbers --->",num1_str+num
After type casting integer to string, and then adding two numbers ---> 1947
In [11]:
# Suppose you want to add string with numbers or vice versa... I mean different variables..
str1 = "Python version is "
version = 3.8
# print(str1 + version) # it will throw TypeError, You can try running the code
---------------------------------------------------------------------------
<ipython-input-11-3f0ffd7e9c9e> in <module>
3 version = 3.8
In [12]:
# But you can add string with integer by type casting integer to string
print(str1 + str(version))
In [19]:
def myfunc():
x = "fantastic" # Local variable because it is defined inside function and it has scope
print("CloudyML is " + x) # here local variable gets priority when name of local and g
myfunc()
print("CloudyML is " + x)
CloudyML is fantastic
CloudyML is awesome
In [20]:
# What if you want to call global variable with same name as local inside a function??
def myfunc():
global x
x = "fantastic" # Local variable because it is defined inside function and it has scope
print("CloudyML is " + x) # here global variable gets priority because I used global k
myfunc()
print("CloudyML is " + x)
CloudyML is fantastic
CloudyML is fantastic
In [29]:
# Method 1
quantity = 5
item_name = "Mango"
price = 10
order = "I want {} pieces of {} for {} dollars." # {} is called placeholder, so 3 placehold
print(order.format(quantity, item_name, price))
# Method 2
order = "I want {0} pieces of {1} for {2} dollars." # here 0,1,2 tells the position of qu
print(order.format(quantity, item_name, price))
# Method 3
print(f"I want {quantity} pieces of {item_name} for {price} dollars.") # Observe the f out
# names passed in
# Method 4
print("I want %d pieces of %s for %.0f dollars."%(quantity, item_name, price)) # %d for int
# with 0 de
String slicing
Syntax
let's say we have a string 'a' and we want to use indexing to get something from the string
a[start:stop:step] -----> start means starting index number, stop is the last index no which won't be
included, # step is the jump from start
Observe the index numbering from left to right and right to left which we will use in next cell
In [3]:
Data Scien
Dt ce
century
Next few commands where we are using some equality operators will return boolean True or False
In [8]:
print(10 > 9)
print(10 == 9)
print(10 < 9)
True
False
False
In [9]:
False
False
False
False
False
False
False
In [11]:
True
True
True
In [14]:
x = 15
y = 4
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
x % y = 3
These are the conditions used basically in if, elif, and else
statement
Equals: a == b
localhost:8888/notebooks/Downloads/Python basics Notes.ipynb 10/17
9/1/2021 Python basics Notes - Jupyter Notebook
q
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
In [15]:
# simple if statement
a = 100
b = 101
if b > a: # observe the ':' after if block
print("b is greater than a") # Observe the print statment line indentation(4 spaces gap
b is greater than a
In [18]:
a = 100
b = 50
if b > a:
print("b is greater than a")
elif a == b: # elif keyword is pythons way of saying "if the previous
print("a and b are equal") # conditions were not true, then try this condition".
else: # else keyword catches anything which isn't caught by the preceding conditions
print("a is greater than b")
a is greater than b
Explanation
1. First if condition is checked, if it meets the requirement then code under if block is executed.
2. If it fails the requirement of first if condition, then it goes to next condition which is elif.
3. If it meets the requirement of elif condition, it executes code inside elif, otherwise it goes to final else block.
For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
In [19]:
India
China
USA
UK
Russia
In [20]:
for i in "Galaxy":
print(i)
In [21]:
for i in "Galaxy":
if i == 'x': # once i reaches x in 'Galaxy', it will come out of the loop
break # break stop the loop before it has looped through all the i
else:
print(i)
In [22]:
# continue statement---> we can stop the current iteration of the loop, and continue with t
for i in "Galaxy":
if i == 'x': # once i reaches x in 'Galaxy', it will skip the current iteration
continue
else:
print(i)
While loop
While loop ---> we can execute a set of statements as long as a condition is true.
In [4]:
i = 0
while i < 5:
print("Python is cool language.")
i += 1
In [5]:
count = 0
while True:
print("Java is also cool.")
count += 1
if count == 5:
break
In [6]:
i = 0
while i < 5:
print("Python is cool language.")
i += 1
else:
print("Python is more than cool language.") # With the else statement we can run a bloc
# once when the condition no longer is tru
Functions in Python
A function is a block of code which only runs when it is called.
In [7]:
# I have used print in the function so I don't need to define a variable here, just call fu
cloudyfunc()
In [8]:
# Here I will use return in the same function cloudyfunc and see how it works
cloudy # print cloudy here(in jupyter or colab, no need to use print in such condition)
Out[8]:
In [10]:
MLfunc("cloudy", "ML")
cloudy ML
In [12]:
def recursive_function(some_num):
if some_num > 0:
result = some_num + recursive_function(some_num - 1)
else:
result = 0
return result
result = recursive_function(5)
result
# Explanation
# WHen i passed 5, 5>0, so if block code will be executed and result = 5 + recursive_functi
# for value 4 as argument, 4>0, again if block will be executed, result = 4 + recursive_fun
# for value 3 as argument, 3>0, again if block will be executed, result = 3 + recursive_fun
# for value 2 as argument, 2>0, again if block will be executed, result = 2 + ecursive_func
# for value 1 as argument, 1>0, again if block will be executed, result = 1 + ecursive_func
# for 0, if block condition will fail and else block will be executed where result = 0
Out[12]:
15
List comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the values of an
existing list.
In [17]:
print(num_list)
print(letter_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [18]:
Out[18]:
['U', 'i', 'e', 'a', 'e', 'o', 'A', 'e', 'i', 'a']
In [20]:
for i in name:
if i in ['a', 's']:
my_list.append(i)
my_new_list = [i for i in name if i in ['a', 's']] # 4 line of code merged in this one l
print("Short approach using list comp =",my_new_list)
Normal method way = ['a', 'a', 's', 'a', 'a', 'a', 'a']
Short approach using list comp = ['a', 'a', 's', 'a', 'a', 'a', 'a']
In [29]:
some_num = 10
another_num = 5.6
ist_of_num = [1,2,3,4]
print(math.prod(list_of_num)) # returns product of all numbers in an iterable
# there are many such functions in math library, for more information click the below link.
22026.465794806718
3.1622776601683795
24
8.0
For more math library function, click here --> Click here (https://www.w3schools.com/python/module_math.asp)
That's all for Python basics. For any kind of feedback regarding this notes, you
can talk to your Mentors.
In [ ]: