Python

Convert String to Float Convert String to Float

Python Convert String to Float

In Python, strings are byte sequences that represent Unicode characters. Due to the lack of a character data type in Python, a single character is just a one-length string. To access the string’s components, use square brackets. To generate strings in Python, single quotes, double quotes, and even triple quotes can be used.

This article will go over various methods to convert string to float.

Example:

Input:

'34.124'

Output:

34.124

String to Float Conversion

We’ll look at how to convert a number string to a float object .

Form conversion functions in Python are used to transform one data type to another. The aim of this article is to provide details on how to convert a string to a float. To convert a String to a float in Python, use the float() function.

Float()

Any data form can be converted to a floating-point number using this function.

Syntax:

float(object)

Only one parameter is accepted by the process, and it is also optional to use. The method returns 0.0 if no argument is transmitted.

Parameters:

  • An int, float, or string may be used.
  • If it’s a string, it has to be in the right decimal format.

Return:

  • It gives you a float object as a result.
  • ValueError will be raised if the given string contains something other than a floating-point representation of a number.
  • If no argument is given, 0.0 is returned.
  • Overflow Error is raised if the given statement is beyond the range of float.

Let’s look at some examples of how to convert a string to a float object using the float() function.

Assume we have a Str object with the string ‘34.124′. We’ll transfer the string to the float() function to convert it to a floating-point number, or float entity. Which returns the float object after converting this string to a float. As an example,

# Driver code

# given string value
stringval = '34.124'

# converting string to float
floatvalue = float(stringval)

# printing the float number
print(floatvalue)

# printing the type of the number
print('Type of the number/object :', type(floatvalue))

Output:

34.124
Type of the number/object : <class 'float'>

Convert a comma-separated number string to a float object

Let’s say we have a string called ‘34,123.454’  which includes the number but also some commas. It’s a little difficult to convert this type of string to float. If we transfer this to the float() function directly, we’ll get an error as below:

ValueError: could not convert string to float: '34,123.454'

float() returned an error since string contained characters other than digits. So, before passing the string to the float() function, we need to delete all the extra commas.

We use replace function to replace commas with blank character such that commas  are deleted

Below is the implementation:

# Driver code

# given string value
stringval = '34,123.454'

# convert string with comma to float
# replacing ,(comma) with blank value
floatvalue = float(stringval.replace(',', ''))

# printing the float number
print(floatvalue)

# printing the type of the number
print('Type of the number/object :', type(floatvalue))

Output:

34123.454
Type of the number/object : <class 'float'>

Related Programs:

Python Convert String to Float Read More »

Basics of Python – String

In this Page, We are Providing Basics of Python – String. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – String

String

Python can manipulate string, which can be expressed in several ways. String literals can be enclosed in matching single quotes (‘) or double quotes (“); e.g. ‘hello’, “hello” etc. They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple- quoted strings), e.g. ‘ hello ‘, “hello”. A string is enclosed in double-quotes if the string contains a single quote (and no double quotes), else it is enclosed in single quotes.

>>> "doesnt"
'doesnt'
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
' "Yes., " he said. '

The above statements can also be written in some other interesting way using escape sequences.

>>> "doesn\' t" ;
"doesn ' t”
‘>>> '\"Yes,\" he said.' 
' "Yes," he said.'

Escape sequences are character combinations that comprise a backslash (\) followed by some character, that has special meaning, such as newline, backslash itself, or the quote character. They are called escape sequences because the backslash causes an escape from the normal way characters are interpreted by the compiler/interpreter. The print statement produces a more readable output for such input strings. Table 2-12 mentions some of the escape sequences.

Escape sequence

Meaning

\n

Newline.
\t

Horizontal tab.

\v

Vertical tab.

 

Escape sequence

Meaning
W

A backslash (\).

Y

Single quote (‘).
\”

Double quote (“).

String literals may optionally be prefixed with a letter r or R, such string is called raw string, and there is no escaping of character by a backslash.

>>> str=' This is \n a string '
>>> print str 
This is 
a string
>>> str=r' This is \n a string '
>>> print str 
This is \n a string

Specifically, a raw string cannot end in a single backslash.

>>> str=r ' \ '
File "<stdin>", line 1 
str=r ' \ '
            ∧
SyntaxError: EOL while scanning string literal

Triple quotes are used to specify multi-line strings. One can use single quotes and double quotes freely within the triple quotes.

