Skip to main content

simple coding ( variable, string, list, tuple, Dictionary, set)

1. list directory

code:

import os
print(os.listdir())

O/P:

print your current directory

2.Data type in python

code:

# Printing the variables
print(a)
print(b)
print(c)
print(d)

# Printing the type of variables
print(type(a))
print(type(b))
print(type(c))
print(type(d))

O/P:

avi

345

45.32

True

<class 'str'>

<class 'int'>

<class 'float'>

<class 'bool'>

3. Operator
code:
a = 3
b = 4

# Arithmetic Operators
print("The value of 3+4 is ", 3+4)
print("The value of 3-4 is ", 3-4)
print("The value of 3*4 is ", 3*4)
print("The value of 3/4 is ", 3/4)

# Assignment Operators
a = 34
a -= 12
a *= 12
a /= 12
print(a)

# Comparison Operators
# b = (14<=7)
# b = (14>=7)
# b = (14<7)
# b = (14>7)
# b = (14==7)
b = (14!=7)
print(b)

# Logical Operators
bool1 = True
bool2 = False
print("The value of bool1 and bool2 is", (bool1 and bool2))
print("The value of bool1 or bool2 is", (bool1 or bool2))
print("The value of not bool2 is", (not bool2))

O/P:

The value of 3+4 is  7

The value of 3-4 is  -1

The value of 3*4 is  12

The value of 3/4 is  0.75

22.0

True

The value of bool1 and bool2 is False

The value of bool1 or bool2 is True

The value of not bool2 is True

4. input fuctions

code:

a = input("Enter a number: ")
a = int(a) # Convert a to an Integer(if possible)
print(type(a))

O/P:

Enter a number: 21

<class 'int'>

5. sum of two number

code:

a = input("Input 1st Number = ")
b = input("INput 2nd Number = ")
a = int(a)
b = int(b)
print("the sum of 1st and 2nd number is =", a+b)

O/P:

Input 1st Number = 25

INput 2nd Number = 20

the sum of 1st and 2nd number is = 45

6. Remainder after dividing

code:

a = 45
b = 30
%= gives reaminder
print("the remainder when a diveded by b",a%b)

O/P:

the remainder when a diveded by b 15

7. average of two number

code:

a = input("Enter first number: ")
b = input("Enter second number: ")
a = int(a)
b = int(b)
avg = (a + b)/2
print("The average of a and b is", avg)
O/P:
Enter first number: 6
Enter second number: 12
The average of a and b is 9.0

8. Slicing

code:

name = "avinash"
b = "is very good boy."

print(name+b)

print(name[-7]) #printed the letter which is 1st place that is a
# print(name[-1]) #printe the letter last letter ie. h
# print(name[2])
# print(name[3])
print(name[-2])

print(name[0:3]) #print the letter avi
print(name[-7:-1]) #print letter aninas
print(name[-7:])    #print letter avinash
print(name[1:4]) # print letter vin
print(name[-4:-1]) # print letter nas

print(b[1::3]) #print every 3rd latter
print(b[-17]) # print first letter
print(len(b)) #print how many string are there= 17 

print(b.endswith("boy.")) #string ended with that letter if yes then true otherwise false
print(b.count('o'))      # count letter how many times appear
print(b.capitalize())     #capitalize fist letter
print(b.find("very"))   #find number of first letter of string
print(b.replace('good', "bad")) # replace good with bad

O/P:

avinashis very good boy.

s     

avi   

avinas

avinash

vin

nas

se ob.

i

17

True

3

Is very good boy.

3

is very bad boy.

9. String Fuctions

code:

story = "once upon a time there was a youtuber  who uploaded python course with notes Avi"

# String Functions
print(len(story))
print(story.endswith("avi"))
print(story.count("a"))
print(story.capitalize())
print(story.find("upon"))
print(story.replace("Avi", "Code With avi"))
O/P:
93
True
7
Once upon a time there was a youtuber named harry who uploaded python course with notes avi
5
once upon a time there was a youtuber named Code With Harry who uploaded python course with notes Code With Avi

10. Escape Sequence

code:

= "avinash is very \nvery \tcleaver boy"   #\n new line print /t leave space between word
print(b)

O/P:

avinash is very 

very    cleaver boy

11. 

code:

= input("input your name ")
print("Good afternoon Mr.",a)
O/P:
Good afternoon Mr. avi

12.Letter

code:

letter = '''Dear <|Name|>,
Greeting from ABC coding institute. You are selected for Executive
congratulation!
Have a great day ahead!
Thanks and regards
<|Date|>
'''
name = input("input your name\n")
date = input("enter date\n")
letter = letter.replace('<|Name|>',name)
letter = letter.replace('<|Date|>',date)
print(letter)

O/P:

Dear aviator,

Greeting from ABC coding institute. You are 

selected for Executive

congratulation!

Have a great day ahead!

Thanks and regards

12-12-2021

13.Finding double space

code:

st = "This is a string with double  spaces"

doubleSpaces = st.find("  ")
print(doubleSpaces)

O/P: 28

14. replace 2 space with single space

