Python

Python Programming – Simple statement

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

Python Programming – Simple statement

Simple statement

A simple statement is comprised within a single logical line. Several simple statements may occur on a single physical line separated by semicolons. The extended BNF notation describing syntax for simple statement is:

simple__stmt : := expression_stmt
                            | assert_stmt 
                            | assignment_stmt 
                            | augmented_assignment_stmt 
                            | pass_stmt 
                            | del_stmt
                            | print_stmt 
                            | return_stmt
                            | yield_stmt 
                            | raise_stmt
                            | break_stmt 
                            | continue_stmt
                            | import_stmt 
                            | global_stmt 
                            | exec_stmt

This book will discuss some of the simple statements.

Expression statement

An expression in a programming language is a combination of values, constants, variables, operators, functions etc. that are interpreted according to the particular rules of precedence for a particular programming language, which computes and then returns another value. This process is called evaluation. An expression statement evaluates the expression list (which may be a single expression).

expression_stmt : := expression_list

The following are examples of expression statements and their evaluation.

>>> 4 
4
>>> 4==4 
True 
>>> 2+6 
8
>>> ' Hi ' * 3 
' HiHiHi '

Assignment statement

Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects. The following example shows binding value 4 to object (or name) a.

>>> a=4

Pass statement

The pass statement is a null operation, nothing happens when it is executed. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed.

pass_stmt  : : =  " pass "

The following example defines a function f and does nothing.

>>> def f ( arg ) :
. . .      pass
. . .

Del statement

This statement deletes each target in target_list from left to right.

del_stmt : := " del " target_list

Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised.

>>> a = [ -1 , 1 , 66  .25 , 333 , 333 , 1234 . 5 ]
>>> del a [ 0 ]
>>> a
[ 1 , 66 . 25 , 333 ;  333 , 1234 . 5 ]
>>> del a [ 2 : 4 ]
>>> a
[ 1 , 66 . 25 , 1234 . 5 ]
>>> del a [ : ]
>>> a
[ ]
>>> a = [ -1 , 1 , 66 . 25 , 333 , 333 , 1234 . 5 ]
>>> del a
>>> a

Traceback ( most recent call last ) :
    File " <pyshell#24> " , line 1 , in <module> 
         a
NameError: name ' a ' is not defined

Print statement

The print statement evaluates each expression and then writes the resulting object to standard output (computer screen). If an object is not a string, it is first converted to a string using the rules for string conversion, the resulting or original string is then written. Space is written before each object is (converted and) written unless the output system believes it is positioned at the beginning of a line. A ‘ \n’ character is written at the end unless the print statement ends with a comma. If only the print keyword is there in the print statement, then only the ‘ \ n ‘ character is written. Following is a script “print_example.py”, having the following code:

a=20 
print ' hi ' , 5 , a 
print ' bye ' , 10 , a 
print 
print ' hi ' , 5 , a ,
print ' bye ' , 10 , a ,

Output after running the script is:

>>> runfile ( ' C : / Temp / print_example . py ' , wdir=r ' C : / Temp ' ) 
hi 5 20 
bye 10 20

hi 5 20 bye 10 20

Return statement

The return statement leaves the current function call with the expression_list (or None) as the return value.

return_stmt : := " return " [ expression_list ]

The following script ” addition_example . py ” demonstrate the use of return statement.

def summation ( arg1 , arg2 ) :
       return arg1+arg2

print ' Sum is : ' , summation ( 1 , 2 )

def summation ( arg1 , arg2 ) :        # The function return None
       print ' Sum is: ' , arg1+arg2

summation ( 3 , 4 ) 
print summation ( 3 , 4 )

def summation ( arg1 , arg2 ) :        # The function return None
print 'Sum is: ',arg1+arg2
return

summation ( 5 , 6 ) 
print summation ( 5 ,6)

def summation(argl,arg2):               # The function return None
    print ' Sum is: ' , arg1+arg2
    return None

summation ( 7 , 8 ) 
print summation ( 7 , 8 )

def summation ( arg1 , arg2) : 
def add ( arg1 , arg2) : 
        return arg1+arg2 
return add (arg1 , arg2 )

print ' Sum is : ' , summation ( 9 , 10)

The output after running the script is:

>>> runfile ( ' C : / Temp / addition_example . py ' , . wdir=r ' C : / Temp ' )
Sum is: 3
Sum is: 7 
Sum is: 7
None
Sum is: 11
Sum is: 11
None
Sura is: 15
Sum is: 15
None
Sum is: 19

Break statement

The break statement terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.

break_stmt : : = " break "