>>> line=" " "This is
. . . a triple
. . . quotes example" " "
>>> line
' This, is\na triple\nquotes example'
>>> print line
This is
a triple 
quotes example

Unicode strings are not discussed in this book, but just for the information that a prefix of ‘ u ‘ or ‘ U’ makes the string a Unicode string.

The string module contains a number of useful constants and functions for string-based operations. Also, for string functions based on regular expressions, refer to re module. Both string and re modules are discussed later in this chapter.

Python String Programs

Basics of Python – String Read More »

Python: How to get first N characters in a string?

This article is about finding the first N characters of String where the N represents any number or int value.

How to get the first N characters in a String using Python

As we know in Python String is a sequence of characters where the index numbers are associated with each character.

For example : We have a String variable named String_value which contains a String Technology i.e

String_value = “Technology”

Where the sequence number/index of the first character starts with 0 and it goes on. Like

Index of character ‘T’ = 0

Index of character ‘e’ = 1

Index of character ‘c’ = 2

Index of character ‘h’ = 3

Index of character ‘n’ = 4

Index of character ‘o’ = 5

Index of character ‘l’  = 6

Index of character ‘o’ = 7

Index of character ‘g’ = 8

Index of character ‘y’ = 9

In Python, with the help of the [ ] (Subscript operator or Index Operator) any character of the string can be accessed just by passing the index number within it.

Like String_value[i] will return i-th character of the string.

For example, String_value[4] will return character ‘n’.

Program to get first character of the String :

#Program:

String_value = "Technology"
First_char = String_value[0]
print('First character of the string is', First_char)
Output : 
First character of the string is T

Here, just by passing index position 0 in the operator [ ], we fetched the first character of the string.

Note : Like that by passing any index position in this [ ] operator, we can get the corresponding character of the string.

But next we have to find first N characters simply means a substring we have to return from the original string. So lets know how to achieve that.

Program to get first N characters of the String :

In the above example we just passed a single index position inside the subscript operator, beside this, the subscript operator can also take a range too.

Syntax :String_VariableName [Start_IndexPosition : End_IndexPosition : Step_Size]

Where,

  • Start_IndexPosition : It represents the index position from where it will start fetching the characters. (Here the default value is 0)
  • End_IndexPosition : It represents the index position upto which it will fetch the characters.
  • Step_Size : It represents the step value means interval between the characters.  (Here the default value is 0)

So, to get the first N characters of the string, we have to pass 0 as start index and N as the end index i.e 

String_value[0 : N]

So, it will return characters starting from 0-th index upto n-1-th index. And here default Step_Size is 0.

So Let’s do the program by using this substring concept.

#Program :

String_value = "Technology"
First_char = String_value[0:4]
print('First 4 characters of the string is', First_char)
Output :
First 4 characters of the string is Tech

Need to concern about Index Error :

When we are using index operator [ ] , we need to be careful about the index that we are passing. Because if we pass the index which does not exist in the string then it will give an error “string index out of range”.

#Program :

String_value = "Technology"
#Passing 25th index which is not present in string
First_char = String_value[25]
print('25-th character of the string is', First_char)
Output :
string index out of range

Let’s overview the complete program again 

#Program :

#Asking for string input
String_value = input()
#Asking for a number i.e N-th value
N=int(input())
#This line prints first character of the string as index passed is 0
First_char = String_value[0]
#Printing the first character
print('First character of the string is', First_char)
#It will find the substring from 0-th index to N-1-th index
First_char = String_value[0 : N]
#Printing the first N-th characters
print('First N-th character of the string is', First_char)
Output :
Technology
4
First character of the string is T
First N-th character of the string is Tech

Python: How to get first N characters in a string? Read More »

Python : How to Check if an item exists in list ?

How to Check if an item exists in list using Python?

In Python List is a most versatile datatype which stores multiple items in a single variable. All the items present inside a list are indexed where the first item is associated with the index position 0 (Zero). In this article we will discuss how to check whether the list contains a specific item or not. Let’s explore the concept in more detail.

Example of a List :

List_item = [ 'Bhubaneswar' , 'Mumbai' , 'Kolkatta' , 'Chennai' , 'Delhi' ]

So, our task is to check an item that is present in the list or not. Suppose we are looking for the item ‘Mumbai’ in List_item and it is present in the list but if we will look for the item ‘Goa’ that does not exist in the list named List_item.

There are multiple approaches available which can be used to achieve this. So, let’s discuss each approach one by one.

