Problem Solving With Python2

 

Unit-II

Functions:

· Functions are one of the fundamental building blocks in Python programming language.

· Functions are used when you have a block of statements that needs to be executed multiple times within the program. Rather than writing the block of statements repeatedly to perform the action, you can use a function to perform that action.

· This block of statements are grouped together and is given a name which can be used to invoke it from other parts of the program.

· You write a function once but can execute it any number of times you like.

· Functions also reduce the size of the program by eliminating rudimentary code.

· Functions can be either Built-in Functions or User-defined functions.

 

Built-In Functions

(Explain Built-In Functions in python?)

The Python interpreter has a number of functions that are built into it and are always available.

       


                                                                            
--O--












Commonly Used Modules

( What is a module in python? Give examples?)

· Modules in Python are reusable libraries of code having .py extension, which implements a group of methods and statements.

· Python comes with many built-in modules as part of the standard library.

· To use a module in your program, import the module using import statement.

· All the import statements are placed at the beginning of the program.

 

The syntax for import statement is,

import module_name

 

math module

For example, you can import the math module as

1. >>>import math

The math module is part of the Python standard library which provides access to various mathematical functions and is always available to the programmer.

The syntax for using a function defined in a module is,

module_name.function_name()

The module name and function name are separated by a dot.

Here we list some of the functions supported by math module.

1. >>> import math                                     # Import the math module at the beginning

2. >>> print(math.ceil(5.4))             # The math.ceil(x) function returns the ceiling of x, the

6                                                          #smallest integer greater than or equal to the number

3. >>> print(math.sqrt(4))               # math.sqrt(x), returns the square root of x

2.0

4. >>> print(math.pi)                       #math.pi is the mathematical constant π = 3.141592,

5. >>> print(math.cos(1))                # math.cos(x) returns the cosine of x radians

0.5403023058681398

6. >>> math.factorial(6)                   # math.factorial(x) returns x factorial

720

7. >>> math.pow(2, 3)                     # math.pow(x, y) returns x raised to the power y

8.0

 

function dir():

The built-in function dir() returns a sorted list of comma separated strings containing the names of functions, classes and variables as defined in the module.

For example:

1. >>> dir(math)

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

 

help() function:

The help() function which invokes the built-in help system. The argument to the help() function is a string, which is looked up as the name of a module, function, class, method, keyword, or documentation topic, and then a related help page is printed in the console.

For example, if you want to find information about gcd() function in math module then pass the function name as an argument without parenthesis.

1. >>> help(math.gcd)

Help on built-in function gcd in module math:

gcd(…)

gcd(x, y) -> int

greatest common divisor of x and y

random module the random module which generates random numbers. First, you need to import the random module to use any of its functions. The random() function generates a random floating-point number between 0 and 1 and it produces a different value each time it is called .

 The syntax for random.randint() function is random.randint(start, stop) which generates a integer number between start and stop argument numbers (including both)

1. >>> import random

2. >>> print(random.random())

0.2551941897892144

3. >>> print(random.randint(5,10))

9

 

pip

Third-party modules or libraries can be installed and managed using Python’s package manager pip.

The syntax for pip is,

pip install module_name

Arrow Module

Arrow is a popular Python library that offers a sensible, human-friendly approach to creating, manipulating, formatting and converting dates, times, and timestamps.

To install the arrow module, open a command prompt window and type the below command from any location.

1. C:\> pip install arrow

Install arrow module using pip command .

Below code shows a simple usage of arrow module.

1. >>> import arrow

2. >>> a = arrow.utcnow()

3. >>> a.now()                                  #Current date and time is displayed using now() function

<Arrow [2017-12-23T20:45:14.490380+05:30]>

                                                                                    --O--

Function Definition and Calling the Function

(Discuss about function definition and function calling in python?)

You can create your own functions and use them as and where it is needed.



User-defined functions are reusable code blocks created by users to perform some specific task in the program.

In Python, a function definition consists of the def keyword, followed by

1. The name of the function. The function’s name has to adhere to the same naming rules as variables:

2. A list of parameters to the function are enclosed in parentheses and separated by commas. Some functions do not have any parameters at all while others may have one or more parameters.

3. A colon is required at the end of the function header. The first line of the function definition which includes the name of the function is called the function header.

4. Block of statements that define the body of the function start at the next line of the function header and they must have the same indentation level.

The def keyword introduces a function definition.

The term parameter or formal parameter is often used to refer to the variables as found in the function definition.

Calling and Executing the Function:

A Function can be executed by calling it. Calling the function actually performs the specified actions with the indicated parameters.

 

The syntax for function call or calling function is,

function_name(argument_1,argument_2,…,argument_n)

 

·Arguments are the actual value that is passed into the calling function.

·There must be a one to one correspondence between the formal parameters in the function definition and the actual arguments of the calling function.

·When a function is called, the formal parameters are temporarily “bound” to the arguments and their initial values are assigned through the calling function.

·A function should be defined before it is called and the block of statements in the function definition are executed only after calling the function.

·  Function definitions do not alter the flow of execution of the program.

· When you call a function, the control flows from the calling function to the function definition.

· Once the block of statements in the function definition is executed, then the control flows back to the calling function and proceeds with the next statement.

· Python interpreter keeps track of the flow of control between different statements in the program.

 

Before executing the code in the source program, the Python interpreter automatically defines few special variables. If the Python interpreter is running the source program as a stand-alone main program, it sets the special built-in __name__ variable to have a string value "__main__".

After setting up these special variables, the Python interpreter reads the program to execute the code found in it. All of the code that is at indentation level 0 gets executed. Block of statements in the function definition is not executed unless the function is called.

if __name__ == "__main__":

