Python

Python Tutorial with Exercises99 min read

For beginner Python programmers, the main ones are that the print statement of Python 2.x is now a printfunction in Python 3, the raw_input function in Python 2.x is replaced by the input function in Python 3, and an integer division such as 2/3 in Python 2.x is now a real division in Python 3.

So be aware that there are some significant differences between Python 3 and earlier versions.




The following tutorials help you to learn Python 3 programming language by basicly.

Python 3 Tutorials

Python Print

The print function in Python is used to display output to the console or terminal. Here is an example of how to use it:

Program1.py

This will print the string “Hello, World!” to the console.

You can also use the print function to print the value of a variable. For example:

Program2.py

This will print the string “John” to the console.

You can also use the print function to print multiple values, separating them with a comma. For example:

Program3.py

Python 3 Input

Input means getting data into your program from an input device (usually the keyboard).

Python needs a place to store whatever value is input. These storage places are known as variables, and have to have a name.

The input function in Python allows the user to enter input from the console or terminal. Here is an example of how to use it:

Program4.py

The above Python statement, when executed (i.e. run) will output to the screen whatever is within the quote marks. This text is sometimes refered to as a “Enter some thing:”. Python then waits for you to enter something from the keyboard.

Type in some text and then press the Enter key on the keyboard. Whatever you typed in before you hit the Enter key is stored into the variable called text. text is the variable where the input data is stored.

This will prompt the user to enter their name, and then it will print a greeting using the name that the user entered.

The input function returns a string, so if you want to use the input as a number (integer or float), you will need to convert it to the appropriate type. For example:

Program5.py

This will prompt the user to enter their age, and then it will convert the input to an integer and print a message using the age.

The Assignment symbol =

In Python, the assignment operator is the equals sign =. It is used to assign a value to a variable. For example:

This assigns the value 10 to the variable x.

You can also use the assignment operator to assign the value of an expression to a variable. For example:

This assigns the value 6 to the variable x.

You can also use the assignment operator to assign the value of one variable to another variable. For example:

This assigns the value of x (which is 10) to the variable y.

It’s important to note that the assignment operator = is different from the equality operator ==, which is used to test if two values are equal. For example:

Program6.py

This will print “x and y are not equal”, because x is not equal to y.

Built-in functions

input(), int() and float() , str() are built-in Python functions. They can be used at any time in any Python statement.

The input function allows the user to enter input from the console or terminal. It returns a string, so if you want to use the input as a number (integer or float), you will need to convert it to the appropriate type using int or float.

The int function converts a value to an integer. If the value is a floating-point number, it will be rounded down to the nearest integer.

The float function converts a value to a floating-point number.

The str function converts a value to a string. This can be useful if you need to concatenate a string with a number, for example.

Here are some examples of how these functions can be used:

Program7.py

Data types of input values

The type function is a built-in function in Python that returns the data type of a value.

Here is an example of how to use it:

Program8.py

This can be useful for debugging, or for checking the data type of a value before performing certain operations on it. For example, you might want to make sure that a value is a string before concatenating it with another string.

Program9.py: Print given text

In Python, the string "\n" represents a newline character, which is a special character that causes the text that follows it to be displayed on a new line.

Here is an example of how to use it:

Program10.py

To use a variable in Python, you first need to assign a value to the variable. This is done using the assignment operator =. For example:

Program11.py

You can also reassign a new value to a variable by using the assignment operator again. For example:

Program12.py

It’s important to choose descriptive and meaningful variable names, as this will make your code easier to read and understand.

Program3.py : Calculate the Average of 3 Numbers

This code calculates the average of three numbers that are entered by the user. Here’s how it works:

The code prompts the user to enter the first, second, and third numbers, and stores them in the variables number1, number2, and number3.

The code adds the three numbers together and stores the result in the total variable.

The code divides the total by 3 to calculate the average, and stores the result in the average variable.

The code prints the value of the average variable using two different print statements.

Here’s what the output might look like if the user enters the numbers 15, 20, and 25:

Program14.py: Calculate the Average of Numbers in a Given List

This code calculates the average of a list of numbers that are entered by the user. Here’s how it works:

The code prompts the user to enter the number of elements to be inserted into the list, and stores it in the number variable.

The code creates an empty list called array, and then uses a for loop to prompt the user to enter each element of the list. The elements are added to the list using the append method.

The code calculates the sum of the elements in the list using the sum function, and divides it by the number of elements to calculate the average. The result is stored in the avg variable.

The code prints the value of the avg variable, rounded to two decimal places using the round function.

Here’s what the output might look like if the user enters the numbers 10, 20, and 30:

Program15.py : Calculate the average of 3 numbers using “while”

This code calculates the average of three numbers that are entered by the user using a while loop. Here’s how it works:

The code initializes the variables total and count to 0.0 and 0, respectively.

The code enters a while loop that will continue to run as long as count is less than 3.

Inside the loop, the code prompts the user to enter a number and stores it in the number variable.

The code increments the value of count by 1 using count = count + 1.

The code adds the value of number to the total using total = total + number.

After the loop has finished running 3 times, the code calculates the average by dividing total by 3 and stores the result in the average variable.

The code prints the value of average, converted to a string using the str function.

Here’s what the output might look like if the user enters the numbers 10, 20, and 30:

Examples of use of arithmetic operators

Program16.py : Using operands

This code demonstrates the use of several arithmetic operators in Python:

The + operator is used to add two values together. In this case, it prints the value 3.

The - operator is used to subtract one value from another. In this case, it prints the value 3.

The * operator is used to multiply two values together. In this case, it prints the value 40.

The / operator is used to divide one value by another. In this case, it prints the value 2.0.

The % operator is used to calculate the remainder when one value is divided by another. In this case, it prints the value 0.

The // operator is used to perform floor division, which always truncates the fractional remainder. In this case, it prints the value 3.

The - operator can also be used to negate a value. In this case, it prints the value -10.

The ** operator is used to raise a value to a power. In this case, it prints the value 243.

Examples of use of arithmetic operators
Examples of use of arithmetic operators

Program17.py :

This code demonstrates the use of several arithmetic operators in Python, using floating-point numbers as the operands:

The + operator is used to add two values together. In this case, it prints the value 3.0.

The - operator is used to subtract one value from another. In this case, it prints the value 3.0.

The * operator is used to multiply two values together. In this case, it prints the value 12.0.

The / operator is used to divide one value by another. In this case, it prints the value 3.0.

The % operator is used to calculate the remainder when one value is divided by another. In this case, it prints the value 0.0.

The // operator is used to perform floor division, which always truncates the fractional remainder. In this case, it prints the value 3.0.

The - operator can also be used to negate a value. In this case, it prints the value -15.0.

The ** operator is used to raise a value to a power. In this case, it prints the value 243.0.

Examples of use of Boolean expressions

Program18.py: Python stores true as integer 1, and false as integer 0 but outputs ‘true’ or ‘false’ from print statements

This code demonstrates the use of several Boolean operators in Python, which are used to test the truth or falsehood of a statement.

The > operator is used to test if one value is greater than another. In this case, it prints False because 5 is not greater than 10.

The < operator is used to test if one value is less than another. In this case, it prints True because 2 is less than 16.

The == operator is used to test if two values are equal. In this case, it prints True because 5 is equal to 5.

The <= operator is used to test if one value is less than or equal to another. In this case, it prints True because 7 is equal to 7.

The >= operator is used to test if one value is greater than or equal to another. In this case, it prints True because 7 is equal to 7.

The != operator is used to test if two values are not equal. In this case, it prints False because 10.0 is equal to 10.

You may also like: Python Code Examples

Program19.py: string objects and string assignments

This code demonstrates the use of string objects and string assignments in Python.

The print function is used to print two string literals, which are strings that are written directly in the code. The first string is surrounded by double quotes, and the second string is surrounded by single quotes.

The code assigns the string “Hello out there” to the variable a1 and prints it.

The code assigns the string “Hello” to the variable a2 and prints it.

The code assigns the strings “Hello” and “World” to the variables b1 and b2, respectively.

The code concatenates the two strings using the + operator and assigns the result to the c variable.

The code prints the value of the c variable, which is the concatenation of the strings “Hello” and “World”.

The output of this code will be:

Program20.py : Convert the integer to a string first to concatenate a string and an integer

This code demonstrates how to concatenate a string and an integer in Python by first converting the integer to a string using the str function.

The code assigns the strings “Hello” and ” World” to the variables a and b, respectively, and concatenates them using the + operator. The result is assigned to the c variable and printed.

The code concatenates the c variable, which is a string, with the string representation of the integer 10, which is obtained using the str function. The result is assigned to the d variable and printed.

The output of this code will be:

Program21.py : Round up a floating point number to the nearest integer

This code demonstrates two ways to round a floating-point number to the nearest integer in Python.

The code prints the value of the x variable, which is 2.6.

The code uses the round function to round the value of x to the nearest integer and assigns the result back to the x variable. The value of x is then printed again.

The code uses the int function to truncate the fractional part of the value of x and assigns the result back to the x variable. The value of x is then printed again.

The output of this code will be:

Program22.py : Round a float number to 2 decimal places, and output that number as € currency printed with a comma after the number of thousands

This code demonstrates how to round a floating-point number to two decimal places and format it as a currency value with a comma separating the thousands.

The code prints the value of the number variable, which is 5274.2578.

The code uses the round function to round the value of number to two decimal places and assigns the result back to the number variable. The value of number is then printed again.

The code divides the value of number by 1000 and assigns the result to the thousands variable. The value of thousands is then printed.

The code uses the int function to truncate the fractional part of the value of thousands and assigns the result back to the thousands variable. The value of thousands is then printed again.

The code calculates the remainder when number is divided by 1000 and assigns the result to the remainder variable. The value of remainder is then printed.

The code concatenates the string “€”, the string representation of thousands, a comma, and the string representation of remainder using the + operator. The result is assigned to the formatted_output variable and printed.

The output of this code will be:

Program23.py: Converting one data type to another

This code demonstrates how to convert one data type to another in Python.

The code prompts the user to enter a number and stores it in the number1 variable as a string. The value of number1 and its data type are printed.

The code uses the int function to convert the string value of number1 to an integer and assigns the result back to the number1 variable. The value of number1 and its data type are printed again.

Here’s an example of what the output might look like if the user enters the number 10:

Program24.py: Displaying an object’s memory location

This code demonstrates how to display the memory location of an object in Python using the id function.

The code prompts the user to enter a number and stores it in the number1 variable as a string. The value of number1, its data type, and its memory location are printed.