Method-1 : Checking if the item exists in the list using “in” operator

"in" operator in python can be used to check the item exists in the list or not. With the help of if condition it can check whether the item is present or not. If it is present in the list then it returns True and if it is not present in the list it returns False.

Syntax : item_name in list_name
#Program :

List_item = [ 'Bhubaneswar' , 'Mumbai' , 'Kolkatta' , 'Chennai' , 'Delhi' ]
#Checking an item which is present in the list
if 'Mumbai' in List_item:
    print('Item Mumbai is present')
else:
    print('Item Mumbai is not present')
#Checking an item which is not present in the list
if 'Goa' in List_item:
    print('Item Goa is present')
else:
    print('Item Goa is not present')
Output :
Item Mumbai is present
Item Goa is not present

Method-2 : Checking if the item exists in list using list.count() function

list.count() method gives the occurrence of an item in the list. Means if the item found at least once or more than that then the item is present if the item occurrence is zero then that item is not present in the list.

Synatx :  item_name.count(item)
#Program :

List_item = [ 'Bhubaneswar' , 'Mumbai' , 'Kolkatta' , 'Chennai' , 'Delhi' ]
#Checking an item which is present in the list
#Occurrence of Chennai is 1
if List_item.count('Chennai'):
    print('Item Chennai is present')
else:
    print('Item Chennai is not present')
#Checking an item which is not present in the list
#Occurrence of Pune is 1
if List_item.count('Pune'):
    print('Item Pune is present')
else:
    print('Item Pune is not present')
Output :
Item Chennai is present
Item Pune is not present

Method-3 : Checking if the item exists in list using any() function

Using any( ) function for checking a string is a most classical way of performing this task. With the help of any( ) function we can check if any item of given iterable is True or we can check for a match in a string with a match of each list item/element.

Syntax : any(condition)
Python :

List_item = [ 'Bhubaneswar' , 'Mumbai' , 'Kolkatta' , 'Chennai' , 'Delhi' ]

#Checking an item which is present in the list
#Checking any item whose length is 11 exist in the list or not
result = any(len(item) == 11 for item in List_item)
if result:
    print('Item Bhubaneswar is present')
else:
    print('Item bhubaneswar is not present')

#Checking an item which is not present in the list
#Checking any item whose length is 1 exist in the list or not
result = any(len(item) == 1 for item in List_item)
if result:
    print('Item found with length 1')
else:
    print('No Item found with length 1')
Output :
Item Bhubaneswar is present
No Item found with length 1

Method-4 : Checking if the item exists in list using ‘not in’ inverse operator

'not in' inverse operator in python is an inbuilt operator which returns True if the item is not present in the list and it returns False if the item is present in the list.

Syntax : item_name not in list_name
Program :

List_item = [ 'Bhubaneswar' , 'Mumbai' , 'Kolkatta' , 'Chennai' , 'Delhi' ] 
#Checking an item which is not present in the list
#It will result true because Goa is not present in list
if 'Goa' not in List_item: 
    print('True, Goa not in list') 
else :
    print('False, Goa is in list') 

#Checking an item which is present in the list 
#It will result false because Delhi is present in list
if 'Delhi' not in List_item: 
    print('True, Delhi not in list') 
else :
    print('False, Delhi is in list')
Output :
True, Goa not in list
False, Delhi is in list

Method-5 : Checking if the item exists in list using Naive method

The naive method is the most simplest way of checking the existance of an element as it iterates the through all the elements of the list. If the item found in the list then it return true.

#Program :

List_item = [ 'Bhubaneswar' , 'Mumbai' , 'Kolkatta' , 'Chennai' , 'Delhi' ] 
#Checking an item which is not present in the list
#It will result true because Kolkatta present in list

for i in List_item: 
    if i == 'Kolkatta':
        print("True")
Output :
True

Python : How to Check if an item exists in list ? Read More »

Find the index of value in Numpy Array using numpy.where()

How to find the index of value in Numpy array using numpy.where() in Python ?

NumPy or Numerical Python which is a general purpose array processing package and it is used for working with arrays. In python there numpy.where( ) function which is used to select elements from a numpy array, based on a condition and if the condition is satisfied we perform some operations.

Syntax : numpy.where(condition[ , x, y ])

Where

  • condition is a conditional expression which returns the Numpy array of bool
  • x,y are two optional arrays i.e either both are passed or not passed