statement(s)

The special variable, __name__ with "__main__", is the entry point to your program. When Python interpreter reads the if statement and sees that __name__ does equal to "__main__", it will execute the block of statements present there.

 

Program to Demonstrate a Function with and without Arguments

1. def function_definition_with_no_argument():

2.         print("This is a function definition with NO Argument")

3. def function_definition_with_one_argument(message):

4.         print(f"This is a function definition with {message}")

5. def main():

6.         function_definition_with_no_argument()

7.         function_definition_with_one_argument("One Argument")

8. if __name__ == "__main__":

9.         main()

Output

This is a function definition with NO Argument

This is a function definition with One Argument

                                                                       

Program to Find the Area of Trapezium Using the Formula Area = (1/2) * (a + b) * h Where a and b Are the 2 Bases of Trapezium and h Is the Height

1. def area_trapezium(a, b, h):

2.         area = 0.5 * (a + b) * h

3.         print(f"Area of a Trapezium is {area}")

4. def main():

5.         area_trapezium(10, 15, 20)

6. if __name__ == "__main__":

7.         main()

Output

Area of a Trapezium is 250.0

 

Program to Demonstrate Using the Same Variable Name in Calling Function and Function Definition

1. god_name = input("Who is the God of Seas according to Greek Mythology?")

2. def greek_mythology(god_name):

3.         print(f"The God of seas according to Greek Mythology is {god_name}")

4. def main():

5.         greek_mythology(god_name)

6. if __name__ == "__main__":

7.         main()

Output

Who is the God of Seas according to Greek Mythology? Poseidon

The God of seas according to Greek Mythology is Poseidon

 

The return Statement and void Function

The function performs its specific task to calculate a value and return the value to the calling function so that it can be stored in a variable and used later. This can be achieved using the optional return statement in the function definition.

The syntax for return statement is,

return [expression_list]

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

·The return statement terminates the execution of the function definition in which it appears and returns control to the calling function. It can also return an optional value to its calling function.

·In Python, it is possible to define functions without a return statement. Functions like this are called void functions, and they return None.

·If you want to return a value using return statement from the function definition, then you have to assign the result of the function to a variable.

· A function can return only a single value, but that value can be a list or tuple. In some cases, it makes sense to return multiple values if they are related to each other. If so, return the multiple values separated by a comma which by default is constructed as a tuple by Python.

·When calling function receives a tuple from the function definition, it is common to assign the result to multiple variables by specifying the same number of variables on the left-hand side of the assignment as there were returned from the function definition. This is called tuple unpacking.

 

Program to Check If a 3 Digit Number Is Armstrong Number or Not

1. user_number = int(input("Enter a 3 digit positive number to check for Armstrong number"))

2. def check_armstrong_number(number):

3.         result = 0

4.         temp = number

5.         while temp != 0:

6.                     last_digit = temp % 10

7.                     result += pow(last_digit, 3)

8.                     temp = int(temp / 10)

9.         if number == result:

10.                   print(f"Entered number {number} is a Armstrong number")

11.       else:

12.                   print(f"Entered number {number} is not a Armstrong number")

13. def main():

14.       check_armstrong_number(user_number)

15. if __name__ == "__main__":

16.       main()

Output

Enter a 3 digit positive number to check for Armstrong number407

Entered number 407 is a Armstrong number

Program to Demonstrate the Return of Multiple Values from a Function Definition

1. def world_war():

2.         alliance_world_war = input("Which alliance won World War 2?")

3.         world_war_end_year = input("When did World War 2 end?")

4.         return alliance_world_war, world_war_end_year

5. def main():

6.         alliance, war_end_year = world_war()

7.         print(f"The war was won by {alliance} and the war ended in {war_end_year}")

8. if __name__ == "__main__":

9.         main()

Output

Which alliance won World War 2? Allies

When did World War 2 end? 1945

The war was won by Allies and the war ended in 1945

 

Scope and Lifetime of Variables

(Explain Scope and Lifetime of variable? Or local and global scope of a variable)

·Python programs have two scopes: global and local.

· A variable is a global variable if its value is accessible and modifiable throughout your program. Global variables have a global scope.

· A variable that is defined inside a function definition is a local variable. The local variable is created and destroyed every time the function is executed, and it cannot be accessed by any code outside the function definition. Local variables inside a function definition have local scope and exist as long as the function is executing.

· The lifetime of a variable refers to the duration of its existence.

· It is possible to access global variables from inside a function, as long as you have not defined a local variable with the same name. A local variable can have the same name as a global variable, but they are totally different so changing the value of the local variable has no effect on the global variable. Only the local variable has meaning inside the function in which it is defined.

Program to Demonstrate the Scope of Variables

1. test_variable = 5

2. def outer_function():

3.             test_variable = 60

4.             def inner_function():

5.                             test_variable = 100

6.                             print(f"Local variable value of {test_variable} having local scope to inner function is displayed")

7.             inner_function()

8.             print(f"Local variable value of {test_variable} having local scope to outer function is displayed ")

9. outer_function()

10. print(f"Global variable value of {test_variable} is displayed ")

Output

Local variable value of 100 having local scope to inner function is displayed

Local variable value of 60 having local scope to outer function is displayed

Global variable value of 5 is displayed

The variable name test_variable appears at different stages of the program. None of these variables are related to each other and are totally independent.

                                                                                    --O--

You can nest a function definition within another function definition. A nested function (inner function definition) can “inherit” the arguments and variables of its outer function definition. In other words, the inner function contains the scope of the outer function. The inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.

The inner function definition can be invoked by calling it from within the outer function definition.

Calculate and Add the Surface Area of Two Cubes. Use Nested Functions

