Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Thursday, November 5, 2020

Five Unbelievable Facts About Python

Dear Readers,

Here I would like to Share 5 amazing or unbelievable facts about python programming language which you might haven't noticed yet!!


picture depicting unique facts in python











So without Wasting your time lets just jump to the facts:

1. What if I said you to compare your name with your best friends name ,sounds illogical right?:

---> Well in python you can actually compare strings based on lexicographic values(comparing dictionary order wise)

1
2
>>'abc' < 'adc'
True

True (since d comes after b if seen alphabetically)

2. Do you really want to know BTS(behind the scenes ) in python programming?: 

--->Well dis module is there for your aide (it means disassemble ) so it disassembles your code into human readable format and lets you know what your interpreter is doing 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import dis
def hello():
    print('Hello')

print(dis.dis(hello))

#Output:
  3           0 LOAD_GLOBAL              0 (print)
              2 LOAD_CONST               1 ('Hello')
              4 CALL_FUNCTION            1
              6 POP_TOP
              8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
None

For more info click me!

3. We can compare tuples and lists also in python(for coders):

--->

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
3,4,5 < 6,7,8
(3, 4, True, 7, 8)
# here our interpreter takes it as 3,4,(5<6),7,8
# hence we use 
>>> (3,4,5)<(5,3,7)
True
>>> (3,4,5)<(2,1,9)
False
# so majority wins more i.e more trues make # output true
# similarly you can use lists
>>>[1,2,3]<[2,3,4]
True

4. How would you take logical interpretation for True or False statements?, 

--->Well our Python has something for us in that case

In python any value not equal to zero(in number terms) is true and you can use True in place of 1 as well and None,0,'',[],{},(),etc depict False 

1
2
3
4
5
>>> True == 1
True
>>> True is 1
False
# they share equal values but they are not same

5.How should you code, or what should be the format?

---> Well guess what guys python solved this as well with the zen of python

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

So guys I hope you enjoyed it reading this blog as much as I enjoyed Writing it please comment and subscribe for more such blogs on regular basis. Also you can check more of my blogs like random module in python, simple calculator

Wednesday, November 4, 2020

String Formatting-3

 String Formatting-3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
1. endswith()-to check whether string ends with a particular character(case sensitive)

-->print('numpy'.endswith('y'))

-->True

2. find()/index()- method finds the first occurrence of the specified value,returns -1 if not found,almost like index method.

-->print('Debug'.find('b'))

-->2

-->print('Debug'.find('s'))

-->-1

-->print('Debug'.index('s'))

-->ValueError



3. replace()- This method replaces a specified phrase with another specified phrase.

-->print('hi there'.replace('hi','hello'))

-->hello there



4. split()-splits a string into list,based on a seprator(default string).

-->print('harsh'.split())

-->['harsh']

-->print('h,a,r,s,h'.split(','))

-->['h','a','r','s','h']



5. join()-joins a iterable into string,using a seprator(default string).

-->print(','.join(['h','a','r','s','h']))

-->'h,a,r,s,h

String Formatting-2

 String Formatting-2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
1. isalpha()-to check whether string has only alphabets

-->print('alpha'.isalpha())

-->True



2. isdigit()-to check whether string has only digits

-->print('1010'.isdigits())

-->True



3. isspace()-to check whether string has only spaces

-->print('   '.isspace())

-->True



4. center()-this will center align the string ,using specified character(space is default) as a fill character

-->print('Python'.center(10,'*'))

-->**Python**



5. startswith()-to check whether string starts with a particular character(case sensitive)

-->print('numpy'.startswith('n'))

-->True

String Formatting-1


String Formatters

Part -1

Dear Readers ,
today I would like to share about string formatter in python and I have them all in this single blog,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Important string operations-1

1. len()-to evaluate the length of a string

-->print(len('sample'))

-->6



2. str()-create new string object from given object

-->print(type(str(6)))

-->'<class 'str'>'



3. lower()-to covert a string to lowercase

-->print('HI'.lower())

-->hi



4. upper()-to covert a string to uppercase

-->print('hi'.upper())

-->HI



5. strip()-strip the spaces in input there are two subtype's lstrip and rstrip also

