Data Types in Python -
print(100) #INT
print(3.14) #FLOAT
print("Abhii") #STRING
Here 100, 3.14, "Abhii" These are literal expressions
% modulus gives remainder(result)
print(16.0//4) #gives float value because of 16.0
#4.0
print(16//4) #result in integer
#4
print(2**3**2)# MEANS 2**(3**2) = 2**9 = 2*2*2*2*2*2*2*2*2
#512
Function Call -
The function can take any number of values but they return only a single value
def square(n): #this is a function
return n*n #this function returns n*n
xyz = 5
print(square(5)) #we call function here to solve problem
Statement and Expression -
#50+21 = expression
#71 = value
#int = type
x = 50+21 #this is a complete statement
Here 50+21 = expression
x = "hello"
y = "Abhii"
print(2 * len(x) + len(y)) #15
Updating variables -
x = 6
print(x)
x = x + 1 #here we update the x value 6 - 7
print(x)
Input -
name = input("What's Your name : ")
print("Hello",name)
Convert hours minutes and seconds -
str_seconds = input("Please enter the number of seconds you wish to convert")
total_secs = int(str_seconds)
hours = total_secs // 3600
secs_still_remaining = total_secs % 3600
minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining % 60
print("Hrs=", hours, "mins=", minutes, "secs=", secs_finally_remaining)
By default, the value of input is always Strings
Our First Turtle Program -
import turtle
wn = turtle.Screen()
alex = turtle.Turtle()
alex.forward(150)
alex.left(90)
alex.forward(75)
Repetition With a For Loop -
print("This will execute first")
for _ in range(3): #by this (3) each line both print statements will executes 3-3 times
print("This line will execute three times")
print("This line will also execute three times")
print("Now we are outside of the for loop")
Another example with turtle -
import turtle
wn = turtle.Screen()
elan = turtle.Turtle()
distance = 50
for _ in range(10):
elan.forward(distance)
elan.right(90)
distance = distance + 10
Importing Modules -
import random
#both can do same work
#from random import randrange, random
prob = random.random()
print(prob)
diceThrow = random.randrange(1,7) #include 1 but exclude 7 / last item = last - 1
#returns an int, one of 1,2,3,4,5,6
print(diceThrow)
import to make it available
Incremental Programming -
import turtle
import math
wn = turtle.Screen()
bob = turtle.Turtle()
bob.right(90)
bob.forward(50)
bob.left(90)
bob.forward(50)
bob.left(90)
bob.forward(90)
bob.left(90)
bob.forward(50)
bob.right(135)
dist = math.sqrt(50*50/2)
bob.forward(dist)
bob.right(90)
bob.forward(dist)
WEEK 1 ENDS HERE
WEEK 2 STARTS FROM HERE -
Strings -
a = "abhi" #this is string
#string always write in quotes
#to create multi line string we can store in """ """ .
LIST -
In List, we can store different/or the same type of data.
a = [ 1,"Abhii",3,6.9]
print(a)
print(type(a)) #this gives you the type of 'a'
TUPLES -
Tuples are immutables
my_tuple = (1,2,"Abhii") #tuples can store in '()'.
print(my_tuple) #
tup = () #tuple with zero item
print(tup)
INDEX -
s = "Abhii" #string indexing
print(s[0]) #means at 0th index value print = 'A'
print(len(s)) #to get how many no. of characters inside 's'
a = [1,2,3]
print(s[len(a)-1]) # to get the last item
print(s[-1]) # also means last index
Slice Operator -
si = (1,"Abhii",71,"Verma")
print(si[0:2]) # means 2nd index exluded
Concatenation -
list1 = ["Abhii","Verma","DevOps"]
print(list1 + [1,2,3]) # this is called concatination
print(list1 *3) #means repeat the list three times
Count and Index -
a = "this is a string"
print(a.count("i")) #shows how many times 3 comes in this string
z = [1,2,3,1,"Abhii",4]
print(z.count(1)) #shows '2' because '1' comes 2 times
a = "Counting the index"
print(a.index("o")) #getting the index of 'o'
Split and Join -
str = "this will become list"
sp = str.split()# now this string converted into list
print(type(sp)) #this will show list
print(sp) #shows in list format
stri = "this is string"
print(stri.split("i")) #removes the i character from the string
Join
a = ["Abhii","Verma","linux"]
jn = ':'
s = jn.join(a) # replace commas and quotes with colon
print(s)
Loops -
x = ["Lol","WTF","OMG",71]
for i in x :#this will print the list items one by one
print(i)
#loops over string
for abhi in "DevOps Linux":
print(abhi) # it print every character separately and iterate till last item
Accumulator Pattern -
num = [1,2,3,4,5,6,7,8,9]
accum = 0 # 1/1+2/..
for w in num :
accum = accum + w
print(accum)
Range Function -
for num in range (1,11):
print("Numbers :",num)
for num in range(5):
print(" From zero to Four ",num)
#prints numbers in list starting from 0-4
print(list(range(5)))
INDEX -
fruits = ["Abhii","Linux","Fedora","DevOps","Terraform"]
for i in range(5):
print(i,fruits[i]) #gives value + index number
WEEK 3 -
BOOLEAN EXPRESSIONS
These are either true or false
#True or False
print(True)
print(type(True)) #means boolean type
#booleans with operators
print(5==6) #false/true
print(6==6) #will return true or false
print(5!=6) #returns true
Logical Operator
x = 5
print(x>0 or x<10) # true because in or operator both or either one condition should be true
n = 25
print(n%2 == 0 and n%3 == 0 ) #both condition false so it prints false
IN and NOT IN Operator -
print("a" in "abhii") # returns true because 'a' is present in 'abhii'
print('s' in "abhii") # return false because 's' is not present in 'abhii'
print(' ' in "a") #returns true because by default empty string is present in every string
print('s' not in "Linux") # returns true because not means no present ? said yes so it prints 'True'
print('a' in ["abhii", "linux","DevOps"])# return false because in list it check for like only a in that particular string
print('a' in ["abhii", 'a',"linux","DevOps"])#returns true because single a is present there
Conditional Execution -
x = 15
if x % 2 == 0 : # modulus is remainder operator
print(x,"X is even")
else : #means otherwise
print("x is odd") # this condition executes this time
#
x = 14
if x % 2 == 0 : # modulus is remainder operator
print(x,"X is even") # this condition executes this time
else : #means otherwise
print("x is odd")
# another case
x = 14
if x % 2 == 0 : # modulus is remainder operator
print(x,"X is even") # this condition executes this time
else : #means otherwise
print("x is odd")
print("this always executes") # this condition always executes no matter what inside if else
Unary Selection, Nested Conditionals, and Chained Conditionals -
x = -10
if x < 0 :
print(x,"x is negative")
else :
print("X is positive")
else : # this cause an error because else only works if it has 'if' statemet for that.
print("this will produce error.")
#
NESTED
x = 10
y = 10
if x < y:
print("x is less than y")
else :
if x > y: # this is nesting #means condition inside condition
print("x is greater than y")
else:
print("x is equal to y")
Chained Condition -
x = 10
y = 10
if x < y:
print("x is less than y")
elif x > y: # t
print("x is greater than y")
else:
print("x is equal to y")
The Accumulator Pattern with Conditionals and Accumulating a Maximum Value -
nums = [1,3,7,9,68,69,71]
best_num = nums[0]
for n in nums :
if n > best_num:
best_num = n
print(best_num)
WEEK - 4
Sequence Mutation -
alist = ['a', 'b', 'c', 'd', 'e', 'f']
alist[1:3] = [] # here at index 1 and 2 changes with empty #exclude 3/last one
print(alist) #modify and remove the 'b' and 'c'
#
alist = ['a', 'd', 'f']
alist[1:1] = ['b', 'c'] # at index 1 there's 2 items so it appends & add 'b','c' next to 'a'
print(alist)
alist[4:4] = ['e'] #index 4 replaces with ''e''
print(alist)
# strings are immutable
greeting = "Hello, world!"
greeting[0] = 'J' # you cannot modify the strings # ERROR!
print(greeting)
Mutability -
fruit = ["banana", "apple", "cherry"]
print(fruit)
fruit[0] = "pear" # assign index 0 to 'pear'
fruit[-1] = "orange" # -1 means last index
print(fruit)
Operations over List -
lst = [1,2,3]
del lst[0] # remove 'o' index
print(lst)
#delete items in sequence
lst = [1,2,3,4,5,6]
del lst[1:4] # removes indexes - '1,2,3'
print(lst)
Object and reference -
a = 'abhii'
b = 'abhii'
print(a is b) #returns bool expression
Aliasing -
a = [81,82,83]
b = [81,82,83]
print(a is b)
b = a
print(a == b)
print(a is b)
a[0] = 5
print(b)
Cloning List -
a = [71,69]
b = a[:] #this will make clone of 'a'
print(b) #output same as a
print(a == b)
print(a is b)
b[0] = 5 #only list b will affect here
print(a) #original list
print(b) #modified list
Methods On List -
#append
lst = [] #creates an empty list
lst.append("Abhii") # append/adding element to the list
lst.append("Linux")
lst.append("Docker") # this is how we append the list
print(lst)
#insert
lst = [1,2,3]
lst.insert(1,69)# index 1 = 69 now
# insert doesn't replace it adding the element at the index you give to it and rest left elemts move step further
print(lst) # 1,69,2,3
print(lst.count(1)) # show the item how many times come
# count the element you give
#index
lst = [1,2,3]
print(lst.index(1)) #shows the index of the item
#reverse the list order
lst = [1,2,3,4,5]
lst.reverse()
print(lst)
#sort
lst = [69,1,71,22]
lst.sort()
print(lst) # items are arranged in ascending order
#remove
lst = [69,1,71,22]
lst.remove(1)
print(lst)# 1 removes from the list
#pop
lst = [69,1,71,22]
lastitem = lst.pop() #removes tha last item
print(lastitem)
print(lst)
Append Vs Concatenate -
lst = [71,69,68]
lst.append("Abhii") #add element at last
print(lst)
#concatinate
x = x+1
#same as
x += 1
conc = [2,3,4]
conc = conc + ["Abhii"] #concatinate list add element at last
print(conc)
Non - Mutating Methods On Strings -
st = "Linux"
print(st.upper()) #convert lower case to upper case
ll = st.lower() #conert upper into lower
print(ll)
Accumulator Pattern with Lists -
nums = [3, 5, 8]
accum = [] #creates an empty list
for w in nums:
x = w**2
accum.append(x) #now putting the x items into accum variable
# print(accum) #prints every list item till loop goes
print(accum)
#
alist = [4,2,8,6,5]
blist = [ ]
for item in alist:
blist.append(item+5)
print(blist)
x = [1,2,3]
y = x
x += [4,5] # here both list updates(x,y)
y = y + [6] #here only y list update
print(x)
print(y)
Summary -
Here we Understand the Data types, List, Function Calls, Input Taking, For Loop, Importing Module, Tuples, Slicing, Concatenation, Split, Join, Range, Index, Boolean Expressions, Operators, Conditional Execution(if/else), Nested/Chained conditions, Operations Over list, Aliasing, Append/Concatinate.
So this is all about the introduction/Basics of Python.