1. def add_cubes(a, b):

2.         def cube_surface_area(x):

3.                     return 6 * pow(x, 2)

4.         return cube_surface_area(a) + cube_surface_area(b)

5. def main():

6.         result = add_cubes(2, 3)

7.         print(f"The surface area after adding two Cubes is {result}")

8. if __name__ == "__main__":

9.         main()

Output

The surface area after adding two Cubes is 78

 

(Discuss Different types of arguments in python with example?)

Default Parameters

Any calling function must provide arguments for all required parameters in the function definition but can omit arguments for default parameters. If no argument is sent for that parameter, the default value is used.

Usually, the default parameters are defined at the end of the parameter list, after any required parameters and non-default parameters cannot follow default parameters. The default value is evaluated only once.

Program to Demonstrate the Use of Default Parameters

1. def work_area(prompt, domain="Data Analytics"):

2.         print(f"{prompt} {domain}")

3. def main():

4.         work_area("Sam works in")

5.         work_area("Alice has interest in", "Internet of Things")

6. if __name__ == "__main__":

7.         main()

Output

Sam works in Data Analytics

Alice has interest in Internet of Things

 

Keyword Arguments

Whenever you call a function with some values as its arguments, these values get assigned to the parameters in the function definition according to their position. In the calling function, you can explicitly specify the argument name along with their value in the form kwarg = value. In the calling function, keyword arguments must follow positional arguments. All the keyword arguments passed must match one of the parameters in the function definition and their order is not important. No parameter in the function definition may receive a value more than once.


Program to Demonstrate the Use of Keyword Arguments

1. def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):

2.         print(f"This parrot wouldn't {action}, if you put {voltage}, volts through it.")

3.         print(f"Lovely plumage, the {type}")

4.         print(f"It's {state} !!!")

5. parrot(1000)

6. parrot(voltage=1000)

7. parrot(voltage=1000000, action='VOOOOOM')

8. parrot('a thousand', state='pushing up the daisies')

Output

This parrot wouldn't voom, if you put 1000, volts through it.

Lovely plumage, the Norwegian Blue

It's a stiff !!!

This parrot wouldn't voom, if you put 1000, volts through it.

Lovely plumage, the Norwegian Blue

It's a stiff !!!

This parrot wouldn't VOOOOOM, if you put 1000000, volts through it.

Lovely plumage, the Norwegian Blue

It's a stiff !!!

This parrot wouldn't voom, if you put a thousand, volts through it.

Lovely plumage, the Norwegian Blue

It's pushing up the daisies !!!

 

The parrot() function definition accepts one required parameter (voltage) and three optional parameters (state, action, and type). In line one positional argument is specified.

In line , keyword argument is used to pass a value to non-optional parameter. Two keyword arguments are specified in and one positional and one keyword arguments are stated in .

Also, the following functional calls are invalid.

parrot() # required argument missing

parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument

parrot(110, voltage=220) # duplicate value for the same argument

parrot(actor='John Cleese') # unknown keyword argument

*args and **kwargs(Discuss about *args and **kwargs in detail?)

*args and **kwargs are mostly used as parameters in function definitions. *args and **kwargs allows you to pass a variable number of arguments to the calling function. Here variable number of arguments means that the user does not know in advance about how many arguments will be passed to the calling function.

 *args as parameter in function definition allows you to pass a non-keyworded, variable length tuple argument list to the calling function.

**kwargs as parameter in function definition allows you to pass keyworded, variable length dictionary argument list to the calling function. *args must come after all the positional parameters and **kwargs must come right at the end.

Program to Demonstrate the Use of *args and **kwargs

1. def cheese_shop(kind, *args, **kwargs):

2.         print(f"Do you have any {kind} ?")

3.         print(f"I'm sorry, we're all out of {kind}")

4.         for arg in args:

5.                     print(arg)

6.         print("-" * 40)

7.         for kw in kwargs:

8.                     print(kw, ":", kwargs[kw])

9. def main():

10.       cheese_shop("Limburger", "It's very runny, sir.",

"It's really very, VERY runny, sir.",

shop_keeper="Michael Palin",

client="John Cleese",

sketch="Cheese Shop Sketch")

11. if __name__ == "__main__":

12. main()

Output

Do you have any Limburger ?

I'm sorry, we're all out of Limburger

It's very runny, sir.

It's really very, VERY runny, sir.

----------------------------------------

shop_keeper : Michael Palin

client : John Cleese

sketch : Cheese Shop Sketch

 

The function definition cheese_shop() has three parameters where the first parameter is a positional parameter and the last two parameters are *args and **kwargs . In the statement blocks of the function definition * and ** are not used with args and kwargs. In the function call 10 the first argument is assigned to the first parameter in the function definition.

After the first argument, the remaining series of arguments separated by commas are assigned to *args until the keyword arguments are encountered. All the keyword arguments in the calling function are assigned to **kwargs. You can work with **kwargs just like you work with dictionaries. The order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the calling function. Loops are used to display the items in args and kwargs .


Command Line Arguments

A Python program can accept any number of arguments from the command line. Command line arguments is a methodology in which user will give inputs to the program through the console using commands. You need to import sys module to access command line arguments. All the command line arguments in Python can be printed as a list of string by executing sys.argv.

Program to Demonstrate Command Line Arguments in Python

1. import sys

2. def main():

3.         print(f"sys.argv prints all the arguments at the command line including file name {sys.argv}")

4.         print(f"len(sys.argv) prints the total number of command line arguments including file name {len(sys.argv)}")

5.         print("You can use for loop to traverse through sys.argv")

6.         for arg in sys.argv:

7.                     print(arg)

8. if __name__ == "__main__":

9. main()

Output