The code uses the int function to convert the string value of number1 to an integer and assigns the result back to the number1 variable. The value of number1, its data type, and its memory location are printed again.

Here’s an example of what the output might look like if the user enters the number 10:

The memory location is represented as a hexadecimal number, which is the address in memory where the object is stored. Note that the memory location of the object changes after it is converted to an integer, because a new object is created and the original string object is no longer referenced.

if statement

An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at most only one else statement following if.

Syntax

The syntax of the if…else statement is −

Program25.py : Displaying boolean values

This code demonstrates how to display a boolean value in Python.

The code assigns the value 10 to the number variable.

The code uses the > operator to test if number is greater than 0 and assigns the result to the isPositive variable.

The code prints the value of isPositive, which is a boolean value indicating whether number is positive or not.

The output of this code will be:

Program26.py: Combining boolean expressions with and

This code demonstrates how to combine two boolean expressions using the and operator in Python.

The code assigns the values 25 and 55000 to the age and salary variables, respectively.

The code uses the and operator to combine two boolean expressions that test if age is greater than 21 and if salary is greater than 50000. The result is printed.

The output of this code will be:

The and operator returns True only if both of the expressions on either side of it are True. If either of the expressions is False, the and operator returns False.

Program27.py : The if statement

This code demonstrates the use of the if statement in Python.

The if statement tests if the value of the a variable is equal to the string 'world'. If the test is True, the code inside the if block is executed. If the test is False, the code inside the else block is executed.

In this case, the value of a is 'world', so the test evaluates to True and the code inside the if block is executed. The output of this code will be:

Program28.py : The if statement with multiple statements

This code demonstrates how to use the if statement with multiple statements in Python.

The if statement tests if the value of the x variable is equal to the string 'April'. If the test is True, the code inside the if block is executed. If the test is False, the code inside the else block is executed.

In this case, the value of x is 'April', so the test evaluates to True and the code inside the if block is executed. The \n characters in the first print statement are used to print a new line, so the output will be:

Program29.py : The if statement with multiple statements

In this code, the if statement checks whether the value of x is equal to 'May'. If it is, it prints three lines of text. If it is not, it prints two lines of text.

The if statement is followed by a condition, which is an expression that evaluates to either True or False. If the condition is True, the indented block of code following the if statement is executed. If the condition is False, the indented block of code following the else statement is executed.

In this case, since the value of x is 'April', the condition x == 'May' evaluates to False, so the code in the else block is executed. This will print the following lines of text:

Program30.py : A nested if example (an if statement within another if statement)

This code prompts the user to enter a score, which is then converted to an integer and stored in the score variable.

The code then checks if the score is greater than or equal to 80. If it is, the grade is set to 'A'. If the score is not greater than or equal to 80, the code enters the else block and checks if the score is greater than or equal to 70. If it is, the grade is set to 'B'. If the score is not greater than or equal to 70, the grade is set to 'C'.

Finally, the code prints the grade.

Here’s an example of how the program could be run:

Program31.py: A nested if example – using if/else

This code prompts the user to enter a score, which is then converted to an integer and stored in the score variable.

The code then checks if the score is greater than or equal to 80. If it is, the grade is set to 'A'. If the score is not greater than or equal to 80, the code enters the else block and checks if the score is greater than or equal to 70. If it is, the grade is set to 'B'. If the score is not greater than or equal to 70, the code enters the next else block and checks if the score is greater than or equal to 55. If it is, the grade is set to 'C'. If the score is not greater than or equal to 55, the code enters the next else block and checks if the score is greater than or equal to 50. If it is, the grade is set to 'Pass'. If the score is not greater than or equal to 50, the grade is set to 'Fail'.

Finally, the code prints the grade.

Here’s an example of how the program could be run:

Program 32.py: A nested if example – using if/elif/else

This code prompts the user to enter a score, which is then converted to an integer and stored in the score variable.

The code then uses an ifelifelse statement to check the score and assign a grade. The if statement checks if the score is greater than 80 or equal to 80. If it is, the grade is set to 'A'. If the score is not greater than or equal to 80, the code enters the elif block and checks if the score is greater than 70 or equal to 70. If it is, the grade is set to 'B'. This process continues until the score is checked against all of the conditions, or until a grade is assigned. If none of the conditions are met, the code in the else block is executed and the grade is set to 'Fail'.

Finally, the code prints the grade.

Here’s an example of how the program could be run:

Program 33.py: Demo of DeMorgan’s Laws

a Not And is equivalent to an Or with two negated inputs or a Not Or is equivalent to an And with two negated inputs

This code prompts the user to enter a score, which is then converted to an integer and stored in the score variable.

The code then uses an ifelifelse statement to check the score and assign a grade. The if statement checks if the score is greater than 80 or equal to 80. If it is, the grade is set to 'A'. If the score is not greater than or equal to 80, the code enters the elif block and checks if the score is greater than 70 or equal to 70. If it is, the grade is set to 'B'. This process continues until the score is checked against all of the conditions, or until a grade is assigned. If none of the conditions are met, the code in the else block is executed and the grade is set to 'Fail'.

Finally, the code prints the grade.

Here’s an example of how the program could be run:

Program 34.py: Decision using two conditions linked with an and or an or

This code prompts the user to enter their age and whether they own their own car. It then uses multiple if statements to check the values of these variables and print different messages based on the combination of values.

