Basics of python

HelloWorld.py

print("Hello World !")

if_else.py

score = int(input("Enter your score: "));
if score >= 40 :
 print("Good score!");
elif score <= 30:
 print("Try again!");
elif score in range(31, 39) :
 print("average score!");
else:
 print("Enter valid integer!");

# task
x = int(input("Enter your experience if 5/10: "));
if x == 10 :
 print("Thankyou I appreciate it!");
elif x == 5 :
 print("Sorry for this experience!");
else :
 print("Enter valid choice");

 #challenge
 y = int(input("Rate the product experience between 1 and 5: "));
 if y == 1:
  print("Sorry to hear about your experience!");
 elif y == 2:
  print("We are trying to get better.");
 elif y == 3:
  print("Thanks");
 elif y == 4:
  print("We just missed the perfect rating from you.");
 elif y == 5:
  print("Happy to know that you loved our services.");
 else:
  print("Enter valid rating!");

Indents and Comments.py

# print("Shiva Tejaswini")
# print("I learn python")
x = 4 \
    + 5
print(x)
# way 1
print("Shiva Tejaswini \n I learn python")

# way 2
x = "Shiva Tejaswini \n I learn python"
print(x)

x = """Shiva Tejaswini
I learn python 
and this is way 3"""
print(x)

# hometask
x = """Errors are a part of programming
                        -Hitesh"""
print(x)
print("Hey there!")
x = "Hey there! \n Tejaswini here."
print(x)
x="""Hey there!
    Tejaswini here
    and I am learning python"""
print(x)

lists_tuples.py

#LISTS
myListOne = [5.8, "Tejaswini", 7, 10.2]
myListTwo = [55, 66, "Shiva"]
print(myListOne)
print(myListOne[1])
print(myListOne[1:])
print(myListOne[1:3])
mylistOne.append(3)
print(myListOne)
# to repeat elements twice in same order
print(myListOne * 2)
# to concatinate 2 lists
print(myListOne + myListTwo)
# to change an element
myListOne[1] = "John"
print(myListOne)

#Tuples-Read only list
myTupleOne = (4, 'hitesh', '5.6', 'Choudary')
myTupleTwo = (5, 2, 'Ram')
print(myTupleOne)
print(myTupleOne[1])
print(myTupleOne[1:3])
print(myTupleOne + myTupleTwo)
# TODO: NOT Valid
# myTupleOne[1] = 'Trello'
# print(myTupleOne)

myD.py

# myDOne = {
#     "One" :2,
#     "Two" :3,
#     3 : 2,
#     3 : "Ram",
#     3 : [1, 2, 3, 4]

myDOne = {
    "playerOne" : "LeBron",
    "playerTwo" : "Jordan",
    "playerThree" : "Kobe"
}
print(myDOne)
print(myDOne["playerTwo"])
print(myDOne.keys())
print(myDOne.values())
myDTwo = {
    1 : "shiva",
    2 : 5,
    "teju" : 3
}
print(myDTwo)

nums_strings.py

#numbers
bank_uid = 1234556
bank_balance = 455.0
# int - 44
# float - 44.0
# complex - i
# this is used to clear the memory space and delete that variable
del bank_uid, bank_balance

#strings
str = "HelloWorld!"
# print(str)
# print(str[1])
# print(str[3:5])
# print(str[3:])
# print(str + " Tejaswini")
# task
print(str[2:6])
# x = input("One: ")
# y = input("two: ")
# print(x + y)

# a = 5
# b = 6
# print(a + b)

take_input.py

# input("Enter a number: ")
# x = 4 + 4
# print(x)
# x = input("Enter a number: ")
# print(x)

# hometask
x = input("Enter a number: ")
y = input("Enter your fav color: ")
print(x,y)
# print(y)

variables_one.py

#!/usr/bin/python
bankAccount = 204938934

score = 2233
highScore = 334545
winnerName = "tejaswini"
winnerScore = 344545