C:\Python_Programming\ch4>python Program_4.12.py arg_1 arg_2 arg_3

sys.argv prints all the arguments at the command line including file name ['Program_4.12.py', 'arg_1', 'arg_2', 'arg_3']

len(sys.argv) prints the total number of command line arguments including file name 4

You can use for loop to traverse through sys.argv

Program_4.12.py

arg_1

arg_2

arg_3

String

A string consists of a sequence of characters, which includes letters, numbers, punctuation marks and spaces. To represent strings, you can use a single quote, double quotes or triple quotes. Python strings are of str data type .

Creating and Storing Strings

Strings are another basic data type available in Python. They consist of one or more characters

surrounded by matching quotation marks. For example,

1. >>> single_quote = 'This is a single message'

2. >>> double_quote = "Hey it is my book"

3. >>> single_char_string = "A"

4. >>> empty_string = ""

5. >>> empty_string = ''

6. >>> single_within_double_quote = "Opportunities don't happen. You create them."

7. >>> double_within_single_quote = "Why did she call the man 'smart'?"

8. >>> same_quotes = 'I\'ve an idea'

9. >>> triple_quote_string = '''This

… is

… triple

… quote'''

10. >>> triple_quote_string

'This\nis\ntriple\nquote'

11. >>> type(single_quote)

<class 'str'>

 

The str() Function

The str() function returns a string which is considered an informal or nicely printable representation of the given object. The syntax for str() function is,

str(object)

It returns a string version of the object. If the object is not provided, then it returns an empty string.

1. >>> str(10)

'10'                   #Here integer type is converted to string type. single quotes represent the string

2. >>> create_string = str()             # The create_string is an empty string

3. >>> type(create_string)

<class 'str'>

 

Basic String Operations

( Explain  Basic String Operations in python?).

In Python, strings can also be concatenated using + sign and * operator is used to create a repeated sequence of strings.

1. >>> string_1 = "face"

2. >>> string_2 = "book"

3. >>> concatenated_string = string_1 + string_2

4. >>> concatenated_string

'facebook'

5. >>> concatenated_string_with_space = "Hi " + "There"

6. >>> concatenated_string_with_space

'Hi There'

7. >>> singer = 50 + "cent"

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unsupported operand type(s) for +: 'int' and 'str'

8. >>> singer = str(50) + "cent"

9. >>> singer

'50cent'

10. >>> repetition_of_string = "wow" * 5

11. >>> repetition_of_string

'wowwowwowwowwow'

 

You cannot concatenate string data type with integer data type . You need to convert integer type to string type and then concatenate the values . You can use the multiplication operator * on a string ­. It repeats the string the number of times you specify and the string value “wow” is repeated five times .

 

in and not in membership operators:

You can check for the presence of a string in another string using in and not in membership operators. It returns either a Boolean True or False. The in operator evaluates to True if the string value in the left operand appears in the sequence of characters of string value in right operand. The not in operator evaluates to True if the string value in the left operand does not appear in the sequence of characters of string value in right operand.

1. >>> fruit_string = "apple is a fruit"

2. >>> fruit_sub_string = "apple"

3. >>> fruit_sub_string in fruit_string

True

4. >>> another_fruit_string = "orange"

5. >>> another_fruit_string not in fruit_string

True

 

String Comparison

You can use (>, <, <=, >=, ==, !=) to compare two strings resulting in either Boolean True or False value. Python compares strings using ASCII value of the characters. For example,

1. >>> "january" == "jane"

False

2. >>> "january" != "jane"

True

3. >>> "january" < "jane"

False

4. >>> "january" > "jane"

True

5. >>> "january" <= "jane"

False

6. >>> "january" >= "jane"

True

7. >>> "filled" > ""

True

String equality is compared using == (double equal sign). String inequality is compared using != sign

Suppose you have string_1 as "january" and string_2 as "jane". The first two characters from string_1 and string_2 (j and j) are compared. As they are equal, the second two characters are compared (a and a). Because they are also equal, the third two characters (n and n) are compared. Since the third characters are also equal, the fourth character from both the strings are compared and because 'u' has greater ASCII value than 'e', string_1 is greater than string_2. You can even compare a string against an empty string.

 

Built-In Functions Used on Strings

There are many built-in functions for which a string can be passed as an argument

len() The len() function calculates the number of characters in a string. The white space characters are also counted.

max() The max() function returns a character having highest ASCII value.

min() The min() function returns character having lowest ASCII value.

For example,

1. >>> count_characters = len("python")

2. >>> count_characters

6

3. >>> max("axel")

'x'

4. >>> min("brad")

'a'

Characters with highest and lowest ASCII value are calculated using max() and min() functions.

 

Accessing Characters in String by Index Number

Each character in the string occupies a position in the string. Each of the string’s character  corresponds to an index number. The first character is at index 0; the next character is at index 1, and so on. The length of a string is the number of characters in it. You can access each character in a string using a subscript operator i.e., a square bracket. Square brackets are used to perform indexing in a string to get the value at a specific index or position. This is also called subscript operator.

The index breakdown for the string "be yourself" assigned to word_phrase string variable is shown below.




The syntax for accessing an individual character in a string is as shown below.

string_name[index]

where index is usually in the range of 0 to one less than the length of the string. The value of index should always be an integer and indicates the character to be accessed.

For example,

1. >>> word_phrase = "be yourself"

2. >>> word_phrase[0]

'b'

3. >>> word_phrase[1]

'e'

4. >>> word_phrase[2]

' '

5. >>> word_phrase[3]

'y'

6. >>> word_phrase[10]

'f'

7. >>> word_phrase[11]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: string index out of range

 

By referring to the index numbers in square bracket, you can access individual characters in a string.