In this article we will discuss about how to get the index of an element in a Numpy array (both 1D & 2D) using this function. So, let’s explore the concept well.

1. Find index of a value in 1D Numpy array :

Suppose array_one is an 1D Numpy array, So it will look like

array_one = np.array([10, 15, 20, 25, 30, 35, 40, 45, 50, 30, 60, 65, 70, 75, 80, 85, 30, 95])

Now, let’s find the index number of 30 in this Numpy array.

Program :

import numpy as np
# numpy array created with a list of numbers
array_one = np.array([10, 15, 20, 25, 30, 35, 40, 45, 50, 30, 60, 65, 70, 75, 80, 85, 30, 95])
# Get the index of elements with value 30
output = np.where(array_one == 30)
#printing the indices where the element 30 is present
print('Tuple of arrays returned : ', output)
print("Elements with value 30 exists at following indices", output[0], sep='\n')
Output :
Tuple of arrays returned :  (array([4, 9, 16]), )
Elements with value 30 exists at following indices 
[4 9 16]

As result is a tuple of arrays which contains the indices where value 30 exists in array array_one i.e. so it returned

(array([4, 9, 16]), )

And as a flat 1D array it returned

[4 9 16]

And if the element is not present in the Numpy array then returned array of indices will be empty. So let’s check that with an example

Program :

import numpy as np
# numpy array created with a list of numbers
array_one = np.array([10, 15, 20, 25, 30, 35, 40, 45, 50, 30, 60, 65, 70, 75, 80, 85, 30, 95])
# Get the index of elements with value 100
output = np.where(array_one == 100)
print('Tuple of arrays returned : ', output)
#printing the indices where the element 100 is present
#As 100 is not present in Numpy array i.e array_one so returned array with indices is empty 
print("Elements with value 30 exists at following indices", output[0], sep='\n')
Output :

Tuple of arrays returned : (array([  ]), )
Elements with value 30 exists at following indices
[  ]

2. Find index of a value in 2D Numpy array :

Suppose array_two is an 2D Numpy array, So it will look like

array_two = np.array([ [10, 15, 20], [25, 30, 35], [40, 45, 50], [30, 60, 65], [70, 75, 80], [85, 30, 95] ])

Now, let’s find the index number of 30 in this Numpy array.

Program :

import numpy as np
# numpy array created with a list of numbers
array_two = np.array([ [10, 15, 20], [25, 30, 35], [40, 45, 50], [30, 60, 65], [70, 75, 80], [85, 30, 95] ])
# Get the index of elements with value 30
output = np.where(array_two == 30)
#printing the indices where the element 30 is present
print('Tuple of arrays returned: ', output)
print("Elements with value 30 first exists at index:", output[0][0])
Output :
Tuple of arrays returned: (array([1, 3, 5]), array([1, 0, 1])) 
Elements with value 30 first exists at index: 1

Where,

First array [1, 3, 5] represents row indices where the element 30 is present

And the second array [1, 0, 1] represents column indices where the element 30 is present.

3. Get indices of elements based on multiple conditions in Numpy :

Example : 1

Get the indices of elements with value less than 20 and greater than 10.

Program :

import numpy as np
# numpy array created with a list of numbers
example_array = np.array([11, 6, 13, 8, 15, 16, 7, 15, 1, 2, 14, 19, 4, 20])
# Get the index of elements of value less than 20 and greater than 10
output = np.where((example_array  > 10) & (example_array  < 20))
print("Elements which are less than 20 and greater than 10 exists at indices",output, sep='\n')
Output :
Elements which are less than 20 and greater than 10 exists at indices 
(array([ 0, 2, 4, 5, 7, 10, 11]),)

Example : 2

Get the first index of an element in numpy array.

Program :

import numpy as np
# numpy array created with a list of numbers
example_array = np.array([15, 6, 13, 8, 15, 16, 7, 15, 1, 2, 14, 19, 4, 20])
# Get the index of elements with value less than 20 and greater than 10
output = np.where(example_array == 15)
if len(output) > 0 and len(output[0]) > 0:
    print('First Index of element with value 15 is ', output[0][0])
Output :
First Index of element with value 15 is 0

Example : 3

Get the indices of the elements which is less than equal to 2

Program :

import numpy as np 
arr = np.arange(10)
#prints the array
print(arr)
#prints indices of the elements which is less than equal to 2
print(arr[arr <= 2])
Output :
[0 1 2 3 4 5 6 7 8 9] 
[0 1 2]

