PYTHON BASICS FOR BEGINNER's (Part-1)
If we want to run a program line by line/command by command the we use
shell(IDLE python).
Variables:-
1.
var1=13
type(var1) #To get data type of variable
int
2.We cannot concatenate string and int data type together
_var1=20
name_var
='Anubhav'
print(name_var+_var1)
TypeError Traceback
(most recent call last)
<ipython-input-5-b3a762642e5b> in <module>
1 _var1=20
2 name_var='Anubhav'
----> 3 print(name_var+_var1)
3.
_var2=22
_var3=7
print(_var2+_var3)
print(_var2-_var3)
print(_var2*_var3)
print(_var2**_var3)
print(_var2/_var3)
print(_var2//_var3)
print(_var2%_var3)
291515424943578883.14285714285714331
4.
_var2=int(input('Enter the value
of _var2:'))
_var3=int(input('Enter
the value of _var2:'))
print(_var2+_var3)
print(_var2-_var3)
print(_var2*_var3)
print(_var2**_var3)
print(_var2/_var3)
print(_var2//_var3)
print(_var2%_var3)
Enter the value of _var2:22Enter the value of _var2:42618882342565.552
Type Casting:-
_var2=int(input('Enter
the value of _var2:')
Since when we input any value we get that is
converted into string that’s y we have to type cast the
Variable to change its data type. Otherwise we will
not get the result.
String Formatting:-
1.
_var1='Hello'
_var2='Anubhav'
_message1=_var1+_var2
print(_message1)
_message1=_var1+'
'+_var2
print(_message1)
_message=_var1+',
'+_var2+'.How are you?'
print(_message)
HelloAnubhavHello AnubhavHello, Anubhav.How are you?
2. Dot format Function:-
Syntax: _message2= ’{}, {}…..{}’.format(variable
1,variable 2…..variable N)
/*No. of closed
parentheses will be equal to no. of variables
_message2='{},{}.How
are you?'.format(_var1,_var2)
print(_message2)
Hello,Anubhav.How are you?
3. F function (Slly to dot format function):-
_message3=f'{_var1},
{_var2}.How are you?'
print(_message3)
Hello, Anubhav.How are you?
4. Functions in string:-
_message4='Anubhav Suman'
print(_message4)
print(type(_message4))
print(_message4.lower())
print(_message4.upper())
print(_message4.__len__())
print(len(_message4))
print(_message4.count('e'))
print(_message4.find('Suman')) #returns the index of first value
print(_message4[10]) #returns the value at 10th index
print(_message4[0:10])
Anubhav Suman<class 'str'>anubhav sumanANUBHAV SUMAN
131309uAnubhav Su
Control Flow & Indentation:-
As soon as we create a for loop and press enter a white space is created(TAB) that is called indentation.
1.
for i in
range(1,12):
print('Value of i:'+i)
TypeError Traceback (most recent call last)
<ipython-input-1-4468723e19b9> in <module>
1 for i in range(1,12):
----> 2 print('Value of i:'+i)
TypeError: can only concatenate str (not "int") to str
2.
for i in range(1,12):
print('Value
of i:'+str(i))
print('For loop completed')
Value of i:1Value of i:2Value of i:3Value of i:4Value of i:5Value of i:6Value of i:7Value of i:8Value of i:9Value of i:10Value of i:11For loop completed 3.
for _var1 in range(1,11): print('No.{} squared is {} and cube is {}'.format(_var1,_var1**2,_var1**3)) No.1 squared is 1 and cube is 1No.2 squared is 4 and cube is 8No.3 squared is 9 and cube is 27No.4 squared is 16 and cube is 64No.5 squared is 25 and cube is 125No.6 squared is 36 and cube is 216No.7 squared is 49 and cube is 343No.8 squared is 64 and cube is 512No.9 squared is 81 and cube is 729No.10 squared is 100 and cube is 1000 4.for _var1 in range(1,11): print(f'No.{_var1} squared is {_var1**2} and cube is {_var1**3}') No.1 squared is 1 and cube is 1No.2 squared is 4 and cube is 8No.3 squared is 9 and cube is 27No.4 squared is 16 and cube is 64No.5 squared is 25 and cube is 125No.6 squared is 36 and cube is 216No.7 squared is 49 and cube is 343No.8 squared is 64 and cube is 512No.9 squared is 81 and cube is 729No.10 squared is 100 and cube is 1000 Functions:-1. No arguments and no return type def add(): var1=int(input("Enter 1st no.:")) var2=int(input('Enter 2nd no.:')) var3=var1+var2 print("Sum:",var3) add()
Enter 1st no.:3
Enter 2nd no.:2
Sum: 5
2. With arguments and no return type def sub(var1,var2): var3=var1-var2 print("Sub:",var3) sub(12,4)
Sub: 8
3. With no arguments and return typedef mul(): var1=int(input("Enter 1st no.:")) var2=int(input('Enter 2nd no.:')) var3=var1*var2 return var3 var4=mul()print("Multi:",var4) or print("Multi:",mul())
Enter 1st no.:3
Enter 2nd no.:4
Multi: 12
4. With argument and return type def div(var1,var2): var3=var1/var2 return var3 print("Div:",div(12,4))
Div: 3.0
Input() Function and escape character:-Within input() function anything you will write it will consider it as a string. 1.var1='Hello' var2=input('Enter name:') print(var1+' '+var2) #print(var1,var2)
Enter name:anubhav
Hello anubhav
2.var1=int(input("Enter value:"))
type(var1)
Enter value:1244
Int
var1=input("Enter
value:")
type(var1)
Enter value:1234
str
3.
var1=input("Enter value:") var1=var1*2 print(var1)
Enter value:Anubhav
AnubhavAnubhav
4. var1="Anubhav is a \nvery good boy" print(var1)
Anubhav is a
very good boy
5.print('What\'s your name') # ‘\’using backslash single quote will work like a string
What's your name
6. print('''Anubhav suman''') #triple quote is used to print multi line string without using ‘\n’
Anubhav
suman
Modules:-If we want to use function again and again we can just make the module of that python file and save it for Further use.(The module must be saved inside the file ,were all ur .ipynb file is kept because it is not a part of the interpreter (isse interpreter ke saath compile ni kiya gya hai)). 1. Importing a function
import Functions #imported function from Functions.ipynb fileFunctions.add()
Enter 1st no.:2
Enter 2nd no.:3
Sum: 5
2. Slly,If we don’t want to write the module name always before the function to call it
from Functions
import mul
mul()
Enter 1st no.:2
Enter 2nd no.:3
6
3. If we don’t want to write the module name always before the
function to call it and to select all the functions from the module
from Functions
import *
add()
mul()
Enter 1st no.:1
Enter 2nd no.:2
Sum: 3
Enter 1st no.:3
Enter 2nd no.:4
12
IF,Else & Elif:-
1. If there is only 2 condition
name=input("Enter
ur name:")
age=int(input("Enter
ur age,{}:".format(name)))
print(age)
if age >= 18:
print("U are eligible to vote")
else:
print("Come after {}
years".format(18-age))
Enter ur name:Anu
Enter ur age,Anu:13
13
Come after 5 years
2. Simple prog.
#guess number 5
print("Please
guess a no. 1-10")
guess=int(input())
if guess < 5:
print("Please guess a higer
number")
guess=int(input())
if guess == 5:
print("Well done,ur guess is
correct")
else:
print("Sorry,you haven't guessed
the correct number")
elif guess >
5:
print("Please guess lower
number")
guess=int(input())
if guess == 5:
print("Well done,ur guess is
correct")
else:
print("Sorry,you haven't guessed
the correct number")
else:
print("You got it in first time")
Please guess a no. 1-10
7
Please guess lower number
2
Sorry,you haven't guessed the correct
number
Break & Continue:-
1. Break
name="Anubhav"
while True:
print("Enter name:")
name1=input()
if name1==name:
break
print('Thank you:'+name)
Enter name:
Anubha
Enter name:
asad
Enter name:
Anubhav
Thank you:Anubhav
2. while True:
print("Who are you:")
name=input()
if name != 'Anubhav':
continue
print("Hello,Anubhav,Enter
password'It\'s a fish':")
password=input()
if
password=='swordfish':
break
print("Accsess
Granted")
Who are you:
ABC
Who are you:
Anubhav
Hello,Anubhav,Enter password'It/'s a
fish':
fish
Who are you:
Anubhav
Hello,Anubhav,Enter password'It/'s a
fish':
swordfish
Accsess Granted
For Loop:-
1. Simple loop
for i in range(10):
print("i is now
{}".format(i))
i is now 0
i is now 1
i is now 2
i is now 3
i is now 4
i is now 5
i is now 6
i is now 7
i is now 8
i is now 9
2. In interval
for i in range(1,20,3):
print(f"i is {i}")
i is 1
i is 4
i is 7
i is 10
i is 13
i is 16
i is 19
3. Reverse order
for i in range(20,1,-2):
print(f"i is {i}")
i is 20
i is 18
i is 16
i is 14
i is 12
i is 10
i is 8
i is 6
i is 4
i is 2
4.
number='9,22,234,456,678,890'
for i in range(0,len(number)):
print(number[i]) #by
default in python the number is printed in new line
9
,
2
2
,
2
3
4
,
4
5
6
,
6
7
8
,
8
9
0
5.
number='9,22,234,456,678,890'
for i in range(0,len(number)):
if number[i] in
'0123456789': #'in' is used to compare
print(number[i],end='') #'end'
is used to print number in single line
922234456678890
#it is a string value not a integer value
6.
number='9,22,234,456,678,890'
cleannumber="
for i in range(0,len(number)):
if number[i] in '0123456789':
cleannumber=cleannumber+number[i]
newnum=int(cleannumber)
print(type(newnum))
print("The number is {}".format(newnum))
<class 'int'>
The number is 922234456678890
While Loop:-
1.
var=0 #var is int value since
var!='0'
while var<=10:
print(f"value of var is
{var}")
var=var+1
value of var is 0
value of var is 1
value of var is 2
value of var is 3
value of var is 4
value of var is 5
value of var is 6
value of var is 7
value of var is 8
value of var is 9
value of var is 10
2.
avail=['east','north','south']
choose=''
while choose not in avail: #'not
in' works same as'!='
choose=input("Enter
direction:")
print("Are u glad to come out of loop")
Enter direction:west
Enter direction:east
Are u glad to come out of loop
3.
avail=['east','north','south']
choose=''
while choose not
in avail:
choose=input("Enter direction:")
if choose == 'quit':
print('Game Over')
break
print("Are
u glad to come out of loop")
Enter direction:west
Enter direction:west
Enter direction:quit
Game Over
List:-
List is used to store
data similar like array. In list we use to access the particular value by its
index.
1. List can store different data types values.
print([1,2,3,4,5,6])
[1, 2, 3, 4, 5, 6]
print(['Hello',3.14,True,None,34])
['Hello', 3.14, True, None, 34]
2. Slicing ,we can select a particular range in list
animals =
['cat','bat','rat','elephant','dog']
print(animals)
['cat', 'bat', 'rat', 'elephant',
'dog']
animals[0:3:2]
['cat', 'rat']
animals[-1]
'dog'
animals[:] #[:]
means end to end of a list
['cat', 'bat', 'rat', 'elephant',
'dog']
3. Multidimensional List
var1=[[1,2,3],['dog','cat','rat','elephant',]]
var1
[[1, 2, 3], ['dog', 'cat']]
var1=[[1,2,3],['dog','cat','rat','elephant',]]
#a
whole single list is treated as on entity inside var1
var1[0][2]
3
4. Functions in List
spam=['cat','dog','cow']
spam.append('elephant')
['cat', 'dog', 'cow', 'elephant']
spam.insert(1,'rat') #we can give the index value also were we
want to insert in insert function
spam
['cat', 'rat', 'rat', 'dog',
'elephant']
var2=[3,6,42,-3,-76]
var2.sort()
var2
[-76, -3, 3, 6, 42]
Iterators:-
Iterator
represents the stream of data in which we want to retrieve the data one by one,
and for this iter() function is
used.
1.
string='1234567890'
my_iterator=iter(string) #if we
directly ask the iterator to give us the value it will not return the value
print(my_iterator) #rather
than it will return us the address location of the variable
<str_iterator object at
0x000001A3F65351D0>
2.
string='1234567890'
my_iterator=iter(string)
print(my_iterator)
print(next(my_iterator)) #next()
func. Is used to retrieve the data from the location
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
<str_iterator object at
0x000001A3F65719B0>
1
2
3
4
5
6
7
8
9
0
3.
string='1234567890'
for i in
iter(string):
print(i,end='')
1234567890
4.
_list=['mon','tue','wed','thrus','fri','sat','sun']
my_iter =
iter(_list)
for x in
range(0,len(_list)):
print(next(my_iter),end=' ')
mon tue wed thrus fri sat sun
5.
list1=['cat','dog','rat']
list2=['dog','cat','rat']
list1==list2 #the order must also be same in both the list if we want to make them equal, since the data is accessed via index of the list rather than it’s value
False
Dictionaries:-
It is also a
format for storing data similarly like list. It consist of two things KEY
& VALUE.
To access a
particular value we use to access the KEY
of that value.
1.
cat={'size':'fat','color':'grey','dispositon':'loud'}
print(cat)
{'size': 'fat', 'color': 'grey',
'dispositon': 'loud'}
cat={'size':'fat','color':'grey','dispositon':'loud'}
cat['color']
'grey'
3.
cat1={'size':'fat','color':'grey','dispositon':'loud'}
cat2={'color':'grey','size':'fat','dispositon':'loud'}
cat1==cat2 #the order doesn’t matter in dictionaries unlike list, since the data is accessed via key of the dictionaries rather than it’s value.
True
4. If we want to access all the values in the dictionaries then values()
func. is used .
spam= {'name':'Anubhav','gender':'male','age':22}
type('age')
for v in spam.values():
print(v)
Anubhav
male
22
5. If we want to access all the keys in the dictionaries then keys() func. is used .
spam= {'name':'Anubhav','gender':'male','age':22}
for v in spam.keys():
print(v)
name
gender
age
6. If we want to access all the items(keys and values both) in the
dictionaries then items() func. is used .
spam=
{'name':'Anubhav','gender':'male','age':22}
for v in
spam.items():
print(v)
('name', 'Anubhav')
('gender', 'male')
('age', 22)
7. Append a
value via program
bday={'Rahul':'Jan
1','Vivek':'Apr 21','Anubhav':'Sep 19'}
while True:
print('Enter the name:')
name=input()
if name=='':
break
if name in bday:
print(bday[name]+' is the birthday of
'+name)
else:
print("I don't have bday info
of"+name)
print("What's his/her bday?")
birthday = input()
bday[name]=birthday #value
is added in bday dictionary via key
print("Bday database is
updated")
Enter the name:
Anubhav
Sep 19 is the birthday of Anubhav
Enter the name:
Rahul
Jan 1 is the birthday of Rahul
Enter the name:
Ram
I don't have bday info ofRam
What's his/her bday?
Feb 17
Bday database is updated
Enter the name:
Vivek
Apr 21 is the birthday of Vivek
Enter the name:
Ram
Feb 17 is the birthday of Ram
Enter the name:
-----------------------------------------------------------------------------------------------------------------------------

Comments
Post a Comment