You can also access individual characters in a string using negative indexing. If you have a long string and want to access end characters in the string, then you can count backward from the end of the string starting from an index number of −1. The negative index breakdown for the string “be yourself” assigned to word_phrase string variable is shown below.





1. >>> word_phrase[-1]

'f'

2. >>> word_phrase[-2]

'l'

By using negative index number of −1, you can print the character ‘f’ , the negative index

number of −2 prints the character ‘l’ . You can benefit from using negative indexing when you want to access characters at the end of a long string.

 

String Slicing and Joining

(Explain Slicing and Joining in strings?)

The "slice" syntax is a handy way to refer to sub-parts of sequence of characters within an original string. The syntax for string slicing is,

string_name[start:end[:step]]

Colon is used to specify range values

With string slicing, you can access a sequence of characters by specifying a range of index numbers separated by a colon. String slicing returns a sequence of characters beginning at start and extending up to but not including end. The start and end indexing values have to be integers. String slicing can be done using either positive or negative indexing.





healthy_drink = "green tea"

 

healthy_drink[0:3]

'gre'

a sequence of characters or a substring is extracted from the beginning (0th Index) up to the third character (2nd Index)

healthy_drink[:5]

'green'

If the start index is omitted, the slicing starts from the first index number (0th Index) up to the end index (excluding) in the string. In substring starting from 0th index to 4th index is printed.

healthy_drink[6:]

'tea'

If the end index is omitted, slicing starts from the start index and goes up to the end of the string index.Substring starting from 6th index to the end of the string is displayed

healthy_drink[:]

'green tea'

If both the start and end index values are omitted then the entire string is displayed

healthy_drink[4:4]

''

If the start index is equal to or higher than the end index, then it results in an empty string

healthy_drink[6:20]

'tea'

If the end index number is beyond the end of the string, it stops at the end of the string

 

In string slicing, start index value (including) is where slicing starts and end index value (excluding) is where the slicing ends.




The negative index can be used to access individual characters in a string. Negative indexing starts with −1 index corresponding to the last character in the string and then the index decreases by one as we move to the left.

1. >>> healthy_drink[-3:-1]

'te'

2. >>> healthy_drink[6:-1]

'te'

You need to specify the lowest negative integer number in the start index position when using negative index numbers as it occurs earlier in the string . You can also combine positive and negative indexing numbers .

 

Specifying Steps in Slice Operation

In the slice operation, a third argument called step which is an optional can be specified along with the start and end index numbers. This step refers to the number of characters that can be skipped after the start indexing character in the string. The default value of step is one.

For example,

1. >>> newspaper = "new york times"

2. >>> newspaper[0:12:4]

'ny'

3. >>> newspaper[::4]

'ny e'

In the slice [0:12:4] takes the character at 0th index which is n and will print every 4th character in the string extending till the 12th character (excluding).

You can omit both start and end index values to consider the entire range of characters in the string by specifying two colons while considering the step argument which will specify the number of characters to skip .

 

Write Python Code to Determine Whether the Given String Is a Palindrome or Not Using Slicing

1. def main():

2.         user_string = input("Enter string: ")

3.         if user_string == user_string[::-1]:

4.                     print(f"User entered string is palindrome")

5.         else:

6.                     print(f"User entered string is not a palindrome")

7. if __name__ == "__main__":

8.         main()

Output

Case 1:

Enter string: madam

User entered string is palindrome

 

Case 2:

Enter string: cat

User entered string is not a palindrome

 

User entered string value is stored in user_string variable . The user_string is reversed using string slicing with −1 and is compared with non-reversed user_string. If both are equal, then the string is palindrome else it is not a palindrome

 

Joining Strings Using join() Method

Strings can be joined with the join() string. The join() method provides a flexible way to concatenate strings. The syntax of join() method is,

string_name.join(sequence)

Here sequence can be string or list.

If the sequence is a string, then join() function inserts string_name between each character of the string sequence and returns the concatenated string.

If the sequence is a list, then join() function inserts string_name between each item of list sequence and returns the concatenated string. It should be noted that all the items in the list should be of string type.

1. >>> date_of_birth = ["17", "09", "1950"]

2. >>> ":".join(date_of_birth)

'17:09:1950'

3. >>> social_app = ["instagram", "is", "an", "photo", "sharing", "application"]

4. >>> " ".join(social_app)

'instagram is an photo sharing application'

5. >>> numbers = "123"

6. >>> characters = "amy"

7. >>> password = numbers.join(characters)

8. >>> password

'a123m123y'

 

Split Strings Using split() Method

The split() method returns a list of string items by breaking up the string using the delimiter string. The syntax of split() method is,

string_name.split([separator [, maxsplit]])

Here separator is the delimiter string and is optional. A given string is split into list of strings based on the specified separator. If the separator is not specified then whitespace is considered as the delimiter string to separate the strings.

If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit + 1 items). If maxsplit is not specified or −1, then there is no limit on the number of splits.

 

1. >>> inventors = "edison, tesla, marconi, newton"

2. >>> inventors.split(",")

['edison', ' tesla', ' marconi', ' newton']

3. >>> watches = "rolex hublot cartier omega"

4. >>> watches.split()

['rolex', 'hublot', 'cartier', 'omega']

 

Strings Are Immutable

As strings are immutable, it cannot be modified. The characters in a string cannot be changed once a string value is assigned to string variable. However, you can assign different string values to the same string variable.

1. >>> immutable = "dollar"

2. >>> immutable[0] = "c"

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'str' object does not support item assignment

3. >>> string_immutable = "c" + immutable[1:]

4. >>> string_immutable

'collar'

5. >>> immutable = "rollar"