Find the index of value in Numpy Array using numpy.where() Read More »

Convert List to String in Python using join() reduce() map()

Convert List to String in Python using join() / reduce() / map()

List:

The list is a type of container in Data Structures in Python that is used to store multiple pieces of data at the same time. In Python, unlike Sets, the list is ordered and has a definite count. The elements in a list are indexed in a definite sequence, and the indexing of a list begins with 0 as the first index.

String:

Strings are sequences of bytes in Python that represent Unicode characters. However, since Python lacks a character data form, a single character is simply a one-length string. Square brackets may be used to access the string’s components. In Python, single quotes, double quotes, and even triple quotes can be used to generate strings.

This article will go over various methods to convert list to string.

Examples:

Input:

givenlist=["this" , "is" , "Btech" ,"Geeks"]

Output:

this is btech Geeks

List to String conversion

There are several ways to convert list to string some of them are:

Method #1 : Using String Concatenation

The elements of the input list are iterated one by one and added to a new empty string in this process.

As a result, a list is converted to a string.

Below is the implementation:

# Function which converts list to string
def listToString(givenlist):
    # Taking eempty string say string
    string = ""
    # Traverse the list and concate the elements to the string
    for element in givenlist:
        # converting element of list to string and concating to empty string
        # concatenating space to differentiate words(deliminator)
        string = string + str(element) + " "

    # return the final string
    return string


# Driver code
# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]

# passing list to convert into string
print(listToString(givenlist))

Output:

hello this is Btech Geeks

Method #2:Using join()

The join() method in Python can be used to convert a List to a String.

Iterables such as Lists, Tuples, Strings, and others are accepted as parameters for the join() process.

It also returns a new string as an argument that contains the elements concatenated from the iterable.

The passed iterable must contain string elements as a prerequisite for the join() method to work.

A TypeError exception is thrown if the iterable includes an integer.

# Function which converts list to string
def listToString(givenlist):
  # using  space " " as separator between the elements of list
    string = ' '.join(givenlist)

    # return the final string
    return string


# Driver code
# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]


# passing list to convert into string
print(listToString(givenlist))

Output:

hello this is Btech Geeks

Method #3:Using map()

The map() function in Python can be used to convert a list to a string.

The map() function accepts the function as well as iterable objects like lists, tuples, strings, and so on. Moving on, the map() function uses the provided function to map the elements of the iterable.

General syntax of map:

map(function, iterable)

# Function which converts list to string
def listToString(givenlist):
  # using  space " " as separator between the elements of list
    string = ' '.join(map(str, givenlist))

    # return the final string
    return string


# Driver code
# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]


# passing list to convert into string
print(listToString(givenlist))

Output:

hello this is Btech Geeks

The map(str, givenlist) function in the preceding code snippet accepts str function and given list as arguments.

It maps each element of the input iterable( list) to the given function and returns the resultant list of elements.

In addition, the join() method is used to convert the output to string form.

Note: This method also applicable to list of integers since every element is converted to list.

Method #4:Using reduce()

Python’s functools module includes the function reduce(), which takes an iterable sequence as an argument and a function as an argument. This function returns a single value from an iterable sequence of items.

It will generate the value by passing the first two values to the given function argument and then calling the same function again with the result and the next argument. When it has consumed all of the items in order, the final result value will be returned.

Below is the implementation:

import functools
# Function which converts list to string


def listToString(givenlist):
    # deliminator or separator between the elements of list let us say it as space
    deliminator = " "
   
    # using reduce function
    string = functools.reduce(lambda a, b: a + deliminator + b, givenlist)

    # return the final string
    return string


# Driver code
# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]


# passing list to convert into string
print(listToString(givenlist))

Output:

hello this is Btech Geeks

We passed two arguments to the reduce() function in this case,

  • A lambda function that takes two arguments and joins them with a delimiter in between.
  • Givenlist

Using the logic provided by the lambda function, it joined all of the elements in the list to form a string.
Related Programs:

Convert List to String in Python using join() / reduce() / map() Read More »

Python Dictionary – Append / Add / Update key-value pairs

How to add or append new key value pairs to a dictionary or update existing keys’ values in python.

In this article we will discuss about how we can add or append new key value pairs to a dictionary or update existing keys’ values. As we know Dictionary in python is one of the important datatype which is used to store data values in key : value pair.

Syntax of dictionary :