If a for loop is terminated by break, the loop control target keeps its current value. The following script ” break_example . py ” demonstrates the use of the break statement.

a=5
for i in range ( 10 ) : 
    if i==a: 
          break 
  else:
        print i

print i

The output after running the script is:

>>> runfile ( ' C : / Temp / addition_example . py ' , wdir= r ' C : / Temp ' )
0 
1
2
3
3 
5

Continue statement

The continue statement makes the current nearest enclosing loop skip one iteration and executes the remaining ones.

continue_stmt : : = " continue "

The following script ” continue_example . py ” demonstrate the use of the continue statement.

for i in range ( 10 ) : 
     if i>4 and i<8 : 
     continue 
else: 
     print i

The output after running the script is:

>>> runfile ( ' C : / Temp / continue_example . py ' , wdir= r ' C : / Temp ' )
0
1
2
3
4
8
9

Import statement

Definitions (variables, function definitions, etc.) from one module can be imported into another module using an import statement. For more information, please refer to chapter 5.

Global statement

The global statement is a declaration that makes listed identifiers to be interpreted as global. This will become clearer by referring to section 3.2.5.

global_stmt : := " global " identifier ( " , " identifier) *

Python Programming – Compound statement Parameter

In this Page, We are Providing Python Programming – Compound statement Parameter. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Compound statement Parameter

Parameter

The parameter is a named entity in a function (or method) definition that specifies the argument (or in some cases, arguments), that the function can accept. Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. For example, given the function definition:

def func ( foo , bar=None , ** kwargs ) : 
              pass

foo, bar, and kwargs are parameters of f unc. However, when calling f unc, for example:

f unc ( 42 , bar=314 , extra=somevar )

the values 42 , 314 , and somevar are arguments.

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object). Actually, call by object reference would be a better description, since if a mutable object is passed, the caller will see any changes the callee makes to it (items inserted into a list).

>>> def changeme ( mylist ) :
. . .               mylist.append ( [ 1 , 2 , 3 , 4 ] )
. . .               print "Values inside the function:  " , mylist
. . .               return
. . . 
>>> mylist= [ 10 , 20 , 30 ] 
>>> changeme ( mylist )
Values inside the function: [ 10 , 20 , 30 , [ 1 , 2 , 3 , 4 ] ]
>>> print "Values outside the function:  " , mylist 
Values outside the function: [ 10 , 20 , 30 , [ 1 , 2 , 3 , 4 ] ]

In the above example, the append operation maintains the passed object reference. In the following example, the object reference is overwritten inside the function.

>>> def changeme ( mylist ) :
. . .          mylist= [ 1 , 2 , 3 , 4 ]
. . .          print "Values inside the function: ",mylist
. . .         return
. . . 
>>> mylist= [ 10 , 20 , 30 ]
>>> changeme ( mylist )
Values inside the function: [ 1 , 2 , 3 , 4 ]
>>> print "Values outside the function:  " , mylist 
Values outside the function: [ 10 , 20 , 30 ]

There are four types of parameters:

Positional or keyword parameter

It specifies that an argument can be passed either positionally or as a keyword argument. Note that, only those parameters which are at the end of the parameter list can be given default argument values i.e. the function cannot have a parameter with a default argument value preceding a parameter without a default argument value in the function’s parameter list. This is because the values are assigned to the parameters by position. For example, def func ( a , b=5 ) is valid, but def func ( a=5 , b ) is not valid.

Only positional parameter

It specifies that an argument can be supplied only by position.

Var-positional parameter

It specifies that an arbitrary sequence of positional arguments can be provided (in addition to any positional arguments already accepted by other parameters). Such a parameter can be defined by prepending the parameter name with *.

Var-keyword parameter

It specifies that arbitrarily many keyword arguments can be provided (in addition to any keyword arguments already accepted by other parameters). Such a parameter can be defined by prefixing the parameter name with **.

Following are few examples of functions.