The first set of if statements use the and operator to check if the age is greater than 21 and the user owns their own car, or if the age is greater than 21 and the user does not own their own car, or if the age is equal to 21 and the user owns their own car, or if the age is equal to 21 and the user does not own their own car, or if the age is less than 21 and the user owns their own car, or if the age is less than 21 and the user does not own their own car.

The second if statement uses the or operator to check if the salary is greater than $50000 or if the age is greater than 21. If either of these conditions is true, the message “you can join our club because you earn more than $50000 OR you are over 21 (or both)” is printed. If neither of these conditions is true, the message “you need to be earning more than 50000 OR be over 21 (or both) to join our club” is printed.

Here’s an example of how the program could be run:

Python while Loop Statements

while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.

Syntax

The syntax of a while loop in Python programming language is −

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.

In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.

Program 35.py: Examples of while loops

This code will print 'Hi World' four times, followed by 'done'.

The while loop will continue to execute the code block inside of it as long as the condition x < 5 is True. At the end of each iteration, the value of x is incremented by 1, so the condition will eventually become False, causing the loop to exit.

Here is the output of this code:

Program 36.py: Examples of while loops

This code will print 'Hi World', followed by 'I love World', four times, followed by 'done', followed by 'gone'.

The while loop will continue to execute the code block inside of it as long as the condition x < 5 is True. At the end of each iteration, the value of x is incremented by 1, so the condition will eventually become False, causing the loop to exit.

Here is the output of this code:

Program 37.py: Examples of while loops – the infinite loop

This code will create an infinite loop that will continue to print 'Hi world', 'I love world', 'Press the Ctrl key and the C key together', and 'to interrupt this program...' indefinitely.

The condition for the while loop is x, which is initially True because x is assigned the value 1. The while loop will therefore continue to execute the code block inside of it indefinitely, unless the loop is interrupted by pressing the Ctrl+C keys together.

To prevent the infinite loop, you can add a condition that will cause the loop to exit when a certain criteria is met. For example, you could add a break statement to the loop to cause it to exit when a certain condition is met:

Program 38.py:

This modified version of the code will print 'Hi world' and 'I love world' five times, followed by 'done' and 'gone'.

Program 39.py: Examples of while loops – another infinite loop

This code will create an infinite loop that will continue to print 'Hello World!', 'Press the Ctrl key and the C key together', and 'to interrupt this program...' indefinitely.

The condition for the while loop is 1, which is always True, so the while loop will continue to execute the code block inside of it indefinitely, unless the loop is interrupted by pressing the Ctrl+C keys together.

To prevent the infinite loop, you can add a condition that will cause the loop to exit when a certain criteria is met. For example, you could add a break statement to the loop to cause it to exit when a certain condition is met:

Program40.py

This modified version of the code will print 'Hello World!' six times, followed by 'done'

Program 41.py: Example of break to end an infinite loop

The break statement will cause the program to exit the innermost loop that it is currently in. In this case, the break statement will cause the program to exit the infinite while loop when the user inputs ‘y’. The program will then continue to execute the statements following the loop.

Here is how the output of the program would look like:

Program 42.py: Example of continue to end an infinite loop

The continue statement will cause the program to skip the rest of the current iteration of the loop and continue with the next iteration. In this case, when the user inputs ‘y’, the program will skip the second input statement and the break statement and continue with the next iteration of the loop.

Here is how the output of the program would look like:

The loop will continue indefinitely until the user inputs ‘y’ in response to the second input statement, at which point the break statement will be executed and the loop will exit. The program will then continue to execute the statements following the loop.

Program 43.py: ‘sentinel-controlled’ while loop

In this program, the sentinel value 0 is used to signal the end of the input phase. The program prompts the user to enter a score, and the input is converted to an integer and stored in the variable score. The while loop then continues to execute as long as score is not equal to 0.

At each iteration of the loop, the value of score is added to the running total totalScore and the count of the number of scores entered is incremented by 1. The program then prompts the user to enter the next score.

When the user enters 0, the loop terminates, and the program enters the termination phase. In the termination phase, the program checks if any scores were entered by checking if numberScores is equal to 0. If numberScores is not equal to 0, the program calculates the average score by dividing totalScore by numberScores and prints the result. If numberScores is equal to 0, the program prints a message indicating that no scores were entered.

Here is an example of how the output of the program might look:

Python for Loop Statements

It has the ability to iterate over the items of any sequence, such as a list or a string.

Syntax

If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.

Program 44.py: Example of the counter-controlled for loop

In this program, the for loop will iterate 10 times. At each iteration, the loop variable c will take on the value of the current iteration number, starting from 0 and ending at 9.

The range function generates a sequence of numbers from 0 to 9, and the for loop iterates over this sequence.

The output of the program will be the numbers 0 through 9 printed on separate lines.

Program 45.py: Example of the counter-controlled for loop

In this program, the for loop will iterate 5 times. At each iteration, the loop variable c will take on the value of the current iteration number, starting from 5 and ending at 9.

The range function generates a sequence of numbers from 5 to 9, and the for loop iterates over this sequence.

The output of the program will be the numbers 5 through 9 printed on separate lines.

Program 46.py: ‘continue’ with the for loop

In this program, the for loop will iterate 5 times. At each iteration, the loop variable c will take on the value of the current iteration number, starting from 1 and ending at 5.

The range function generates a sequence of numbers from 1 to 5, and the for loop iterates over this sequence.