6. >>> immutable

'rollar'

You cannot change the string value once it has been assigned to a string variable. What you can do is create a new string that is a variation of the original string . Also, assigning a whole new string value to existing string variable is allowed .

String Traversing

Since the string is a sequence of characters, each of these characters can be traversed using the for loop.


Program to Demonstrate String Traversing Using the for Loop

1. def main():

2.         alphabet = "google"

3.         index = 0

4.         print(f"In the string '{alphabet}'")

5.         for each_character in alphabet:

6.                     print(f"Character '{each_character}' has an index value of {index}")

7.                     index += 1

8. if __name__ == "__main__":

9.         main()

Output

In the string 'google'

Character 'g' has an index value of 0

Character 'o' has an index value of 1

Character 'o' has an index value of 2

Character 'g' has an index value of 3

Character 'l' has an index value of 4

Character 'e' has an index value of 5

 

Program to Print the Characters Which Are Common in Two Strings

1. def common_characters(string_1, string_2):

2.         for letter in string_1:

3.                     if letter in string_2:

4.                                 print(f"Character '{letter}' is found in both the strings")

5. def main():

6.         common_characters('rose', 'goose')

7. if __name__ == "__main__":

8.         main()

Output

Character 'o' is found in both the strings

Character 's' is found in both the strings

Character 'e' is found in both the strings

 

Write Python Program to Count the Total Number of Vowels, Consonants and Blanks in a String

1. def main():

2.             user_string = input("Enter a string: ")

3.             vowels = 0

4.             consonants = 0

5.             blanks = 0

6.             for each_character in user_string:

7. if(each_character == 'a' or each_character == 'e' or each_character == 'i' or each_character == 'o' or each_character == 'u'):

8.             vowels += 1

9.             elif "a" < each_character < "z":

10.                           consonants += 1

11.           elif each_character == " ":

12.                           blanks += 1

13.           print(f"Total number of Vowels in user entered string is {vowels}")

14.           print(f"Total number of Consonants in user entered string is {consonants}")

15.           print(f"Total number of Blanks in user entered string is {blanks}")

16. if __name__ == "__main__":

17.           main()

Output

Enter a string: may god bless you

Total number of Vowels in user entered string is 5

Total number of Consonants in user entered string is 9

Total number of Blanks in user entered string is 3

 

Write Python Program to Calculate the Length of a String Without Using Built-In len() Function

1. def main():

2. user_string = input("Enter a string: ")

3. count_character = 0

4. for each_character in user_string:

5. count_character += 1

6. print(f"The length of user entered string is {count_character} ")

7. if __name__ == "__main__":

8. main()

Output

Enter a string: To answer before listening that is folly and shame

The length of user entered string is 50

 

String Methods

(Explain  String Methods in python?)

capitalize()The capitalize() method returns a copy of the string with its first character capitalized and the rest lowercased.

string_name.capitalize()

casefold()The casefold() method returns a casefolded copy of the string. Casefolded strings may be used for caseless matching.

string_name.casefold()

center()

The method center() makes string_name centered by taking width parameter into account. Padding is specified by parameter fillchar. Default filler is a space.

string_name.center(width[,fillchar])

count()

The method count(), returns the number of nonoverlapping occurrences of substring in the range [start,end]. Optional arguments start and end are interpreted as in slice notation.

string_name.count(substring [,start [, end]])

endswith()

This method endswith(), returns True if the string_name ends with the specified suffix substring, otherwise returns False. With optional start, test beginning at that position. With optional end, stop comparing at that position.

string_name.endswith(suffix[,start[, end]])

find()

Checks if substring appears in string_name or if substring appears in string_name specified by starting index start and ending index end. Return position of the first character of the first instance of string substring in string_name, otherwise return –1 if substring not found in string_name.

string_name. find(substring[,start[, end]])

isalnum()The method isalnum() returns Boolean True if all characters in the string are alphanumeric and there is at least one character, else it returns Boolean False.

string_name.isalnum()


isalpha()The method isalpha(), returns Boolean True if all characters in the string are alphabetic and there is at least one character, else it returns Boolean False.

string_name.isalpha()


isdecimal()The method isdecimal(), returns Boolean True if all characters in the string are decimal characters and there is at least one character, else it returns Boolean False.

string_name.isdecimal()

 

isdigit()The method isdigit() returns Boolean True if all characters in the string are digits and there is at least one character, else it returns Boolean False.

string_name.isdigit()

isidentifier()The method isidentifier() returns Boolean True if the string is a valid identifier, else it returns Boolean False.

string_name.isidentifier()

islower() The method islower() returns Boolean True if all characters in the string are lowercase, else it returns Boolean False.

string_name.islower()

isspace()The method isspace() returns Boolean True if there are only whitespace characters in the string and there is at least one character, else it returns Boolean False.

string_name.isspace()

isnumeric()The method isnumeric(), returns Boolean True if all characters in the string_name are numeric characters, and there is at least one character, else it returns Boolean False. Numeric characters include digit characters and all characters that have the Unicode numeric value property.

string_name.isnumeric()

istitle() The method istitle() returns Boolean True if the string is a title cased string and there is at least one character, else it returns Boolean False.

string_name.istitle()

isupper() The method isupper() returns Boolean True if all cased characters in the string are uppercase and there is at least one cased character, else it returns Boolean False.

string_name.isupper()

upper()The method upper() converts lowercase letters in string to uppercase.

string_name.upper()

lower()The method lower() converts uppercase letters in string to lowercase.

string_name.lower()

ljust()  In the method ljust(), when you provide the string to the method ljust(), it returns the string left justified. Total length of string is defined in first parameter of method width. Padding is done as defined in second parameter fillchar. (default is space).

 string_name.ljust(width[,fillchar])