#THE RESERVED WORDS
# and  exec  not
# as  finally  or
# assert  for  pass
#  break  from  print
# class  global raise
# continue  if  return
# def  import  try
# elif  is  with
# else  lambda  yield
# except

# x = y = z = 1

x, y, z = 4, 23, "Tejaswini"
print(y)

# Standard type of variables
# Numbers
# String
# List
# Tuple
# Dictionary

Level two

for_loop.py

print(list(range(0,6))) #range(start, stop, step)
print(list(range(0,6,1)))
print(list(range(0,20,2)))
print(list(range(1,20,2)))

# for var_name in big_sequence:
#     print(var_name)

num_list = list(range(0,20))

for i in num_list:
    print(i)
    print(i, end = ';')

for a in "tejaswini":
    print(a)
    print(a , end = ' ')
    print(a , end = ' ;')

superHeros = ["IronMan","BatMan","Captain.America"]
for hero in superHeros:
  print(hero)

loop_control_keywords.py

#TODO Break keyword:

# num_list = [12, 23, 42,45, 21, 53, 98,]
# user_input = int(input("Enter a number: "))
# #Check if the entered number is in list
# for num in num_list:
#     if num == user_input:
#         print("Match found")
#         break
# else:   #here else is out of if loop to avoid executing else statement every time when num == user_input
#     print("Match not found")
#
# #printing values of string till o is found
# for l in "HelloWorld":
#     if l == 'o':
#         break
#     else:
#         print("value is: ",l)

#TODO Continue keyword:it skips printing whenever the key value is matched
for l in "HelloWorld":
    if l == "o":
        continue  
    print("value is: ",l)

#TODO pass keyword-It is used when we want to recheck that loop again and give some inputs later.
for l in "HelloWorld":
    if l == "o":
        pass
    print("value is:",l)

rating_system.py

user_input = int(input("rate us between 1-5: "));
if user_input == 1:
     print("Sorry");
elif user_input == 2:
     print("We vl improve");
elif user_input == 3:
     print("thanks");
elif user_input == 4:
     print("Almost there");
elif user_input == 5:
     print("Happy");
else:
     print("Invalid choice");

while.py

score = 0
while score < 20 : #while(score<20):
    print("your score is: ",score, end=';\n')
    score = score + 1
print("Your loop ends here!", end=';') #to read document ctrl+print or anyother
range(0,5)
# user = 1
# while user == 1:
#     myI = int(input("Enter a number: "))
#     print("Number is : ", myI)
# print("End of loop")

dictionary.py

marvel_heros = {
    "Spiderman" : 70,
    "Ironman" : 80,
    "Thor" : 90
}
dc_heros = {
    "batman" : 75,
    "Flash" : 85,
    "Aquaman" : 68
}

print(marvel_heros.__len__())
print(len(marvel_heros))
# print(dc_heros.clear())
# print(dc_heros)

#TODO - MAPPING is passing on another dictinary
dc_heros.update(marvel_heros)
print(dc_heros)

#TODO - this is used in web develepment, especially while tackling problems down
#TODO " database such as firebase

myTags = ("Name","Last_Name","Age","Phone")
myDict = dict.fromkeys(myTags)
print("My Dictionary is %s" %str(myDict))

list_talks.py

marvel_Heros = ["thor", "hulk" ,"ironman", "captain_marvel"]
my_Details = ["Tejaswini", "Shiva", "Tejaswi", "chicky", "ninteen", "twentyOne"]
print(marvel_Heros[:2])

del(marvel_Heros[1])
print(marvel_Heros)
del my_Details[3]
print(my_Details)

marvel_Heros[2] = "batman" #this overwrites
print(marvel_Heros)

marvel_Heros.append("captain_marvel") #this appends at the end
print(marvel_Heros)

marvel_Heros.insert(0, "Hulk")#this inserts at specified location
print(marvel_Heros)

marvel_Heros.remove("Hulk")
print(marvel_Heros)

marvel_Heros.reverse()
print(marvel_Heros)

print(marvel_Heros.count("batman"))