If the value of c is equal to 3, the continue statement is executed, which causes the program to skip the rest of the current iteration and continue with the next iteration. This means that the print statement will not be executed when c is equal to 3, and the number 3 will not be printed.

The output of the program will be the numbers 1, 2, 4, and 5 printed on separate lines.

Program 47.py: ‘break’ with the for loop

In this program, the for loop will iterate 5 times. At each iteration, the loop variable c will take on the value of the current iteration number, starting from 1 and ending at 5.

The range function generates a sequence of numbers from 1 to 5, and the for loop iterates over this sequence.

If the value of c is equal to 3, the break statement is executed, which causes the program to exit the for loop. This means that the for loop will terminate after the second iteration, and the print statement will not be executed for the remaining iterations.

The output of the program will be the numbers 1 and 2 printed on separate lines.

Program 48.py: Outputting strings and numbers in a single print statement

In this program, the print statement will output the string 'Total is: ' followed by the value of the variables d and c, which are 10 and 75, respectively. The string 'dollars and' and the string ' cents' are also output.

The output of the program will be:

Note that the print function automatically inserts a space between the strings and variables being printed, so you do not need to manually add a space between the strings and variables.

Program 49.py: Outputting strings and numbers in a single printstatement using string formatting.

In this program, the print function is used to output strings and variables using string formatting. String formatting allows you to embed variables within a string and specify how the variables should be formatted.

The % operator is used to specify a placeholder for a variable in the string. The placeholder consists of a % followed by a format specifier, which determines how the variable should be formatted. For example, %s is used to specify a string placeholder, %d is used to specify an integer placeholder, and %f is used to specify a floating point placeholder.

The variables to be formatted are provided as a tuple after the string, and the tuple is placed inside the % operator.

Here is the output of the program:

Program 50.py: Repeat a program at the user’s request

In this program, the while loop will execute as long as the value of the variable answer is either 'y' or 'Y'.

The loop will execute once initially, and at the end of each iteration, the program will prompt the user to enter 'y' or 'n'. If the user enters 'y', the loop will continue to execute. If the user enters 'n', the loop will exit and the program will continue to the next statement after the loop.

Here is an example of how the output of the program might look:

Program 51.py: Use a loop within a loop

In this program, the outer while loop will execute 3 times, and at each iteration, it will print a new line and the value of x. The inner while loop will also execute 3 times, and at each iteration, it will print the value of y on the same line as the value of x.

The output of the program will be:

Program 52.py: Use a loop within a loop

In this program, the outer while loop will execute 2 times, and at each iteration, it will print a new line and the value of x. The middle while loop will also execute 2 times, and at each iteration, it will print the value of y on the same line as the value of x. The inner while loop will execute 2 times at each iteration of the middle while loop, and it will print the value of z on the same line as the value of y.

The output of the program will be:

Program 53.py: Use a loop within a loop

In this program, the outer for loop will iterate 5 times, and at each iteration, it will execute the inner for loop. The inner for loop will also iterate 5 times, and at each iteration, it will print a string containing the values of i and j.

The output of the program will be:

Program 54.py: Use a loop within a loop

In this program, the outer for loop will iterate 3 times, and at each iteration, it will execute the middle for loop. The middle for loop will also iterate 3 times, and at each iteration, it will execute the inner for loop. The inner for loop will iterate 3 times, and at each iteration, it will print a string containing the values of i, j, and k.

The output of the program will be:

Program 55.py: Using the built-in square root function math.sqrt
To use any math function, you have to include the statement: import math in your program – usually at the top, but can be anywhere.

In this program, the math module is imported, which provides mathematical functions that can be used in the program.

The sqrt function is used to calculate the square root of a number. The square root of a number is a value that, when multiplied by itself, gives the original number.

The sqrt function takes a single argument, which is the number for which you want to calculate the square root. The function returns a floating point value representing the square root of the number.

The print function is used to print the output of the sqrt function to the console.

The output of the program will be:

Program 56.py: Using the dir function to list out the names of available functions in the math module

In this program, the math module is imported, which provides mathematical functions that can be used in the program.

The print function is used to print the math module to the console. This will output the module object itself, which is not very useful.

The dir function is used to get a list of all the names defined in the math module. This list includes functions, variables, and other objects defined in the module. The dir function takes a single argument, which is the object for which you want to get the list of names.

The print function is then used to print the output of the dir function to the console.

The output of the program will be:

Python – Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.

Defining a Function

You can define functions to provide the required functionality. Here are simple rules to define a function in Python.

  • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
  • The first statement of a function can be an optional statement – the documentation string of the function or docstring.
  • The code block within every function starts with a colon (:) and is indented.
  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

Syntax

By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.

Program 57.py: Showing functions which have no return statement

This output is produced by the print statements in each of the functions you defined. The greeting() function prints “Hello” to the console each time it is called. The many_greetings(4) function prints “Hello Again!” four times to the console. The many_greetings_with_name(x, " Mary") function prints “Hello Again Mary!” to the console the number of times specified by the value of x.

Here is the output that you would see if you ran the code you provided:

Program 58.py: Using a programmer-defined function

This code defines a function called cube that takes a single argument y and returns the cube of y.

Then it prints the cube of numbers 1 to 5 by calling the cube function in a loop that iterates over the range 1, 2, 3, 4, 5.

Finally, it prints the value of x after the loop has completed, which is 5. The output of the code will be:

Program 59.py: Using two programmer-defined functions

This code defines two functions: cube and doubleIt. The cube function takes a single argument y and returns the cube of y. The doubleIt function takes a single argument z and returns twice the value of z.

Then it prints the cube of numbers 1 to 5 by calling the cube function in a loop that iterates over the range 1, 2, 3, 4, 5. It prints a blank line after the loop.

Then it prints the double of numbers 1 to 5 by calling the doubleIt function in a loop that iterates over the range 1, 2, 3, 4, 5.

The output of the code will be:

Program 60.py: Importing programmer-defined functions

Save codes as myFun.py

This is a program that defines two functions, cube and doubleIt, and then imports them into the main program. The cube function takes in a number y and returns the cube of y, while the doubleIt function takes in a number z and returns 2 * z.

After the functions are imported, the program prints the cubes of the numbers 1 to 5 and the double of the numbers 1 to 5. The for loop iterates through the numbers 1 to 5, and for each number, the function cube or doubleIt is called with that number as the argument. The result of the function is then printed to the screen.

For example, when x is 3, myFun.cube(x) is called and returns 27. Similarly, when x is 4, myFun.doubleIt(x) is called and returns 8.

Program 61.py: Function with no return statement

This is a program that defines a function called times that takes in a number x and prints the x times tables from 1 to 10. The function has no return statement, so it returns None.

The function is called twice, with 1 and 2 as the arguments. When the function is called with 1 as the argument, it prints the 1 times table, and when it is called with 2 as the argument, it prints the 2 times table.

For example, when x is 1, the function prints:

Program 62.py: Function with two return statements

This is a program that defines a function called division that takes in two numbers, x and y, and returns the result of x / y. The function has two return statements.

The first return statement is executed if y is equal to 0. In this case, the function prints a message indicating that division by zero is not allowed, and then returns None.

The second return statement is executed if y is not equal to 0. In this case, the function prints a message indicating that it is returning the result of x / y, and then returns the result of the division.

The function is called twice, with 5.0 and 2 as the first set of arguments, and with 5.0 and 0 as the second set of arguments. When the function is called with 5.0 and 2 as the arguments, it returns 2.5, and when it is called with 5.0 and 0 as the arguments, it returns None.

Program 63.py: Function with no arguments

This is a program that defines a function called greeting that takes in no arguments and prints the message “Hello there!”. The function has no return statement, so it returns None.

The function is called twice, with no arguments. Each time it is called, it prints the message “Hello there!”.

The output of the program will be:

Program 64.py: Program with a Boolean function

This is a program that defines a function called isPositive that takes in a number x and returns a Boolean value indicating whether x is positive or negative.

The function first checks if x is greater than or equal to 0. If it is, the function returns True, and if it is not, the function returns False.

The function is called once, with the user-entered value of x as the argument. The result of the function is stored in the variable result and is then printed to the screen. The function is also called a second time and the result is printed to the screen again.

For example, if the user enters -5.0, the function will return False, and the output of the program will be:

If the user enters 5.0, the function will return True, and the output of the program will be:

Program 65.py: Polymorphic function

Polymorphism : the meaning of the operations depends on the objects being operated on. The * operator is said to be “overloaded”

This is a program that defines a function called doubleIt that takes in a single argument x and returns 2 * x. The function is said to be polymorphic because the meaning of the operation 2 * x depends on the type of the object being passed as the argument x.

The program first calls the function with an integer value y as the argument, and then calls the function with a string value z as the argument.

When the function is called with the integer value 3 as the argument, the operation 2 * 3 is performed, and the function returns 6. When the function is called with the string value "Hello " as the argument, the operation 2 * "Hello " is performed, and the function returns "Hello Hello ".

The output of the program will be:

Program 66.py: The scope of a variable

Local scope means the variable is only available in the function where it is defined. Global scope means the variable is available everywhere in the code.

This is a program that defines a function called my_function that takes in a single argument num and has a local variable num and a global variable number. The function prints the value of both num and number.

The program first defines the global variable number and assigns it the value 10. It then prints the value of number.

Next, the program calls the function my_function with the value of number as the argument. Inside the function, num is a local variable with the value of the argument passed to the function, which is 10. The function also has access to the global variable number, which has the value 10. The function prints the values of both num and number.

Finally, the program tries to print the value of the local variable num defined inside the function. However, this variable is not available outside of the function, so an error will be raised stating that num is not defined.

The output of the program will be:

Python Lists

The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number – its position or index. The first index is zero, the second index is one, and so forth.

Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial.

There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.

The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.

Program 67.py: Creating and using a Python list

This is a program that creates a Python list called result with 8 elements, all initialized to 0, and then modifies some of the elements in the list.

The program first creates the list result and prints it. The list result has 8 elements, all initialized to 0.

Next, the program modifies some of the elements in the list. The element at index 0 is set to 75, the element at index 1 is set to 90, and the element at index 4 is set to 72.

Finally, the program prints the value of each element in the list using the list indexing notation result[i], where i is the index of the element.

The output of the program will be:

Program 68.py: Creating and printing an empty list

This is a program that creates an empty list called list1 and then prints it. An empty list is a list with no elements, so it has a length of 0.

The program creates an empty list using the syntax list1 = []. It then prints the list using the print() function.

The program also includes a commented-out line that would generate an error if it were executed. This line tries to access the element at index 0 in the list list1, but since the list is empty, it does not have any elements, and trying to access an element at an invalid index will raise an error.