rjust() In the method rjust(), when you provide the string to the method rjust(), it returns the string right justified. The total length of string is defined in the first parameter of the method, width. Padding is done as defined in second parameter fillchar. (default is space).

string_name.rjust(width[,fillchar])

title() The method title() returns “titlecased” versions of string,that is, all words begin with uppercase characters and the rest are lowercase.

string_name.title()

swapcase() The method swapcase() returns a copy of the string with uppercase characters converted to lowercase and vice versa.

string_name.swapcase()

splitlines()  The method splitlines() returns a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is givenand true.

string_name.splitlines([keepends])

startswith()  The method startswith() returns Boolean True if the string starts with the prefix, otherwise return False. With optional start, test string_name beginning at that position. With optional end, stop comparing string_name at that position.

string_name.startswith(prefix[,start[, end]])


strip()The method lstrip() returns a copy of the string_name in which specified chars have been stripped from both side of the string. If char is not specified then space is taken as default.

string_name.strip([chars])

rstrip()The method rstrip() removes all trailing whitespace of string_name.

string_name.rstrip([chars])

lstrip()The method lstrip() removes all leading whitespace in string_name.

string_name.lstrip([chars])

replace() The method replace() replaces all occurrences of old in string_name with new. If the optional argument max is given, then only the first max occurrences are replaced.

string_name. replace(old,new[, max])

zfill()The method zfill() pads the string_name on the left with zeros to fill width.

string_name.zfill(width)

For example,

1. >>> fact = "Abraham Lincoln was also a champion wrestler"

2. >>> fact.isalnum()

False

3. >>> "sailors".isalpha()

True

4. >>> "2018".isdigit()

True

5. >>> fact.islower()

False

6. >>> "TSAR BOMBA".isupper()

True

7. >>> "columbus".islower()

True

8. >>> warriors = "ancient gladiators were vegetarians"

9. >>> warriors.endswith("vegetarians")

True

10. >>> warriors.startswith("ancient")

True

11. >>> warriors.startswith("A")

False

12. >>> warriors.startswith("a")

True

13. >>> "cucumber".find("cu")

0

14. >>> "cucumber".find("um")

3

15. >>> "cucumber".find("xyz")

-1

16. >>> warriors.count("a")

5

17. >>> species = "charles darwin discovered galapagos tortoises"

18. >>> species.capitalize()

'Charles darwin discovered galapagos tortoises'

19. >>> species.title()

'Charles Darwin Discovered Galapagos Tortoises'

20. >>> "Tortoises".lower()

'tortoises'

21. >>> "galapagos".upper()

'GALAPAGOS'

22. >>> "Centennial Light".swapcase()

'cENTENNIAL lIGHT'

23. >>> "history does repeat".replace("does", "will")

'history will repeat'

24. >>> quote = " Never Stop Dreaming "

25. >>> quote.rstrip()

' Never Stop Dreaming'

26. >>> quote.lstrip()

'Never Stop Dreaming '

27. >>> quote.strip()

'Never Stop Dreaming'

28. >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()

['ab c', '', 'de fg', 'kl']

29. >>> "scandinavian countries are rich".center(40)

'scandinavian countries are rich'

 

Write Python Program That Accepts a Sentence and Calculate the Number of Words, Digits, Uppercase Letters and Lowercase Letters

1. def string_processing(user_string):

2.         word_count = 0

3.         digit_count = 0

4.         upper_case_count = 0

5.         lower_case_count = 0

6.         for each_char in user_string:

7.                     if each_char.isdigit():

8.                                 digit_count += 1

9.                     elif each_char.isspace():

10.                               word_count += 1

11.                   elif each_char.isupper():

12.                               upper_case_count += 1

13.                   elif each_char.islower():

14.                               lower_case_count += 1

15.                   else:

16.                               pass

17.       print(f"Number of digits in sentence is {digit_count}")

18.       print(f"Number of words in sentence is {word_count + 1}")

19.       print(f"Number of upper case letters in sentence is {upper_case_count}")

20.       print(f"Number of lower case letters in sentence is {lower_case_count}")

21. def main():

22.       user_input = input("Enter a sentence ")

23.       string_processing(user_input)

24. if __name__ == "__main__":

25.       main()

Output

Enter a sentence The Eiffel Tower in Paris is 324m tall

Number of digits in sentence is 3

Number of words in sentence is 8

Number of upper case letters in sentence is 4

Number of lower case letters in sentence is 24

 

Write Python Program to Convert Uppercase Letters to Lowercase and Vice Versa

1. def case_conversion(user_string):

2.         convert_case = str()

3.         for each_char in user_string:

4.                     if each_char.isupper():

5.                                 convert_case += each_char.lower()

6.                     else:

7.                                    convert_case += each_char.upper()

8.         print(f"The modified string is {convert_case}")

9. def main():

10.       input_string = input("Enter a string ")

11.       case_conversion(input_string)

12. if __name__ == "__main__":

13.       main()

Output

Enter a string ExquiSITE

The modified string is eXQUIsite

Write Python Program to Replace Comma-Separated Words with Hyphens and Print Hyphen-Separated Words in Ascending Order

1. def replace_comma_with_hyphen(comma_separated_words):

2.         split_words = comma_separated_words.split(",")

3.         split_words.sort()

4.         hyphen_separated_words = "-".join(split_words)

5.         print(f"Hyphen separated words in ascending order are'{hyphen_separated_words}'")

6. def main():

7.         comma_separated_words = input("Enter comma separated words ")

8.         replace_comma_with_hyphen(comma_separated_words)

9. if __name__ == "__main__":

10.       main()

Output

