Python programs – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 13:01:07 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Python programs – Java2Blog https://java2blog.com 32 32 Count number of characters in a string in python https://java2blog.com/count-number-of-characters-string-python/?utm_source=rss&utm_medium=rss&utm_campaign=count-number-of-characters-string-python https://java2blog.com/count-number-of-characters-string-python/#respond Thu, 13 Jan 2022 09:20:28 +0000 https://java2blog.com/?p=18809 In this post, we will see how to count number of characters in a String in Python.

We can think of strings as a collection of characters, with every character at a given index.

Ways to count the number of characters in a string in Python

In this tutorial, we will find out the total number of characters in a string in Python.

Using the len() function

This function is the most straightforward method. The len() function returns the length of a given iterable in Python. We can use it to find the number of characters in a string.

For example,

s = 'java2blog'
print(len(s))

Output:

9

Using the for loop

We can use the for loop to iterate over a string in Python. We can use a counter variable and increment it in every iteration. This variable will return the total number of characters in a string.

For example,

s = 'java2blog'
t = 0
for i in s:
    t += 1
print(t)

Output:

9

In the above example,

  • The t variable is given a value of 0.
  • We iterate over the string s using the for loop.
  • In every iteration, we increment t and display its value after the loop ends.

Using the collections.Counter class

The collections.Counter class stores the elements of a string as key-value pairs. The keys are the characters of the string, and the value of each key is how many times this character occurs in the string.

We can sum up these values to find the total number of characters in the given string.

See the code below.

from collections import Counter
s = 'java2blog'
counter = Counter(s)
print(sum(counter.values()))

Output:

9

In the above code,

  • We create an object of the Counter class ob.
  • We create an object of all the values of the dictionary-like object ob with the values() function.
  • The sum() function returns the sum of these values.

Conclusion

In this tutorial, we discussed how to get the characters in a given string in Python. The len() function is the simplest and most used method. We can also use the for loop and Counter class for a lengthy method.

]]>
https://java2blog.com/count-number-of-characters-string-python/feed/ 0
How to decrement for loop in python https://java2blog.com/python-for-loop-decrement/?utm_source=rss&utm_medium=rss&utm_campaign=python-for-loop-decrement https://java2blog.com/python-for-loop-decrement/#respond Thu, 28 Oct 2021 11:55:49 +0000 https://java2blog.com/?p=17524 We use the for loop widely in the programming world. Most programs, whether highly complex or not, contain this loop. Sometimes, depending on the conditions, we need to decrement the loop.

This article focuses on the ways to decrement the for loop in Python.

What is for loop in Python?

The for loop is a conditional iterative statement that executes a block of code until we satisfy a given condition. It can loop through different iterables also in Python.

Ways to decrement the for loop in Python

We need to decrement a for loop when we wish to execute something in reverse order. Python does not make use of the decrement operator in the for loop. However, we can emulate the use for decrementing a for loop using other different methods.

Let us now discuss how to decrement the for loop in Python.

Using the start, stop and step parameters in range() function

The range() function returns a series of numbers within a given starting and ending index. The range() function is quite essential in the use of the for loop.

We can use the start, stop, and step parameters in this function. The start parameter indicates the starting value of the sequence, and the stop parameter tells the last value. The step parameter tells how much to increment or decrement between the values in the series.

To decrement a value in the for loop, the start value should be greater than the stop value, and the step parameter should be a negative integer.

For example,

starti = 7
stopi = 0
step = -1
for x in range(starti, stopi, step):
    print (x)

Output:

7
6
5
4
3
2
1

In the above example,

  • We define the value for the start, stop, and step parameters.
  • The start index value needs to be higher than the stop index as we must traverse in the reverse order.
  • We take the value of the step parameter to be -1, which helps to decrement the value before the next number in the series.
  • Finally, the print() function displays the output.

Using the reversed() function

The reversed() function reverses the order of the provided sequence. It takes only one parameter, which is the sequence whose order we need to reverse.

Since we usually decrement a value in the for loop to do something in reverse order, we use this function to reverse the given sequence directly.

The range() function within the for loop can be passed as a parameter to the reversed() function to implement the desired output.

See the code below.

for x in reversed(range(8)):
    print (x)

Output:

7
6
5
4
3
2
1

In the above example,

  • The range() function generates a series of numbers.
  • The reversed() function reverses the order of the given range.
  • We loop through the sequence and display it.

Using the while loop

As you know, the while loop is another popular iterative statement that can execute a given set of statements several times.

This method is an alternative solution to the given problem, wherein we use the while loop instead of the for loop. But still, it achieves the same results in the program.

In a while loop, we increment or decrement the value separately.

For example,

x = 7
while x>0:
    print (x)
    x -= 1

Output:

7
6
5
4
3
2
1

Conclusion

In this tutorial, different ways by which we can decrement the for loop in Python have been discussed. Decrementing a loop is very common and is relatively easy to understand and implement with the proper use of the right functions. Also, this tutorial demonstrates an alternative to the problem by using the while loop instead of the for loop.

That’s all about how to decrement for loop in Python.

]]>
https://java2blog.com/python-for-loop-decrement/feed/ 0
Calculator program in Python https://java2blog.com/calculator-program-python/?utm_source=rss&utm_medium=rss&utm_campaign=calculator-program-python https://java2blog.com/calculator-program-python/#respond Fri, 18 Jun 2021 19:05:52 +0000 https://java2blog.com/?p=15288 A simple Calculator can be utilized to carry out the four basic arithmetic operations namely addition, division, multiplication, and subtraction depending on the input of the user.

This tutorial demonstrates how to create a simple Calculator in Python.

Using the while loop along with the if...else conditional statement.

To implement a simple Calculator program in Python, we take the help of the basic while loop along with an if...elif...else conditional statement.

Define functions for Addition, Subtraction, Multiplication and Division

We create four user-defined functions for the four basic operations that exist in a simple Calculator and proceed with the code after creating these functions.

def addition(a, b):
        return a + b
    def subtraction(a, b):
        return a - b
    def multiplication(a, b):
        return a * b
    def division(a, b):
        return a / b

Take user input using input function

Here, we accept input from the user, with the help of the input() function. The input() function is utilized to take input from the user, after which Python evaluates the input and identifies the datatype.

Complete calculator program in Python

The following code uses the while loop and the if...elif...else branching to implement a Simple Calculator program in Python.

def addition(a, b):
    return a + b
def subtraction(a, b):
    return a - b
def multiplication(a, b):
    return a * b
def division(a, b):
    return a / b
print("Select one of the four simple operations:")
print("1 Addition")
print("2 Subtraction")
print("3 Multiplication")
print("4.Division")
while True:
    userinput = input("The Selected Operation: ")
    if userinput in ('1', '2', '3', '4'):
        x = float(input("Please Enter the first operand: "))
        y = float(input("Please Enter the second operand: "))
        if userinput == '1':
            print(x, "+", y, "=", addition(x, y))
        elif userinput == '2':
            print(x, "-", y, "=", subtraction(x, y))
        elif userinput == '3':
            print(x, "*", y, "=", multiplication(x, y))
        elif userinput == '4':
            print(x, "/", y, "=", division(num1, num2))
        break
    else:
        print("Wrong or Invalid Input")

Output:

Select one of the four simple operations:
1.Addition
2.Subtraction
3.Multiplication
4.Division
The Selected Operation: 3
Please Enter the first operand: 4
Please Enter the second operand: 8
4.0 * 8.0 = 32.0

Explanation

  • Firstly, we create four user-defined functions for addition, subtraction, multiplication, and division respectively.
  • Then, the user is asked to choose an option between these four operations.
  • Options 1, 2, 3, and 4 are valid while selecting any other option will give the result as Wrong or Invalid Input and the loop goes on until there is a valid option which is selected. Here, we have use float() function to convert String to float in python.
  • The two operands are taken as an input by the user, and an if...elif...else branching is utilized to make the use of the four functions more distinct.
  • All the four user defined functions addition(), subtraction(), multiplication(), and division() evaluate their respective operations based on the input received, and an output is generated.

That’s all about simple calculator program in Python.

]]>
https://java2blog.com/calculator-program-python/feed/ 0
Number guessing game in Python https://java2blog.com/number-guessing-game-python/?utm_source=rss&utm_medium=rss&utm_campaign=number-guessing-game-python https://java2blog.com/number-guessing-game-python/#respond Sun, 06 Jun 2021 19:10:40 +0000 https://java2blog.com/?p=15123 A number guessing game is a common mini-project for basic programmers who have a grasp on random number generation and conditional statements with iteration.

The number guessing game is based on a concept where player has to guess a number between given range. If player guesses the expected number then player wins else player loose the game. Since this game has limited attempts, so, player has to guess the number with the limited attempts, else player will lose the game.

In this article, we will create number guessing game in Python.

Number guessing game Rules

  1. You must enter only valid integer within the specified range.
  2. You will be provided limited attempts to guess the number.
  3. You cannot leave the game, once started.

If the entered number is less than or greater than the required number, then player gets the message (hint) to proceed further either in up or down range.

In such a game, we first generate a random number between a given range. We ask the user to guess this number. If the guess is right, we print that the guess is right and break out of the loop. Else we tell whether the number is less or more than the actual number. We also ask the user for the total guesses he or she is allowed to take. When the number of guesses exceeds this, we break off the loop.