The output of the program will be:

Program 69.py: Appending to an empty list

This is a program that creates an empty list called list1, and then adds two elements to the list using the append() method.

The program first creates an empty list using the syntax list1 = [] and then prints the list. The list is initially empty, so it has a length of 0.

Next, the program adds an element to the list using the append() method. The element is the integer 67. The append() method adds the element to the end of the list, so the list now has a length of 1 and the element at index 0 is 67.

The program then adds another element to the list using the append() method. This element is the string "hello". The append() method again adds the element to the end of the list, so the list now has a length of 2 and the element at index 1 is "hello".

Finally, the program tries to access the element at index 2 in the list. However, the list only has 2 elements, so trying to access an element at index 2 will raise an out-of-range error.

The output of the program will be:

Program 70.py: List of lists

This is a program that creates two lists, list1 and list2, and then creates a third list called list3 that contains list1 and list2 as its elements.

The program first creates the list list1 and prints it. list1 has 3 elements: 1, 2, and 3.

Next, the program creates the list list2 and prints it. list2 has 3 elements: 4, 5, and 6.

The program then creates the list list3 and assigns it the value [list1, list2]. This creates a list with list1 and list2 as its elements. list3 has a length of 2 and its elements are list1 and list2.

Finally, the program prints the elements of list3 using the list indexing notation list3[i], where i is the index of the element.

The output of the program will be:

Program 71.py: Accessing the last item in a list

This is a program that creates a list called list1 with 8 elements and then prints the first, second, last, and second-to-last elements of the list.

The program creates the list list1 and assigns it the value [1,2,3,6,7,8,9,10]. It then prints the list.

Next, the program uses the list indexing notation list1[i] to access and print the first, second, last, and second-to-last elements of the list. The indexing notation list1[i] returns the element at the i-th position in the list, where the first element has an index of 0 and the last element has an index of len(list1) - 1.

To access the last element of the list, the program uses the index -1, which refers to the last element of the list. To access the second-to-last element of the list, the program uses the index -2, which refers to the element at the position len(list1) - 2.

The output of the program will be:

Program 72.py: Deleting items from a list

Program 73.py: Repeating lists

This is a program that creates a list called list1 with 3 elements and then creates new lists by repeating list1 using the * operator.

The program first creates the list list1 and assigns it the value [1,2,3]. It then prints the list.

Next, the program creates a new list by repeating list1 3 times using the * operator. This creates a new list with the elements of list1 repeated 3 times. The original list list1 is not modified. The program then prints the new list.

The program then prints the original list list1 again to show that it has not been modified.

Finally, the program assigns the value list1 * 2 to list1. This creates a new list with the elements of list1 repeated 2 times and assigns the new list to list1. The original list is replaced with the new list. The program then prints the new list.

The output of the program will be:

Program 74.py: List indexing

This is a program that creates a list called list1 with 11 elements and then extracts a sublist from list1 using list indexing.

The program first creates the list list1 and assigns it the value [10,9,8,7,6,5,4,3,2,1,0]. It then uses the list indexing notation list1[start:end] to extract a sublist from list1.

The indexing notation list1[start:end] returns a sublist of list1 starting at the index start and ending at the index end - 1. If the start index is not specified, it defaults to 0, and if the end index is not specified, it defaults to the length of the list.

In this program, the first sublist is extracted from the list using the indexing notation list1[0:1]. This returns a sublist with a single element, the element at index 0.

The second sublist is extracted from the list using the indexing notation list1[5:7]. This returns a sublist with 2 elements, the elements at indices 5 and 6.

The program then prints the two sublists.

The output of the program will be:

Program 75.py: Finding the length of a list

This is a program that creates three lists and then prints the lengths of the lists using the len() function.

The program first creates the list list1 and assigns it the value ["Tomy","May",'Lindia','Barbrossa',1,2,3]. It then creates the list list2 and assigns it the value [1,2,3,4]. Finally, it creates an empty list called list3.

The program then prints the lengths of the three lists using the len() function. The len() function returns the number of elements in a list.

The output of the program will be:

Program 76.py: Concatenating lists

This is a program that creates two lists, list1 and list2, and then concatenates them using the + operator.

The program first creates the list list1 and assigns it the value [1,2,3]. It then prints the list.

Next, the program creates the list list2 and assigns it the value [4,5,6]. It then prints the list.

The program then concatenates list1 and list2 using the + operator and assigns the result to list1. This creates a new list that contains the elements of list1 followed by the elements of list2. The original list list1 is replaced with the new list. The program then prints the new list.

Finally, the program concatenates list1 with itself using the + operator and assigns the result to list1. This creates a new list that contains the elements of list1 repeated twice. The original list list1 is replaced with the new list. The program then prints the new list.

The output of the program will be:

Program 77.py: List iteration

This is a program that creates a list called list2 with 6 elements and then iterates over the elements of the list using a for loop.

The program first creates the list list2 and assigns it the value [1,2,3,"Hello",4,5].

Next, the program uses a for loop to iterate over the elements of the list. The loop variable i takes on the value of each element of the list in turn, and the statements inside the loop are executed for each element.

The program prints the value of each element using the print() function. The end parameter of the print() function is set to " ", which means that the elements are printed on the same line separated by a space.

The output of the program will be:

Program 78.py: List membership