-->print('  Python  '.strip())

-->Python

-->print('  Python'.lstrip())

-->Python

-->print('Python  '.rstrip())

-->Python

Tuesday, November 3, 2020

Calculator



 Calculator

Dear Readers,

Today I would share a super cool application of python programming
by making a calculator:

==>1. Our function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def operator_func(selection,a,b):
    if selection =='add':
        return a+b
    elif selection =='sub':
        return a+b
    elif selection =='multiply':
        return a+b
    elif selection =='divide':
        try:
            return a/b
        except ZeroDivisionError as e :
            error = f'error occured :{e}'
            return error

==>2.Here we select our operator and numbers:

1
2
3
operator = input('select:\n1.add\n2.subtract\n3.multiply\n4.divide\n')
num1 = int(input('enter number_1\n'))
num2 = int(input('enter number_2\n'))

==>3.We get the value attached to the keys of the operator_dict using get method:

1
2
operator_dict ={'1':'add','2':'sub','3':'multiply','4':'divide'}
selection = operator_dict.get(operator,'select valid operator')

==>4.Get our answer:

1
print(f'your answer is :\n{operator_func(selection,num1,num2)}')

Sunday, November 1, 2020

OS & SYS

System Module  and OS Module 

     Its Important Functionalities
 

Dear Readers,
Today I would like to share major functionalities from OS and SYS module,
Function of OS module is that it allows the user(you) to interact with the operating system of your device:

1.os.name

==>This helps to get the information on current operating system of your device
1
2
>>> os.name
'nt'

2.os.getcwd()

==>This Function os.getcwd(), returns the Current Working Directory(CWD) of the file used to execute the code, can vary from system to system.

1
2
>>> os.getcwd()
'C:\\Users\\Example\\OneDrive\\Desktop\\python playlist'

3. os.rename('existing_file_name','new_file_name')

==> This function is used to change the name of the file. The name of the file changes only if, the file exists and user has sufficient privilege permission to change the file.

1. sys.argv

 ==>This function returns a list of command line arguments passed to python script. The name of the script is always the item at index 0,and the rest of the arguments are stored at subsequent indices.

1
2
>>> sys.argv[0]
'C:\\Users\\Adarsh tiwari\\OneDrive\\Desktop\\python playlist\\test.py'

2. sys.exit

==>This causes the script to exit to either python console or the command prompt. This is a way of safe exit in case of generation of error

3.sys.path

==>This modules search paths can be identified using this function

1
2
>>> sys.path
['C:\\Users\\Adarsh tiwari\\OneDrive\\Desktop\\python playlist', 'C:\\Users\\Adarsh tiwari\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Adarsh tiwari\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Adarsh tiwari\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Adarsh tiwari\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Adarsh tiwari\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages']

4.sys.maxsize

==>This module returns the largest value an integer can take
1
2
>>> sys.maxsize
9223372036854775807

Saturday, October 31, 2020

swap nums

p> Dear readers,

Today we will try to perform swapping the numbers exercise in python, c and c++:

So there are two Logical ways used:

Logic 1:

Here :

1.copy elements from number_1 into a temporary variable 

2. copy number 2 to number_1 

3. copy number_1 from (temporary variable) to number_2

so example:

number_1 = 10

number_2 = 12

Step 1. temporary variable = 10

Step 2.number_1 = 12

Step3.number_2 = 10(from temporary  variable) 

number_1 = 12

and 

number_2 =10

Logic 2:

Note: This is more programmer oriented logic

1.number_1 = number_1 + number_2 ---> [1]

2.number_2 = number_1 - number_2 => using [1]: number_1 + number_2 - number_2 == number_1 --> [2]

3.number_1 = number_1 - number2 => using [2] and [1]:  number_1 +number_2 - number_1 == number_2 

example

number_1 = 10, number_2 = 12

1,number_1 = 10 + 12 = 22

2.number_2 = 22 - 12 = 10(10 + 12 - 12)

3.number_1 = 22 - 10 = 12(10 + 12 - (22 - 12))==>(34-22)==>(12)

number_1 = 12 ,number_2 = 12

Lets Code now