Enter comma separated words global,education

Hyphen separated words in ascending order are 'education-global'

 

Write Python Program to Count the Occurrence of User-Entered Words in a Sentence

1. def count_word(word_occurrence, user_string):

2.         word_count = 0

3.         for each_word in user_string.split():

4.                     if each_word == word_occurrence:

5.                                 word_count += 1

6.                     print(f"The word '{word_occurrence}' has occurred {word_count} times")

7. def main():

8.         input_string = input("Enter a string ")

9.         user_word = input("Enter a word to count its occurrence ")

10.       count_word(user_word, input_string)

11. if __name__ == "__main__":

12.       main()

Output

Enter a string You cannot end a sentence with because because because is a conjunction

Enter a word to count its occurrence because

The word 'because' has occurred 3 times

 

Formatting Strings

(Write about formatted strings in Python?)

Python supports multiple ways to format text strings. These include %-formatting and str.format().

A new string formatting mechanism referred to as "f-strings" is becoming popular among Python community. In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions within curly braces '{' and '}'.

 

The %-formatting is limited as to the types it supports. Only int, str and doubles can be formatted. All other types are either not supported or converted to one of these types before formatting. In addition, there’s a well-known trap when a single value is passed.

The str.format() formatting was added to address some of these problems with %-formatting. In particular, it uses standard function call syntax and therefore supports multiple parameters. However, str.format() is not without its issues.

An f-string example

1. >>> f'The value is {value}.'

'The value is 80.'

The f-strings provide a concise, readable way to include the value of Python expressions inside strings.


Backslashes may not appear inside the expression portions of f-strings, so you cannot use them. Backslash escapes may appear inside the string portions of an f-string. For example, to escape quotes inside f-strings:

1. >>> f'{\'quoted string\'}'

File "<stdin>", line 1

SyntaxError: f-string expression part cannot include a backslash

Backslashes are not supported within the curly braces when f-strings are used.

You can use a different type of quote inside the expression:

1. >>> f'{"quoted string"}'

'quoted string'

Use different types of quotes within and outside the curly braces.

Format Specifiers

Format specifiers may also contain evaluated expressions.

The syntax for f-string formatting operation is,

f'string_statements {variable_name [: {width}.{precision}]}’

The f character should be prefixed during f-string formatting.

The string_statement is a string consisting of a sequence of characters. Within curly braces, you specify the variable_name whose value will be displayed. Specifying width and precision values are optional. If they are specified, then both width and precision should be included within curly braces.

Also, using variable_name along with either width or precision values should be separated by a colon. You can pad or create space around variable_name value element through width value.

By default, strings are left-justified and numbers are right-justified.

Precision refers to the total number of digits that will be displayed in a number. This includes the decimal point and all the digits, i.e., before and after the decimal point. For example,

1. >>> width = 10

2. >>> precision = 5

3. >>> value = 12.34567

4. >>> f'result: {value:{width}.{precision}}'

'result: 12.346'

5. >>> f'result: {value:{width}}'

'result: 12.34567'

6. >>> f'result: {value:.{precision}}'

'result: 12.346'

Different ways of string formatting in f-strings.

Escape Sequences



Escape Sequences are a combination of a backslash (\) followed by either a letter or a combination of letters and digits. Escape sequences are also called as control sequences.

1. >>> print("You can break \

… single line to \

… multiple lines")

You can break single line to multiple lines

2. >>> print('print backslash \\ inside a string ')

print backslash \ inside a string

3. >>> print('print single quote \' within a string')

print single quote ' within a string

4. >>> print("print double quote \" within a string")

print double quote " within a string

5. >>> print("First line \nSecond line")

First line

Second line

6. >>> print("tab\tspacing")

tab spacing

7. >>> print("same\rlike")

like

8. >>> print("He\bi")

Hi

9. >>> print("\u20B9")

10. >>> print("\046")

&

11. >>> print("\x24")

$

Raw Strings

A raw string is created by prefixing the character r to the string. In Python, a raw string ignores all types of formatting within a string including the escape characters.

1. >>> print(r"Bible Says, \"Taste and see that the LORD is good; blessed is the man who takes refuge in him.\"")

Bible Says, \"Taste and see that the LORD is good; blessed is the man who takes refuge in  him.\"

As you can see in the output, by constructing a raw string you can retain quotes, backslashes that are used to escape and other characters, as in .

 

Unicodes

· Fundamentally, computers just deal with numbers. They store letters and other characters by assigning a number for each one.

·  Before Unicode was invented, there were hundreds of different systems, called character encodings for assigning these numbers.

· These early character   encodings were limited and could not contain enough characters to cover all the world’s languages.

· Even for a simple language like English, no single encoding was adequate for all the letters,  punctuation, and technical symbols in common use.

· The Unicode Standard provides a unique number for every character, no matter what platform, device, application or language.

· It has been adopted by all modern software providers and now allows data to be transported through many different platforms, devices and applications without corruption.

· Unicode can be implemented by different character encodings. The Unicode Standard defines Unicode Transformation Formats like UTF-8, UTF-16, and UTF-32, and several other encodings are in use. The most commonly used encodings are UTF-8, UTF-16 and UCS-2 (Universal Coded Character Set), a precursor of UTF-16. UTF-8 is dominantly used by websites (over 90%), uses one byte for the first 128 code points and up to 4 bytes for other characters.

· Regular Python strings are not Unicode: they are just plain bytes. To create a Unicode string, use the 'u' prefix on the string literal. For example,

>>> unicode_string = u'A unicode \u018e string \xf1'

>>> unicode_string

'A unicode string ñ'

A Unicode string is a different type of object from regular "str" string type.

No comments:

Post a Comment