The user can take help of this to know the actual number. For example, if the user guesses that the number is 45 and the output is that the actual number is less than 45, then the user can interpret that the number won’t lie between 45 and 100 (given that the range is till 100). This way the user can keep guessing and interpreting the result. We print the number of guesses it takes the user to get the answer right.

Number guessing game implementation in Python

Here is implementation of number guessing game in Python.

import random
t = 0
g = int(input("Total Guesses: "))
low = int(input("Enter the lower range: "))
high = int(input("Enter the upper range: "))
x = random.randint(low, high)
n = int(input("Enter an integer between the given range: "))

while (x != 'n'):
    if(t<(g-1)):
        if n < x:
            print("The number guessed is low")
            t = t+1
            n = int(input("Enter an integer between the given range: "))
        elif (n > x):
            print("The number guessed is high")
            t = t+1
            n = int(input("Enter an integer between the given range: "))
        else:
            print("The number guessed is right")
            print("Total guesses taken: ", t+1)
            break
    else:
        print("Ran out of tries!")
        break

Output:

Total Guesses: 5
Enter the lower range: 0
Enter the upper range: 7
Enter an integer between the given range: 5
The number guessed is low
Enter an integer between the given range: 6
The number guessed is right
Total guesses taken: 2

We created the above program in Python 3.
Here are the steps for creating number guessing game in Python:

  • We first asked the user to specify the range for the number to be generated. A random number is generated using the randint() function from the random module.
  • We initialized a variable with 0 to keep track of the total guesses made.
  • We ran the while loop till the number guessed is not equal to the actual number.
  • We used an if-else ladder to check if the guessed number is smaller or bigger than the actual number and increment the total guesses in each pass.
  • We broke out of the loop when the guess matches the number.
  • We printed the total guesses taken when the guess is right.

By similarly implementing the logic, we can create this game in Python 2 or some other programming language.

That’s all about Number guessing game in Python.

]]>
https://java2blog.com/number-guessing-game-python/feed/ 0
Perfect number program in Python https://java2blog.com/perfect-number-python/?utm_source=rss&utm_medium=rss&utm_campaign=perfect-number-python https://java2blog.com/perfect-number-python/#respond Mon, 31 May 2021 11:43:33 +0000 https://java2blog.com/?p=14994 According to number theory, a limb of pure mathematics that deals with integers, a Perfect Number can be defined as a positive integer whose value is equivalent to the sum of its proper positive divisors, excluding the number itself (alternatively known as aliquot sum).

An example of a perfect number is the number 6, the first perfect number in the series. The numbers 1, 2, and 3 are its proper divisors, and the sum of all three proper divisors gives us the original number, which makes it a perfect number.

In this tutorial, we will discuss different ways to check whether a number is a perfect number in python.

Use the Simple iteration method to check whether a given number is a perfect number.

In the Simple iteration method, we iterate through all the numbers from 1 to the desired number x to check if that specific number is a proper divisor. The code returns a true value if the sum of all the proper divisors is found to be equal to the number x, otherwise, it returns false.

The following code implements the Simple iteration method to check whether a given number is a perfect number.

def perfectornot(x):
        s = 0
        for i in range(1, x):
            if x % i == 0:
                s = s + i
        return s == x
    print(perfectornot(28))

Output:

True

Explanation

  • Created a function, which takes in the value x, which is the original number that needs to be evaluated.
  • We create a loop or an iteration for generating the numbers from 1 to x, and then the if statement to check if the number divided by the variable i gives no remainder and is a proper divisor.
  • All the proper divisors that are found out by the iteration are added together, and if the sum of proper divisors is equivalent to the original number x, then it is a perfect number. The result is then printed.

Use the square root method to check whether a given number is a perfect number.

Another method, which is arguably the more efficient method out of the two, is the square root method.

In this method, we iterate through all the numbers up until the square root of n is encountered. The basic concept is to add both i and x/i to the sum s, if the number i divides the original number x which is to be checked for a perfect number.

The following code implements the square root method to check whether a given number is a perfect number.

def perfectornot( x ):
        s = 1
        i = 2
        while i * i <= x:
            if x % i == 0:
                s = s + i + x/i
            i = i + 1
        return (True if s == x and x!=1 else False)
    print(perfectornot( 28 ))

Output:

True

Time complexity of an algorithm or a code can be defined as the total time that is essential for the program to run till its execution gets terminated. The first method has the time complexity of O(n), whereas the second method, which is the square root method, has the time complexity O(n^1/2).

Therefore, due to this difference in time complexities between the two methods, the second (square root) method is considered to be much more efficient than the simple iteration method.

That’s all about Perfect number in Python.

]]>
https://java2blog.com/perfect-number-python/feed/ 0