#1. Python

# swapping number logic
num1 = int(input('enter first number:\n'))
num2 = int(input('enter first number:\n'))
print(f'numbers before swap a:{num1} and b:{num2} ')
# Logic is used here
temp = num1
num1 = num2
num2 = temp
print(f'\nnumbers after swap a:{num1} and b:{num2} ')
#This is second Logic
num1 = int(input('enter first number:\n'))
num2 = int(input('enter first number:\n'))
print(f'numbers before swap a:{num1} and b:{num2} ')
num1 = num1 + num2
num2 = num1 - num2
num1 = num1 - num2
print(f'\nnumbers after swap a:{num1} and b:{num2} ')

#2.C++

#include <iostream>
using namespace std;

int main()
{
    int num1, num2, temp;

    cin >> num1 >> num2;
    cout << "Before swapping num1 = " << num1 << ", num2 = " << num2  << endl;
    //Logic is used here
    temp = num1;
    num1 = num2;
    num2 = temp;

    cout << "\nAfter swapping num1 = " << num1 << ", num2 = " << num2 << endl;
    //here is second Logic
    cout<<"\nTry with Second Logic:\n"<<endl;

    cin >> num1 >> num2;

    cout << "Before swapping num1 = " << num1 << ", num2 = " << num2  << endl;
    //Logic is used here
    num1 = num1 + num2;
    num2 = num1 - num2;
    num1 = num1 - num2;

    
    cout << "\nAfter swapping num1 = " << num1 << ", num2 = " << num2 << endl;

    return 0;
}

# C

#include<stdio.h>

int main(){
    int num1 ,num2,temp;
    printf("enter number1 and number2:\n");
    scanf("%d%d",&num1,&num2);
    printf("numbers before swap are num1 :%d num2:%d",num1,num2);
    // logic used here
    temp = num1;
    num1 = num2;
    num2 = temp;
    
    printf("\nnumbers after swap are num1 :%d num2:%d\n",num1,num2);
    //Second Logic
    printf("Try with the second Logic...\n");
    
    printf("enter number1 and number2:\n");
    scanf("%d%d",&num1,&num2);
    printf("numbers before swap are num1 :%d num2:%d",num1,num2);

    // logic used here
    num1 = num1 + num2;
    num2 = num1 - num2;
    num1 = num1 - num2;
    
    printf("\nnumbers after swap are num1 :%d num2:%d",num1,num2);


}

Wednesday, October 28, 2020

Random module

Random Module

 
Dear Readers,
todays post is on random module

                              Random Module Usage in Python

Importing necessary libraries from random module

from random import random,gauss,randrange,randint,sample,choice,choices,seed

# Use seed to get same random number again and again as the output, without seeding you would get varied output everytime you run the program.

seed(9)

# for getting a random floating number always less than one

print(random())

# for getting intergers we use randint and randrange ,randint(start_value,stop_value) and randrange(start_value,stop_value)

print(randint(0,9))
print(randrange(0,1000))

# get a random choice out of a list or a tuple using choice attribute , you can use choices to get a random sample as an output with specified size

list1 = ['a','b','c','d','e','f','g','h']
print(choice(list1))
print(choices(list1,k=4)) # here k means size of the output/or number of random selections to be made and ouput is in list format

# to get a gaussian number we use , gauss(mean,standard deviation) ['THIS IS OPTIONAL'] 

print(gauss(10,2.5))

# like random choices we can use random sample, like sample(list_name,size)

list2 = [1,2,3,4,5,6,7]
print(sample(list2,4)) # outputs list format only

Tuesday, October 27, 2020

Blogs

                       Regular Python Blogs

Dear Readers,

python blogs picture


I welcome you all to my blogs related to python programming language, I assure you it would be worth every second of your time you give to read my blogs . I would keep it short and regular so those who would love to get regularly updated would benefit the most out of my blogs.

SO, with a shining hope of learning on the way through my blogs for you and for me as well while writing them for you I urge you to keep learning and growing.

Linear Search algorithm

Linear Search Algorithm Dear Readers, In this Blog today I would Share about Linear Search Algorithm a must know for everyone whether you wa...