dictionary_name = {key1: value1, key2: value2}

where,

  • key1, key2… represents keys in a dictionary. These keys can be a string, integer, tuple, etc. But keys needs to be unique.
  • value1, value2… represents values in dictionary. These values can be numbers, strings, list or list within a list etc.
  • key and value is separated by : symbol.
  • key-value pair symbol is separated by , symbol.

For example,

my_dictionary = {"Name":"Satya", "Address":"Bhubaneswar", "Age":20, }

So, now let’s explore the concept how to add a key:value pair to dictionary in Python.

Method #1 : Add/Update using update( ) function :

In python there is an inbuilt member function update( ) which can be used to add or update a new key-value pair to the dictionary.

dictionary_name.update(Iterable_Sequence of key: value)

Actually, this update( ) function adds the key-value pair in the dictionary and if the key exists in the dictionary then it updates the value of that key.

If the key does not exist in the dictionary then it will add the key-value pair in the dictionary. Like this

#Program

CovidCase = {"January": 100000, "February": 110000, "March": 120000, "April": 130000}
print("Before adding new value")
print(CovidCase)
#Adding new key-value
#As the key does not exist so the key May and it's value will be added
CovidCase.update({"May": "140000"})
print("After adding new value")
print(CovidCase)
Output :
Before adding new value
{"January": 100000, "February": 110000, "March": 120000, "April": 130000}
After adding new value
{"January": 100000, "February": 110000, "March": 120000, "April": 130000, "May": 1400000}

If the key exists in the dictionary then it will update the key-value pair in the dictionary. Like this

#Program 

CovidCase = {"January": 100000, "February": 110000, "March": 120000, "April": 130000} 
print("Before adding new value") 
print(CovidCase) 
#Adding new key-value 
#As the key exists,so key January value will be updated
CovidCase.update({"January": "140000"}) 
print("After adding new value") 
print(CovidCase)
Output : 
Before adding new value 
{"January": 100000, "February": 110000, "March": 120000, "April": 130000} 
After adding new value 
{"January": 140000, "February": 110000, "March": 120000, "April": 130000, "May": 1400000}

Method #2 : Add/Update using Subscript [ ] notation :

In python there is a subscript [] operator which can also be used to create a new key-value pair just by assigning a value to that key.

If the key does not exist in the dictionary then it will add the key-value pair in the dictionary. Like this

#Program

CovidCase = {"January": 100000, "February": 110000, "March": 120000, "April": 130000}
print("Before adding new value")
print(CovidCase)
#Adding new key-value
#As the key does not exist so the key May and it's value will be added
CovidCase["May"]=140000
print("After adding new value")
print(CovidCase)
Output : 
Before adding new value 
{"January": 100000, "February": 110000, "March": 120000, "April": 130000} 
After adding new value 
{"January": 100000, "February": 110000, "March": 120000, "April": 130000, "May": 1400000}

If the key exists in the dictionary then it will update the key-value pair in the dictionary. Like this

#Program

CovidCase = {"January": 100000, "February": 110000, "March": 120000, "April": 130000} 
print("Before adding new value") 
print(CovidCase) 
#Adding new key-value
#As the key exists,so key January value will be updated
CovidCase["January"]=140000 
print("After adding new value") 
print(CovidCase)
Output : 
Before adding new value 
{"January": 100000, "February": 110000, "March": 120000, "April": 130000} 
After adding new value 
{"January": 140000, "February": 110000, "March": 120000, "April": 130000, "May": 1400000}

Method #3 : Append using append( ) function:

In python there is an inbuilt function append( ) to add values to the keys of the dictionary. As we will add only value to the keys, so we need to find out the keys to which we want to append the values.

#Program

CovidCase = {"January": [], "February": [], "March": []} 
print("Before adding new value") 
print(CovidCase) 
#Adding new key-value
#As the key exists,so key January value will be updated
CovidCase["January"].append(140000)
CovidCase["February"].append(150000)
CovidCase["March"].append(160000)
print("After adding new value") 
print(CovidCase)
Output : 
Before adding new value 
{"January": [ ], "February": [ ], "March": [ ]} 
After adding new value 
{"January": 140000, "February": 150000, "March": 160000}

Method #4 : Adding values to an existing key-value pair

With the help of update( ) function and subscript [ ] operator the key-value pair is added in dictionary only if that key does not exist in dictionary and if the key exists in the dictionary then the respective value of the key in  dictionary is updated. But if we do not want to replace the value of an existing key dictionary but we want to add a new value to a current value then also we can do it by creating a function.