marvel_Heros.extend(my_Details)
print(marvel_Heros)

py_math.py

print(abs(-3)) #absolute value is +ve of a num

import math
#donot include this lib just to perform abs
print(math.fabs(-3))

print(math.ceil(-45.12)) #ceil prints closet highest integer
print(math.ceil(200.12))

print(math.floor(-45.12)) #floor prints closet least integer
print(math.floor(200.12))

#TODO math lib supports power, logarithm, trigo, max and many.

print(max(22, 55, 44, 67, 87))
print(min(22, 33,44,55,66))
print(math.sqrt(25))

random_numbers.py

#In a simple login system user enters mail-id and we save him as a user.Here we create a unique id which is a combination of
#strings and numbers which is generated randomly and save in database, in games we try to generate random numbers
#import keyword is used to import code written by others and sometimes we have to install code manually
# to see options that can be imported (import ctrl+space)
import random

range(100) #By default it understands that frst parameter is 0
print(random.choice(range(100))) #choice automatically picks a random value in range

#TODO To build a dice game:
print(random.choice(range(1,7))) # 7 not included

print(random.choice([1, 2, 3, 4, 5, 6])) #list can be an argument
print(random.choice("ShivaTejaswini")) #String as input
#use ctrl+d to duplicate a line

#syntax random.randrange(start, stop, step)
print(random.randrange(1, 100, 2))
#TODO refer python.org for more info

print(random.random()) #it generates a number between 0 and 1 (DS & ML)
#but these are not truly random cuz there is a predictable algo behind them
#to control this use seed
random.seed(10)
print(random.random()) #it gives same result everytime yet random (scientific experiments) (to reproduce same randomness)
#if seed value is not set then it generates random sequence of number everytime we run
random.seed()
print(random.random())

random.seed(10)
print(random.randint(1, 100))

list_numbers = [11, 22, 33, 44 ,55]
# first shuffle then print
random.shuffle(list_numbers)
print(list_numbers)

string_talk.py

score = 2330
name = "Tejaswini"
print("Hey",name + ", Your score is",score)

print("Hey %s, Your score is %d" %('Tejaswini',233))

myStr = "Hello World"
print(myStr[:6] + "India")
print(myStr.lower())
myStr = myStr.lower()
print(myStr.islower())

#TODO to explore multiple such options string_name. and string_name.is

user_Input = "    Tejaswini    "
#sometimes we get user input with preceding and trailing spaces which is inefficient
# to store in database
print(user_Input.strip())
user_Input = "-------Tejaswini------"
print(user_Input.strip('-'))

tuples_talk.py

marvel_Heros = ("thor", "hulk" ,"ironman", "captain_marvel")
my_Details = ("Tejaswini", "Shiva", "chicky", "ninteen", "twentyOne")

email = ("Tejaswini",)#for single elements ending comma is must or else it is not a tuple
print(email)

heros = marvel_Heros + my_Details
print(heros)

dummy.py

num1 = 127.899
num2 = 3465.148
num3 = 3.776
num4 = 264.821
num5 = 88.081
num6 = 799.999
# Display each number in a field of 7 spaces with 2 decimal places.
print(format(num1, '7.2f'))
print(format(num2, '7.2f'))
print(format(num3, '7.2f'))
print(format(num4, '7.2f'))
print(format(num5, '7.2f'))
print(format(num6, '7.2f'))

Level Three

function_one.py

#we will learn something similar to creating our own print statement/function
#function - methods (They are interchangeable)
#Myth: if we define normally it's a function and if it is inside a class then it's a method.
# to define a function -> def function_name(): \n (1 or 2 or 4 spaces consistently)
#TODO WAY-1:

# def Tejaswini():
#     "function docString" # next line to def is usually this string and is skippable
#     print("I want to learn python")
#     print("I am doing it")
#     return
#Tejaswini() #unles we call the function it will not print anything

#print("_______")
#Tejaswini() #notice it prints all the statements in the function without rewriting them.