code:

st = "This is a string with double  spaces  ok"

st = st.replace("  ", " ")
print(st)

O/P: This is a string with double spaces ok

15. List

code:

# Create a list using []
= [1, 2 , 4, 56, 6]

# Print the list using print() function
print(a)

# Access using index using a[0], a[1], a[2]
print(a[2])

# Change the value of list using
a[0] = 98
print(a)

# We can create a list with items of different types
= [45, "avi", False, 6.9]
print(c)

O/P:

[1, 2, 4, 56, 6]

4

[98, 2, 4, 56, 6]

[45, 'avi', False, 6.9]

16. slicing of List

cocd:

friends = ["Avi", "Tom", "Rohan", "Sam", "Divya", 45]
print(friends[0:4])
print(friends[-4:])

O/P:

['Avi', 'Tom', 'Rohan', 'Sam']

['Rohan', 'Sam', 'Divya', 45]

17. List Methods

code:

l1= [1, 8, 7, 2, 21,] 
print(l1)
l1.sort() #sort the list
l1.reverse() #reverse the list
l1.append(45) #adds 45 at the end of the list
l1.insert(2,544) #inserts 544 at the index 2
l1.pop(1)     #remove element at index 2
l1.remove(21) #remove element 21
print(l1)

O/P:

[1, 8, 7, 2, 21]

[1, 2, 7, 8, 21]

[21, 8, 7, 2, 1]

[21, 8, 7, 2, 1, 45]

[21, 8, 544, 7, 2, 1, 45]

[21, 544, 7, 2, 1, 45]

[544, 7, 2, 1, 45]

18. Tuple

code:

# Creating a tuple using ()
= (1, 2, 4, 5)

# t1 = () # Empty tuple
# t1 = (1) # Wrong way to declare a Tuple with Single element
t1 = (1,) # Tuple with Single element
print(t1)

#Printing the elements of a tuple
print(t[0])

#Cannot update the values of a tuple
#t[0] = 34 # throws an error

O/P:

(1,)

1

19.  tuple method

code:

# Creating a tuple using ()
= (1, 2, 4, 5, 4, 1, 2,1 ,1)

print(t.count(1))
print(t.index(5))

O/P:

4

3

20. store List

code:

f1 = input("Enter fruit number 1 ")
f2 = input("Enter fruit number 2 ")
f3 = input("Enter fruit number 3 ")
f4 = input("Enter fruit number 4 ")
f5 = input("Enter fruit number 5 ")
f6 = input("Enter fruit number 6 ")
f7 = input("Enter fruit number 7 ")

myFruitList = [f1, f2, f3, f4, f5, f6, f7]
print(myFruitList)

O/P:

Enter fruit number 1 Mango

Enter fruit number 2 Banana

Enter fruit number 3 Orenge

Enter fruit number 4 Apple

Enter fruit number 5 Grapes

Enter fruit number 6 ShrgarCane

Enter fruit number 7 Cucumber

['Mango', 'Banana', 'Orenge', 'Apple', 'Grapes', 'ShrgarCane', 'Cucumber']

21. tuple test cannot chage

code:

= (2,4,5,3,2)
a[0] = 45

O/P:

TypeError: 'tuple' object does not support item assignment

22. sum of List

code:

= [2, 4, 56, 7]

print(a[0] + a[1] + a[2] + a[3])
print(sum(a))

O/P:     69

            69

23. count  number in tuple

code:

= (7, 0, 8, 0, 0, 9)

print(a.count(0))

O/P:  3

24. fav Languge Dict

code:

mydict = {
    "Fast": "In a Quick Manner",
    "Avi": "A coder",
    "Marks": [1, 2, 3, 4],
    "anotherdict": {'AVo': 'Player'}
}

print(mydict['Fast'])
print(mydict['Avi'])
print(mydict['Marks'])
print(mydict['anotherdict']['AVo'])

mydict["Marks"]= [2, 0, 2, 3]
print(mydict["Marks"])

O/P:

In a Quick Manner

A coder

[1, 2, 3, 4]

Player

[2, 0, 2, 3]

25. Dict method

code:

mydict = {
    "Fast": "In a Quick Manner",
    "Avi": "A coder",
    "Marks": [1, 2, 3, 4],
    "anotherdict": {'AVo': 'Player'},
    1:2
}
print(list(mydict.keys()))   #prints the keys of the dictionary
print(mydict.values())     #prints values of the dictionay
print(mydict.items())     #prints (keys,values)
print(mydict)
updateDict = {
    "lovish": "friend",
    "divya": "pooja"
}
mydict.update(updateDict)  #pudates the dictionary by adding key-value pairs
print(mydict)

print(mydict.get('Avi2'))  #Returns None as avi2 is not present in the dictionary
print(mydict['Avi2'])    #throws an error as avi2 is not present in the dictionary

O/P:

['Fast', 'Avi', 'Marks', 'anotherdict', 1]

dict_values(['In a Quick Manner', 'A coder', [1, 2, 3, 4], {'AVo': 'Player'}, 2])