#Program

def add_value(dict_obj, key, value):
    # Checking the key exists or not
    if key in dict_obj:
        # Key exist in dict.
        # Checking type of value of key is list or not
        if not isinstance(dict_obj[key], list):
            # If type not in list, then make it list
            dict_obj[key] = [dict_obj[key]]
        # Adding the value in list
        dict_obj[key].append(value)
    else:
        # if key is not in dictionary then add key-value pair
        dict_obj[key] = value


CovidCase = {"January": 140000, "February": 150000, "March": 160000}
#Before adding
print(CovidCase)
#After adding
add_value(CovidCase, "February", 170000)
print(CovidCase)
Output : 
Before adding new value 
{"January": [ ], "February": [ ], "March": [ ]} 
After adding new value 
{"January": 140000, "February": [150000, 170000] "March": 160000}

Python Dictionary – Append / Add / Update key-value pairs Read More »

How to Get the Path of Current Working Directory in Python?

Get the path of the current working directory in Python

In this article, we will discuss how to get the path of the current working directory in python. First, let us understand what a directory is.

Directory

The directory or simply say folder is a collection of files and sub-directory. A directory or folder is created to store our files in an organized manner.

Path of Directory

The path of the directory is specified as a unique location of the directory in the system. Unique here identifies that no two files or directories can have the same name in the same path or location. There are 2 types of path one is an absolute path while the other is a relative path.

Absolute path

The path with reference to the root directory is called the absolute path.

Relative Path

The path with reference to the current directory is called the relative path.

os.getcwd() Method

This can be achieved through the os module in python. Before using this module we have to import this module into the program and then we are free to use os module functions.

getcwd() function of os module helps us to find the path current working directory. As this function returns the path of current working directly so we can either store it in a variable then print it or we can directly print it as per our requirement.

syntax: variable_name = os.getcwd()

import os
print(os.getcwd())

Output

C:\Users\HP\Desktop\python

So we can easily get the path of our current working directly using this method.

Now the question that may arise is this path is an absolute path or a relative path. As we get the path with respect to the root directory hence os. getcwd() method gives the absolute path.

How to Get the Path of Current Working Directory in Python? Read More »

Introduction to Python – Executing Python Script

In this Page, We are Providing Introduction to Python – Executing Python Script. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Introduction to Python – Executing Python Script

Executing Python script

As discussed in the previous section, the Python script can be executed using the F5 functional key, from Python’s IDE. It can also be executed using a command prompt by typing the following command:

$ python <filename>

On different platforms, the execution of Python scripts (apart from running from inside Python’s IDE) can be carried out as follows:

Linux

On Unix/Linux system, Python script can be made directly executable, like shell scripts, by including the following expression as the first line of the script (assuming that the interpreter is on the user’s PATH) and giving the file an executable mode.

#! /usr/bin/env python

The ‘# !’ must be the first two characters of the file. Note that the hash or pound character ‘#’ is used to start a comment in Python. The script can be given an executable mode/permission, using the chmod command:

$ chmod + x HelloWorld.py

Windows

On the Windows system, the Python installer automatically associates .py files with python.exe, so that double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed. At MS-DOS prompt, the Python script can be executed by going to the directory containing the script and just entering the script name (with extension).

Introduction to Python – Executing Python Script Read More »

Introduction to Python – Script Mode

In this Page, We are Providing Introduction to Python – Script Mode. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Introduction to Python – Script Mode

Script mode

If the Python interpreter is closed and then invoked again, the definitions that were made (functions, variables, etc.) are lost. Therefore, to write a long program, the programmer should use a text editor to prepare the input for the interpreter and run it with that file as input instead. This is known as creating a “script”. Most of the examples in this book are discussed using interactive mode, but few scripts are also incorporated.

First program

This section will demonstrate to write a simple Python program, which prints “Hello World”. Type the following lines in an IDLE text editor and save it as “HelloWorld.py”.

#! /usr/bin/env python 
print('Hello world')

The first line is called “shebang line” or “hashbang line” (more information in the next section). The second line gives the output: “Hello World”. There are numerous ways to run a Python program. The simplest approach is to press the F5 functional key after saving the program in an IDLE text editor. The output is shown below:

>>>
Hello world

Introduction to Python – Script Mode Read More »