>>> def person_info ( fn , In , ag , tel=5128975 , nat=' American ' ) :
. . .               print ' First name : ' , fn
. . .               print ' Last name : ' , In
. . .               print ' Age : ' , ag 
. . .               print ' Telephone number : ' , tel
. . .               print ' Nationality : ' , nat
. . . 
>>> person_info ( ’ Sachin ' , ' Tendulkar ' , 40 , 17896823 , ' Indian ' ) 
First name: Sachin 
Last name: Tendulkar 
Age: 40
Telephone number: 17896823 
Nationality: Indian
>>> person_info ( ' Mike ' , ' Johnson ' , 20 )
First name: Mike 
Last name: Johnson 
Age: 20
Telephone number: 5128975 
Nationality: American
>>> person_info ( ' Nadeem ' , ' Khan * , 54 , nat= ' Pakistani ' )
First name: Nadeem 
Last name: Khan 
Age: 54
Telephone number: 5128975 
Nationality: Pakistani
>>> person_info ( ' Chin ' , ' Chan ' , 15 , nat= ' Chinese ’ , tel=1894313654 ) 
First name: Chin 
Last name: Chan 
Age: 15
Telephone number: 1894313654 
Nationality: Chinese 
>>>
>>> def person_info ( fn , In , ag , tel , nat ) :
. . .                   print ' First name: ' , fn
. . .                   print ' Last name: ' , In
. . .                   print ' Age: ' , ag
. . .                   print ' Telephone number: ' , tel
. . .                   print ' Nationality: ' , nat
. . . 
>>> person_info ( ' Sachin ' , ' Tendulkar ' , 40,17896823, ' Indian') 
First name: Sachin 
Last name: Tendulkar 
Age: 40
Telephone number: 17896823 
Nationality: Indian
>>> person_info ( ' Chin ' , ' Chan ' , 15 , 1894313654 , ' Chinese ' ) 
First name: Chin 
Last name: Chan 
Age: 15
Telephone number: 1894313654 
Nationality: Chinese 
>>>
>>> def total ( a , b , *numbers ) :
. . .      tot=a+b
. . .      for num in numbers:
. . .      tot=tot+num
. . .      return tot
. . .
>>> print ' Total : ' , total ( 1 , 2 , 3 , 4 , 5 )
Total : 15
>>> print ' Total : ' , total ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 )
Total : 55 
>>>
>>> def person_info ( fn= ' Chinln = ' Chan ' , ** more_info ) :
. . .         print ' First name : ' , fn
. . .         print ' Last name : ' , In
. . .         if more_info.has_key ( ' ag ' ) :
. . .               print ' Age : ' , more_info [ ' ag ' ]
. . .         if more_info.has_key ( ' tel ' ) :
. . .              print ' Telephone number : ' , more_info [ ' tel ' ]
. . .         if more_info.has_key ( ' nat ' ) :
. . .              print ' Nationality : ' , more_info [ ' nat ' ] 
. . . 
>>> person_info ( )
First name: Chin 
Last name: Chan
>>> person_info ( ag=40 , tel=1789 , ln= ' Tendulkar ' , nat= ' Indian ' , fn= ' sachin ' )
First name: Sachin 
Last name: Tendulkar 
Age: 40
Telephone number: 1789 
Nationality: Indian
>>> personl_info ( ag=15 , nat= ' Chinese ' , tel=l894313654 )
First name: Chin
Last name: Chan
Age: 15 
Telephone number: 1894313654 
Nationality: Chinese 
>>>
>>> def total( a , b , *numbers , **kwag ) :
. . .       tot=a+b 
. . .       for num in numbers:
. . .            tot=tot+num
. . .      for key in kwag:
. . .           tot=tot+kwag [ key ]
. . .      return tot
. . . 
>>> print ' Total : ' , total ( 5 , 7 , 10 , 2 , 14 , c=100 , d=106 , e=211 ) 
Total: 455

Python: How to Create an Empty Set and Append Items to It?

A Set is an unordered collection data type that can be iterated, mutated, and does not contain duplicate elements. Python’s set class represents the mathematical concept of a set. The main advantage of using a set over a list is that it has a highly optimised method for determining whether a specific element is contained in the set. This is based on the hash table data structure. Because sets are unordered, we cannot access items using indexes as we do in lists.

Characteristics of set:

  • Sets are not in any particular order.
  • Set elements are one of a kind. It is not permitted to use duplicate components.
  • A set’s elements can be modified, but the set’s elements must be of an immutable form.

In this article, we will first look at various ways to create an empty set, and then we will look at how to add or append items to the empty set.

Methods to Create an Empty Set

Method #1: Using set() to create an empty set in Python

A set is formed by enclosing all of the items (elements) within curly braces, separated by commas, or by using the built-in set() function.

It can contain an unlimited number of items of various types (integer, float, tuple, string etc.). A set, on the other hand, cannot have mutable elements such as lists, sets, or dictionaries as its elements.

It takes an optional iterable sequence and returns a set that has been initialised with the elements in the sequence. However, if no iterable sequence is passed to the function it returns an empty set.

Below is the implementation:

# creating new set
emptyset = set()
# printing the set
print(emptyset)
# printing the size of empty set
print("length of set = ", len(emptyset))

Output:

set()
length of set =  0

Method #2:Using empty set literal

Empty curly brackets, i.e., are commonly used in Python to create a dictionary. However, starting with Python 3.5, if we pass some comma separated arguments in curly square brackets, it will create a set with them. For example, 1, 2, 3 can be used to make a set with three values.

So, to make an empty set, we can use the same method.

Below is the implementation:

# creating new set
emptyset = {*()}
# printing the set
print(emptyset)
# printing the size of empty set
print("length of set = ", len(emptyset))

Output:

set()
length of set =  0

Append an item to an empty set

In set, insertion is accomplished via the set.add() function, which generates an appropriate record value for storage in the hash table. The same as searching for a specific item, i.e., O(1) on average. However, in the worst-case scenario, it can become O (n).

Below is the implementation:

# creating new set
emptyset = {*()}
# adding elements to set
emptyset.add('BTechGeeks')
emptyset.add('Hello')
emptyset.add('BTechGeeks')
# printing the set
print(emptyset)

Output:

{'BTechGeeks', 'Hello'}

Appending multiple items to the empty set

Using the set’s update() function, we can add multiple items to an empty set in a single line.

Below is the implementation:

# creating new set
emptyset = set()
# adding elements to set
emptyset.update(('Hello', 'BTechGeeks', 'Hello'))
# printing the set
print(emptyset)

Output:

{'Hello', 'BTechGeeks'}

Explanation:

The update() function takes a single or several iterable sequences as arguments and updates the set with all of the things in those sequences. In the preceding example, we created an empty set and then appended all of the items in a tuple to it in a single line.

 
Related Programs:

Check If Type of a Variable is String in Python

A string is a series of characters.

A character is nothing more than a representation of something. For example, there are 26 characters in the English language.

Computers do not work with characters, but rather with numbers (binary). Although characters are seen on your screen, they are stored and manipulated internally in a series of 0’s and 1’s.

A string in Python is a sequence of Unicode characters. Unicode was created in order to include every character in every language and to bring encoding uniformity.. Python Unicode can teach you everything you need to know about Unicode.

Examples:

Input:

string="hello"

Output:

Yes it is string variable

Determine whether a variable type is string

There are several ways to check whether a variable type is string some of them are:

Method #1 : Using type() function

The type() method returns the class type of the argument (object) that was passed as a parameter. The function type() is used mainly for debugging.

The type() function accepts two types of arguments: single and three argument. If only one argument is passed, type(obj), it returns the type of the given object. If type(name, bases, dict) is passed as an argument, it returns a new type object.

Syntax:

type(object)
type(name, bases, dict)

Parameters:

name : class name, which corresponds to the class’s __name__ attribute.
bases: a tuple of classes from which the current class is descended. Later corresponds to the attribute __bases__.
dict: a dictionary containing the class’s namespaces. Later is equivalent to the __dict__ attribute.

Return:

returns a new type class or, more precisely, a metaclass

We get the type of variable using type() and then compare it to str to see if it is a string variable.

Below is  the implementation:

# given variable
variable = "hello"
# comparing str and type of variable
if(type(variable) == str):
    print("Yes it is string variable")
else:
    print("No it is not string variable")

Output:

Yes it is string variable

Method #2 : Using isinstance() function

Python comprises a function for determining the type of a variable.

isinstance(object, classinfo)

The result of this function is If the given object is an instance of class classinfo or any of its subclasses, return True otherwise, return False.

Let’s see if we can use this to see if a variable is of the string form.

Below is the implementation:

# given variable
variable = "hello"
# using isinstance function to check whether the type of it is string or not
if(isinstance(variable, str)):
    print("Yes it is string variable")
else:
    print("No it is not string variable")

Output:

Yes it is string variable

Method #3 : By comparing types

We hard coded the string class in both previous solutions. But we can also compare the type of variable with the type of the empty string, without hard coding.

We know that the string object type is “”.

To compare the types we use this.

Below is the implementation:

# given variable
variable = "hello"
# comparing using type() function as type of string is ""
if(type(variable) == type("")):
    print("Yes it is string variable")
else:
    print("No it is not string variable")

Output:

Yes it is string variable

Related Programs:

Python: Iterate Over Dictionary (All Key-Value pairs)

Python’s implementation of an associative array, which is a data structure, is dictionaries. A dictionary is a collection of key-value pairs. Each key-value pair represents a key and its associated value.

Enclosing a comma-separated list of key-value pairs in curly braces defines a dictionary { }. A colon ‘ : ‘ separates each key from its associated value.

Note:

  • Keys are mapped to values in dictionaries, which are then stored in an array or series.
  • The keys must be of the hashable form, which means that their hash value must remain constant over their lifetime.

The keys and values of a dictionary are iterated over in the same order as they were generated in Python 3.6 and later. However, this behaviour varies between Python versions and is dependent on the dictionary’s insertion and deletion history.

Examples:

Input :

dictionary = {'This': 100, 'is':200, 'BTechGeeks':300}

Output:

This 100
is 200
BTechGeeks 300

Traverse the dictionary

There are several ways to traverse the dictionary some of them are:

Method #1: Using for loop

To iterate over all keys in a dictionary, a dictionary object may also be used as an iterable object. As a result, we can apply for loop on a dictionary with ease. It loops through all the keys in the dictionary by using for in the dictionary. We will pick the value associated with each key and print it.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Using for loop to traverse the dictionary
for key in dictionary:
    # here key gives the key of the dictionary
    # Getting value at key
    value = dictionary[key]
    # printing values and keys
    print(key, value)

Output:

This 100
is 200
BTechGeeks 300

Method #2:Using items()

When dealing with dictionaries, you’ll almost certainly want to use both the keys and the values. .items(), a method that returns a new view of the dictionary’s items, is one of the most useful ways to iterate through a dictionary in Python.

This sequence is an iterable View object that contains all of the dictionary’s key,value elements. It is supported by the original dictionary. Let’s use this to iterate over all of the dictionary’s key-value pairs.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Using items and converting dictionary to list
dictlist = list(dictionary.items())
# Traverse the dictlist and print key and values of dictionary
for i in dictlist:
  # printing key and value
    print(i[0], i[1])

Output:

This 100
is 200
BTechGeeks 300

Method #3:Using List Comprehension

Since the items() function of a dictionary returns an iterable sequence of key-value pairs, we may use this list comprehension to iterate over all diction pairs.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Using list comprehension
[print(key, value) for key, value in dictionary.items()]

Output:

This 100
is 200
BTechGeeks 300

Filtering Items in dictionary

You can find yourself in a situation where you have an existing dictionary and want to construct a new one to store only the data that meets a set of criteria. This can be accomplished using an if statement inside a for loop, as shown below:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Create a new empty dictionary
newdictionary = dict()
# Traverse the original dictionary and check the condition
for key, value in dictionary.items():
    # If value meets the criteria, it should be saved in new dict.
    if value <= 200:
        newdictionary[key] = value
# printing the new dictionary
print(newdictionary)

Output:

{'This': 100, 'is': 200}

Related Programs:

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

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

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

In Python, String is a sequence of characters where character can be a string, integer or any symbol. With each character 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 = “Digital”

The first character starts with index 0 and it goes on. Like

Index of character ‘D’ = 0

Index of character ‘i’ = 1

Index of character ‘g’ = 2

Index of character ‘i’ = 3

Index of character ‘t’ = 4

Index of character ‘a’ = 5

Index of character ‘l’  = 6

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

Like String_value[i] will return i-th character of the string, where ‘i’ represents an index position.

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

Get last character of the String using negative indexing :

Negative indexing refers to associate negative index value to each character of the string. Like last character of string will be associated with index number -1 then negative index will go on incrementing and characters will go on decrementing so that each character will be associated with a negative index.

Let’s see how actually its implemented

String_value = “Digital”

Where the sequence number/index of the last character starts with -1 and it goes on. Like

Index of character ‘D’ = -7

Index of character ‘i’ = -6

Index of character ‘g’ = -5

Index of character ‘i’ = -4

Index of character ‘t’ = -3

Index of character ‘a’ = -2

Index of character ‘l’  = -1

So let’s see a program to get the last character of the string using negative indexing.

#Program:

String_value = "Digital"
Last_char = String_value[-1]
print('Last character of the string is', Last_char)
Output : 
Last character of the string is l

Here, just by passing -1 in the operator [ ], we fetched the last character of the string.

Get the last character of string using len() function :

Without using negative indexing we can also get the last character of the string just by finding the length of the string and then printing the character at length-1 position.

So let’s see a program to get the last character of the string using len( ) function.

#Program: 

String_value = "Digital" 
#Finding length of String_value
length = len(String_value )
# Finding the last character of string
#Length of the string -1 represents last character
Last_char = String_value[length -1]
print('Last character of the string is', Last_char)
Output :
Last character of the string is l

Get last N characters in a string :

In above examples we only have passed index position in the subscript operator, i.e. [] but it can also accept a range too i.e.

Syntax : string_value[ start_index_position : end_index_position : step_size]

Where,

  • start_index_position: It refers to the index position, from where it will start fetching the characters in a string (Default value is 0).
  • end_index_position: It refers to the index position, upto which it will fetch the characters from string (Default value is end of string).
  • step_size: It refers to the interval between each character (Default value is 1).

When we use the above statement it returns a substring means part of the string.

So let’s see a program to understand the implementation of it.

Approach #1 : Using negative index

#Program: 

String_value = "Digital" 
#Finding length of String_value
length = len(String_value )
# Finding the last 3 characters of string
# Here mention start index i.e -3 
# End index not mentioned, so it will go upto last character
Last_char = String_value[-3:]
print('Last 3 characters of the string is', Last_char)
Output :
Last 3 characters of the string is tal

Approach #2 : Using len( ) function

#Program: 

String_value = "Digital" 
#Finding length of String_value 
length = len(String_value ) 
# Finding the last 3 character of string 
#here start index is length of the string -3 i.e length-3
Last_char = String_value [length - 3 :]
print('Last 3 characters of the string is', Last_char)
Output :
Last 3 characters of the string is tal

How to change current working directory in python ?

How to get and change current working directory in python ?

In python, we use OS module to interact with the operating system. As it comes under Python’s standard utility module, so we do not have to install it externally. During working if we use invalid or inaccessible file names and paths, then all functions in OS module raise OS error.

So at the top of file we have to import os module to use this functions.

While we deal with files in directories in python we use two types of paths i.e

  1. Relative Path : Location begins from the current working directory.
  2. Absolute Path : Location begins from the root directory.

Where, current working directory refers to the folder in which the Python script is operating.

So, in this article we will discuss how we can get and change the current working directory in python.

Get the Current Working Directory in Python :

getcwd() method of the os module is used to get the absolute path of current working directory.

Syntax : os.getcwd()

So, let’s see a program, to understand the implementation of it.

#Program :

import os
  
# Function to Get the current working directory
def current_path():
    print("Current working directory before change")
    print(os.getcwd())
    print()
  
# Printing CWD before change
current_path()
Output :
Current working directory before change
home/linuxize/desktop

Change the Current Working Directory in Python :

os.chdir( ) method is used to change the current working directory in python.

Syntax : os.chdir()

So, let’s see a program, to understand the implementation of it.

#Program :

import os
  
# Function to Get the current working directory
def current_path():
    print("Current working directory after change")
    print(os.getcwd())
    print()
  
  
# Changing the current working directory
os.chdir('/temp')
# Printing current working directory after
current_path()
Output :
Current working directory after change
/temp

Changing the path which does not exist :

Suppose a path does not exist, but we are trying to change that path using os.chdir( ) method. As we are trying to change a false path which does not exist so it will raise an error FileNotFoundError.

So, let’s see a program, to understand the implementation of it.

#Program
# Python program to change the current working directory
 
# importing necessary libraries 
import sys, os 
    
# initial directory 
cwd = os.getcwd() 
    
# This directory does not exist
fd = 'false_dir/temp'
    
# But we are trying to insert to flase directory 
try: 
    print("Inserting inside :", os.getcwd())
    os.chdir(fd) 
        
# Cache the exception  
except: 
    print("Some error associated with specified directory. Exception : ")
    print(sys.exc_info()) 
              
# handling with finally           
finally: 
    print()
    print("Restoring the correct path") 
    os.chdir(cwd) 
    print("So Current directory is :", os.getcwd())
Output :
Inserting inside : home/linuxize/desktop
Some error associated with specified directory. Exception :
(<class ‘FileNotFoundError’>, FileNotFoundError(2, ‘No such file or directory’), <traceback object at 0x7fca10a2e788>)
Restoring the correct path
So Current directory is :
home/linuxize/desktop

Python: Print items of a dictionary line by line (4 ways)

How to print items of a dictionary line by line in python ?

In python a dictionary is one of the important datatype which is used to store data values in key : value pair. Generally keys and values are mapped one-to-one. But it is not impossible that we can not map multiple values to a single key. So in this article we will discuss how we can map multiple values per key in dictionary.

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 strings, numbers, list or list within a list etc.
  • key and value is separated by : (colon) symbol.
  • key-value pair symbol is separated by , (comma) symbol.

Example of a dictionary population where multiple values are associated with single key.

population = {"Odisha": 40000000, "Telangana": 50000000, "Delhi": 80000000, "Goa": 10000000}

So, let’s first create a dictionary and we will see how it prints the dictionary in a single line.

#Program

#dictionary created
population = {"Odisha": 40000000, "Telangana": 50000000, "Delhi": 80000000, "Goa": 10000000} 
#printing dictionary in a line
print("Printing dictionary in a single line :") 
print(population)
Output :
Printing dictionary in a single line :
population = {"Odisha": 40000000, "Telangana": 50000000, "Delhi": 80000000, "Goa": 10000000}

It was very easy to print dictionary in a single line as to print the dictionary we just passed the dictionary name i.e population in the print statement. As the dictionary is small so we printed it in a single line also we understood it easily.

But think about a situation when the dictionary is too big and we need to print the dictionary line by line means one key-value pair in a single line then next key-value pair in next line and so on. It will be very easy for us also to understand a big dictionary very easily. So, in this article we will discuss how we can print items of a dictionary in line by line.

Method -1 : Print a dictionary line by line using for loop & dict.items()

In python there is a function items( ), we can use that along with for loop to print the items of dictionary line by line. Actually dict.items( ) returns an iterable view object of the dictionary which is used to iterate over key-value pairs in the dictionary.

So, let’s take an example to understand it more clearly.

#Program

#dictionary created
population = {"Odisha": 40000000, "Telangana": 50000000, "Delhi": 80000000, "Goa": 10000000} 
#printing dictionary in line by line
# Iterating over key-value pairs in dictionary and printing them
for key, value in population.items():
    print(key, ' : ', value)
Output :
Odisha: 40000000
Telangana: 50000000
Delhi: 80000000
Goa: 10000000

Method -2 : Print a dictionary line by line by iterating over keys

Like in method-1 we did iterate over key-value pair, in method-2 we can only iterate over key and for each key we can access its value and print the respective value.

So, let’s take an example to understand it more clearly.

#Program

#dictionary created
population = {"Odisha": 40000000, "Telangana": 50000000, "Delhi": 80000000, "Goa": 10000000} 
#printing dictionary in line by line
# Iterating over key in dictionary and printing the value of that key
for key in population:
    print(key, ' : ', population[key])
Output :
Odisha: 40000000
Telangana: 50000000
Delhi: 80000000
Goa: 10000000

Method -3 : Print a dictionary line by line using List Comprehension

Using list comprehension and dict.items(), the contents of a dictionary can be printed line by line.

So, let’s take an example to understand it more clearly.

#Program

#dictionary created
population = {"Odisha": 40000000, "Telangana": 50000000, "Delhi": 80000000, "Goa": 10000000} 
#printing dictionary in line by line
[print(key,':',value) for key, value in population.items()]
Output : 
Odisha: 40000000 
Telangana: 50000000 
Delhi: 80000000 
Goa: 10000000

Method -4 : Print a dictionary line by line using json.dumps()

In python, json.dumps( ) is provided by json module  to serialize the passed object to a json like string. So to print the dictionary line by line we can pass that dictionary in json.dumps( ).

So, let’s take an example to understand it more clearly.

#Program

import json
#dictionary created
population = {"Odisha": 40000000, "Telangana": 50000000, "Delhi": 80000000, "Goa": 10000000} 
#printing in json format
print(json.dumps(population, indent=1))
Output : 
Odisha: 40000000 
Telangana: 50000000 
Delhi: 80000000 
Goa: 10000000

More Complex File Manipulation with Python

Python is a very convenient language that’s  frequently used for  data science, scripting and web development.

In this article, we will see  how to get different kinds of file information.

Using the os module you can get more information about it.

Getting the different kinds of file information

OS module introduced with large number of tools to deal with various filenames, directories and paths.

To find out a list of all  files and subdirectories in a particular directory , we are using os.listdir().

import os
entries = os.listdir("C:\\New folder\\Python project(APT)\\")

os.listdir() returns a list hold the names of the files and subdirectories in the given folder .

Output:

['articles', 'django folder', 'FilePath.py', 'hello.py', 'imagedownload', 'images', 'lcm', 'lcm2', 'newtons-second-law', 'RssScrapy.py', 'Scrapy1', 'scrapy2', 'scrapy3', 'speedofsound', 'studyrank', 'twosum.py']

A directory listing like that have some difficulty while reading. So we use loop to make it little clear-

import os
entries  = os.listdir("C:\\New folder\\Python project(APT)\\")
for entry in entries:
    print(entry)

Output:

articles
django folder
FilePath.py
hello.py
imagedownload
images
lcm
lcm2
newtons-second-law
RssScrapy.py
Scrapy1
scrapy2
scrapy3
speedofsound
studyrank
twosum.py

So you can see that with the help of loop we can make reading all subfolder little clear.

Listing of directory in Modern Python Versions:

In Python modern versions , an alternative to os.listdir() is to use os.scandir() and pathlib.path().

os.scandir() was introduced in Python 3.5. os.scandir() returns an iterator as opposed to a list when called.

import os

entries = os.scandir("C:\\New folder\\Python project(APT)\\")

print(entries)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
<nt.ScandirIterator object at 0x0371F9F8>

The scandir points out to all the entries in the current directory. You can loop over the entries of the iterator and print out the filenames.While above it will show you object name.

Another method to get a directory listing is to use the pathlib module:

from pathlib import Path

entries = Path("C:\\New folder\\Python project(APT)\\")
for entry in entries.iterdir():
    print(entry.name)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
articles
django folder
FilePath.py
hello.py
imagedownload
images
lcm
lcm2
newtons-second-law
RssScrapy.py
Scrapy1
scrapy2
scrapy3
speedofsound
studyrank
twosum.py

So you have seen three method to list all filenames of any directory which is os.listdir(),os.scandir() and pathlib.path().

List out All Files in a Directory:

To separate out folders and only list files from a directory listing produced by os.listdir(), use os.path():

import os
# List all files in a directory using os.listdir
basepath = ("C:\\New folder\\Python project(APT)\\")
for entry in os.listdir(basepath):
    if os.path.isfile(os.path.join(basepath, entry)):
        print(entry)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
FilePath.py
hello.py
RssScrapy.py
twosum.py

Here we can see that,os.listdir() returns a list of everything in the specified path and then that list is filtered with the help of os.path.itself() to  print out only  files and not directories.

So now we will see other easier way to list files in a directory is by using os.scandir() or pathlib.path() :

import os

# List all files in a directory using scandir()
basepath = "C:\\New folder\\Python project(APT)\\"
with os.scandir(basepath) as entries:
    for entry in entries:
        if entry.is_file():
            print(entry.name)

Using os.scandir() has more clear than os.listdir(), even though it is one line of code long. In this we are calling entry.is_file() on each item in the Scandir() returns True if the object is a file.

Output:

RESTART: C:/Users/HP/Desktop/article3.py 
FilePath.py 
hello.py 
RssScrapy.py 
twosum.py

Here’s we will show to list out files in a directory using pathlib.path():

from pathlib import Path

basepath = Path("C:\\New folder\\Python project(APT)\\")
files_in_basepath = basepath.iterdir()
for item in files_in_basepath:
    if item.is_file():
        print(item.name)

Output:

RESTART: C:/Users/HP/Desktop/article3.py

FilePath.py
hello.py
RssScrapy.py
twosum.py

List out Subdirectories:

To list out subdirectories other than files, use one of the methods below.

import os

# List all subdirectories using os.listdir
basepath = "C:\\New folder\\Python project(APT)\\"
for entry in os.listdir(basepath):
    if os.path.isdir(os.path.join(basepath, entry)):
        print(entry)

Here’s we have shown how to use os.listdir() and os.path():

Output:

articles
django folder
imagedownload
images
lcm
lcm2
newtons-second-law
Scrapy1
scrapy2
scrapy3
speedofsound
studyrank

Getting File Attributes

This will first get a list of files in directory and their attributes and then call convert.date()  to convert each file’s last modified time into a human readable form .convert.date() makes use of .strftime() to convert the time in seconds into a string.

from datetime import datetime
from os import scandir

def convert_date(timestamp):
    d = datetime.utcfromtimestamp(timestamp)
    formated_date = d.strftime('%d %b %Y')
    return formated_date

def get_files():
    dir_entries = scandir("C:\\New folder\\Python project(APT)\\")
    for entry in dir_entries:
        if entry.is_file():
            info = entry.stat()
            print(f'{entry.name}\t Last Modified: {convert_date(info.st_mtime)}')
print(get_files())            

Output:

FilePath.py        Last Modified: 19 Apr 2021
hello.py             Last Modified: 17 Apr 2021
RssScrapy.py     Last Modified: 17 Apr 2021
twosum.py        Last Modified: 17 Apr 2021

So by above method we are able to get  the time the files in directry were last modified.

Conclusion:

So we have seen how to get details of any directory by using three methods i.e. os.listdir() , os.scandir() and pathlib.path().We have also seen how to get only files on that particular folder seperately and also attribute of that folder.

Python Programming – Compound statement Functions

In this Page, We are Providing Python Programming – Compound statement Functions. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Compound statement Functions

Functions

The function is a compound statement which returns some value to the caller. The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line and must be indented.

The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or “docstring”. Docstring is a string literal that appears as the first expression in a class, function, or module. While ignored when the suite is executed, it is recognized by the compiler and put into the doc attribute of the enclosing class, function, or module.

>>> def summation ( a , b ) : 
. . . " " " Gives sum of
. . .            two numbers " " "
. . .      sum=a+b
. . .     return sum
>>> summation ( 5 , 10 )
15
>>> summation. ________ doc_______
' Gives sum of \ n            two numbers '