dict_items([('Fast', 'In a Quick Manner'), ('Avi', 'A coder'), ('Marks', [1, 2, 3, 4]), ('anotherdict', {'AVo': 'Player'}), (1, 2)])

{'Fast': 'In a Quick Manner', 'Avi': 'A coder', 'Marks': [1, 2, 3, 4], 'anotherdict': {'AVo': 'Player'}, 1: 2}

{'Fast': 'In a Quick Manner', 'Avi': 'A coder', 'Marks': [1, 2, 3, 4], 'anotherdict': {'AVo': 'Player'}, 1: 2, 'lovish': 'friend', 'divya': 'pooja'} 

26.  Set 

code:

a= {1, 3, 5, 6, 1}
print(type(a))
print(a) #set dont have repeat item

O/P:

<class 'set'>

{1, 3, 5, 6}

27. Empty Set

code:

# Important: This syntax will create an empty dictionary and not an empty set
= {}
print(type(a))

# An empty set can be created using the below syntax:
= set()
print(type(b))

O/P:

<class 'dict'>

<class 'set'>

28. Set method

code:

b= set()
print(type(b))

#adding values to an empty set
b.add(4)
b.add(5)
b.add(7)
b.add(4) #adding value repeatedly does not change a set
print(b)
b.add((9,8,3,1))
# b.add({4:5}) #cannot add list or dictionary
print(b)

print(len(b)) #prints lenth of this set
b.remove(5)
print(b)

O/P:

<class 'set'>

{4, 5, 7}

{(9, 8, 3, 1), 4, 5, 7}

4

{(9, 8, 3, 1), 4, 7}

29.  finding value of  key in Dict

code:

myDict = {
    "Pankha": "Fan",
    "Dabba": "Box",
    "Vastu": "Item"
}
print("Options are ", myDict.keys())
= input("Enter the Hindi Word\n")
# print("The meaning of your word is:", myDict[a])

# Below line will not throw an error if the key is not present in the dictionary
print("The meaning of your word is:", myDict.get(a))
O/P:
Enter the Hindi Word
Dabba
The meaning of your word is: Box

30. empty  dict and empty set

code:

= {}      #this syntax create empty dictionary
print(type(a))

#empty set can be create by following way
= set()
print(type(b))
b.add(4)
b.add(5)
print(b)

O/P:

<class 'dict'>

<class 'set'>

{4, 5}

31. fav lang Dict

code:

favLang = {}
= input("Enter your favorite language Shubham\n")
= input("Enter your favorite language Ankit\n")
= input("Enter your favorite language Sonali\n")
= input("Enter your favorite language Harshita\n")
favLang['shubham'] = a
favLang['ankit'] = b
favLang['sonali'] = c
favLang['harshita'] = d
favLang['shubham'] = a

print(favLang)

O/P:

Enter your favorite language Shubham English

Enter your favorite language Ankit Marathi

Enter your favorite language Sonali Hindi

Enter your favorite language Harshita German

{'shubham': 'English', 'ankit': 'Marathi', 'sonali': 'Hindi', 'harshita': 'German'}


32. 

code:O/P:

1.

code:

O/P:

1.

O/P:

1.

O/P:

1.

O/P:

1.

O/P:

1.

O/P:

1.

code:

O/P:

1.

code:

O/P:

1.

code:

O/P:

1.

code:

O/P:

1.

code:

O/P:

1.

code:

O/P:

1.

code:

O/P:

1.

code:

O/P:

1.

code:

O/P:

1.

code:





Popular posts from this blog

deploying Machine learning Model : pkl, Flask,postman

1)Create model and train          #  importing Librarys         import pandas as pd         import numpy as np         import matplotlib . pyplot as plt         import seaborn as sns         import requests         from pickle import dump , load         # Load Dataset         url = "http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"         names = [ "sepal_length" , "sepal_width" , "petal_length" , "petal_width" , "species" ]         # Loading Dataset         df = pd . read_csv ( url , names = names )         df . tail ( 11 )         df . columns         test = [         { 'sepal_length' : 5.1 , 'sepal_width' : 3.5 , 'peta...

Binomial Distribution

  The binomial distribution formula is:                                                    b(x; n, P) =  n C x  * P x  * (1 – P) n – x Where: b = binomial probability x = total number of “successes” (pass or fail, heads or tails etc.) P = probability of a success on an individual trial n = number of trials Note:  The binomial distribution formula can also be written in a slightly different way, because  n C x  = n! / x!(n – x)! (this binomial distribution formula uses factorials  (What is a factorial? ). “q” in this formula is just the probability of failure (subtract your probability of success from 1). Using the First Binomial Distribution Formula The binomial distribution formula can calculate the probability of success for binomial distributions. Often you’ll be told to “plug in” the numbers to the  formul...

cammand for installing library in python

 Command for installing in jupyter notebook:                pip install library_name                ex. pip install nump installing from anaconda prompt:           1. pip install numpy           2.   conda install -c conda-forge matplotlib search for conda command for matplotlib and go to official website. Installing from anaconda navigator easy. Somtime give error then open as administrator