#TODO WAY-2
def greetings( name ):
    "function docString"
    print("Hello,", name)
    return
greetings("Tejaswini")
greetings(3) #Here it is accepting both strings and numbers it can be modified to accept either one of them.

#def user_creation(name, email, phone):
def user_creation(name, email, phone=0):
    print("Name is: ",name)
    print("Email is: ",email)
    print("Phone.no is: ",phone)
    return
#user_creation("Tejaswi", "ashivatejaswini@gmail.com", 8328674741)
user_creation("Tejaswi", "ashivatejaswini@gmail.com")
# we can check if the parameters given are str etc with django
#(in print statement we are not giving all the parameters like end = '\n' everytime we
#use print statement but after declaring phone not giving input gives error)
# in this it is compulsory to give 3 parameters defined
# This can be fixed
#TODO return marks a code as complete and in functions we always don't want to print statements
#but process them and give result so return is used.

main.py

import tejaswini
#we can install a lot of modules by pip install numpy and simply use code written by others.
print(tejaswini.addme(3,2))
val = tejaswini.addme(5,5)
print(val)
from tejaswini import addme #to import one specific functions
from tejaswini import * # to import all functions. If we import functions using this syntax then ,
#print(addme(3,2)) would do the job
import tejaswini
num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
print("Main Menu")
print("1.Addition,2.Subtraction,3.Multiplication")
x = int(input("Enter your choice (1-3): "))
if x == 1:
    print(addme(num1,num2))
elif x == 2:
    print(subme(num1,num2))
elif x == 3:
    print(mult(num1,num2))
else:
    print("Enter valid choice!")

multi_args.py

# To rename without loosing link(address)-refractor
def addme(num1, num2):
    total = num1 + num2
    return total
print(addme(3,2))

def addme1(*num): #to take n number of args
    total1 = 0 #initialize to 0 so there vl be no issue with garbage value
    for v in num:         #to iterate through all the nums and add them
        total1 = total1 + v
    return total1
print(addme1(3, 2, 1))
#challenge:1 init_price = 100 subtract the numbers user passes and give final price
def price_decrement(*n):
    init_price = 100
    for v in n:
        init_price = init_price - v
    return init_price
print(price_decrement(12,8))

#challenge 2 restrict such that only 2 args can be given
def price_decrement(*n):
    #init_price = 100
    if len(n) == 2:
        init_price = 100
        for v in n:
            init_price = init_price - v
        return init_price
    else:
        print("Only 2 args allowed!")
print(price_decrement(12,8))

my_dates.py

# time is a very imp module being imported especially when we have to maintain the current time of a record being entered in database.
import time
print(time.localtime())
localtime = time.asctime(time.localtime(time.time()))
print(localtime)

#challenge
import calendar
print(calendar.day_name[calendar.weekday(1947,8,15)])
print(calendar.day_name[calendar.weekday(2004,5,21)])

my_files.py

#In main file there is a function/method called main function it is the source entry point of any project.
# It is totally optional but it is a good practice while dealing with big projects.
#File handling can be done in many ways, most convinient way is through the third party libraries
#just like we can import time,calendar
def main():
    print("hey")
if __name__ == "__main__":
    main()
#this is considered as entry point
#https://stackoverflow.com/questions/419163/what-does-if-name-

my_lambda.py

#lambda function or single line or anonymous
#Syntax ex:var_name = lambda arg1,arg2 : arg1 + arg2
add = lambda num1,num2 : num1+num2
print(add(2,3))

blablabla.py

#How to create our own custom modules and import them
#Implementation:- some of the functionality is kept within the file and it works when called.
#variables, classes, functions, methods etc can beput in modules.
def addme(num1, num2):
    return num1+num2
def subme(num1,num2):
    return num1-num2
#create a file(main.py) in same directory(LevelThree) and can simple import tejaswini.
#if the given name is not in the directory it goes and checks the default python directory,
#whose address is given during installation.

def mult(num1,num2):
    return num1*num2

to be continued...