This is a program that creates a list called list2 with 6 elements and then checks if an element is a member of the list using the in operator.

The program first creates the list list2 and assigns it the value [1,2,3,"Hello",4,5].

Next, the program uses the in operator to check if the element "Hello" is a member of the list list2. The in operator returns True if the element is a member of the list, and False if it is not.

The program prints the result of the membership check using the print() function.

The output of the program will be:

Program 79.py: Selection of list methods

This is a program that creates a list called list2 with 3 elements and then demonstrates several methods of the list class.

The program first creates the list list2 and assigns it the value ["B","C","A"]. It then prints the list.

Next, the program uses the extend() method to add two elements, "X" and "Y", to the end of the list. The extend() method adds the elements of the specified list to the end of the original list. The program then prints the modified list.

The program then uses the pop() method to remove the last element of the list. The pop() method removes the specified element from the list and returns the value of the removed element. If no element is specified, the pop() method removes the last element of the list. The program then prints the modified list.

The program then uses the pop() method again to remove the last element of the list. The program then prints the modified list.

The program then uses the reverse() method to reverse the order of the elements in the list. The reverse() method modifies the list in place, reversing the order of the elements. The program then prints the modified list.

The program then uses the append() method to add an element, "S", to the end of the list. The append() method adds the specified element to the end of the list. The program then prints the modified list.

The program then uses the sort() method to sort the elements of the list into ascending order. The sort() method modifies the list in place, sorting the elements into ascending order. The program then prints the modified list.

Finally, the program uses the reverse() method again to reverse the order of the elements in the list. The program then prints the modified list.

The output of the program will be:

Program 80.py: Sequential search of a list

This is a program that creates a list called list1 with 9 elements and then performs a sequential search of the list to find a specified number.

The program first creates the list list1 and assigns it the value [21,25,24,22,65,1,44,51,78]. It then prompts the user to enter a number to find using the input() function.

Next, the program defines a variable found and assigns it the value 0. This variable will be used to keep track of whether the number was found in the list.

The program then uses a for loop to iterate over the elements of the list. The loop variable i takes on the value of each element of the list in turn.

Inside the loop, the program uses an if statement to check if the number to find is equal to the current element of the list. If the number is found, the program prints the number and its index in the list using the index() method and sets the value of found to 1.

After the loop, the program checks the value of found. If found is 0, it means that the number was not found in the list, and the program prints a message indicating that the number was not found. If found is 1, it means that the number was found in the list, and the message is not printed.

If the user enters a number that is not in the list, the output of the program will be:

If the user enters a number that is in the list, the output of the program will be:

Program 81.py: Sequential search of a list

This is a program that creates a list called mylist with 9 elements and then performs a sequential search of the list to find a specified number.

The program first creates the list mylist and assigns it the value [21,25,24,22,65,1,44,51,78]. It then determines the length of the list using the len() function and assigns it to the variable n.

Next, the program uses a for loop to iterate over the elements of the list. The loop variable i takes on the values 0, 1, 2, …, n-1, and the statements inside the loop are executed for each value. The program prints the elements of the list separated by a space.

The program then prompts the user to enter a number to search for using the input() function and assigns the entered value to the variable search.

The program then defines a variable found and assigns it the value False. This variable will be used to keep track of whether the number was found in the list.

The program then uses another for loop to iterate over the elements of the list. The loop variable i takes on the values 0, 1, 2, …, n-1, and the statements inside the loop are executed for each value.

Inside the loop, the program uses an if statement to check if the element at index i is equal to the number to search for. If the element is equal to the number, the program sets the value of found to True and assigns the value of i to the variable index.

After the loop, the program checks the value of found. If found is True, it means that the number was found in the list, and the program prints a message indicating the index at which the number was found. If found is False, it means that the number was not found in the list, and the program prints a message indicating that the number was not found.

If the user enters a number that is not in the list, the output of the program will be:

If the user enters a number that is in the list, the output of the program will be:

Program 82.py: binarysearch

This is a program that creates a list called mylist with 9 elements and then performs a binary search of the list to find a specified number.

The program first defines a function binarysearch() that takes two arguments: mylist and target. The function uses a while loop to perform the binary search.

The while loop has a condition that states that the loop should continue as long as left is less than right-1. left and right are variables that are initialized to 0 and len(mylist), respectively, at the beginning of the function.

Inside the loop, the program computes the midpoint of the list using the int() function to round down and assigns it to the variable mid. It then retrieves the element at the midpoint and assigns it to the variable number_at_mid.

The program then checks if target is equal to number_at_mid. If it is, the function returns True. If target is less than number_at_mid, the program sets right to mid. If target is greater than number_at_mid, the program sets left to mid.

If left becomes greater than or equal to right, the function returns False. If left becomes equal to right-1 and the element at index left is equal to target, the function returns True. Otherwise, the function returns False.

The program then creates the list mylist and assigns it the value [11,27,36,44,51,22,65,1,78]. It then sorts the list using the sort() method.

The program then enters a while loop that continues as long as repeat is "y" or "Y". Inside the loop, the program prompts the user to enter a number to search for using the input() function and assigns the entered value to the variable mytarget.

The program then calls the binarysearch() function with mylist and mytarget as arguments and assigns the returned value to a variable. If the returned value is True, the program prints a message indicating that the number was found. If the returned value is False, the program prints a message indicating that the number was not found.

Program 78.py: biglist