Python

Program for Spell Checker in Python

Program for Spell Checker in Python

Spelling errors are widespread, and most individuals are accustomed to software alerting them when they have made a mistake. Spell checking is a crucial function for many different products, from autocorrect on mobile phones to red underlining in text editors.

In 1971, for the DEC PDP-10, the first spell-checking programme was built. It was known as SPELL, and it was only capable of doing simple word comparisons and detecting one or two letter deviations. Spell checkers have evolved along with hardware and software. Modern spell checkers can deal with morphology and improve suggestions using statistics.

Python has a variety of libraries for this purpose, making creating a simple spell checker a 20-minute task.

TextBlob is one of these libraries, which is used for natural language processing and has a simple API to work with.

Program for Spell Checker in Python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Importing Required modules for implementing spell checker

Our spell-checking tool will be made up of two modules:

  • textblob module
  • spellchecker module

Let’s begin by installing and importing each one individually.

You can install the module using the pip package manager if you don’t already have it.

The spellchecker module must be imported before we can develop a spell checker in Python.

C: \Users\Admin > pip install spellchecker

In the same method, you can install the textblob module.

C: \Users\Admin > pip install textblob

2)Checking the spell using textblob module

TextBlob is a python module for processing textual data in the Python programming language. It provides a straightforward API for tackling standard natural language processing tasks including part of speech tagging, noun phrase extraction, sentiment analysis, classification, and translation, among others.

correct() method: The correct() method is the most basic approach to correct input text.

Below is the implementation:

from textblob import TextBlob
# first we tyoe the incorrect spelling text
given_text = "eaars"
print("The original text before spell checking = "+str(a))
correct_text = TextBlob(given_text)
# Getting the correct text and correcting the spelling using correc() functioon
print("The text after correcting given text: "+str(correct_text.correct()))

Output:

The original text before spell checking = eaars
The text after correcting given text : ears

3)Using spell checker module

Let’s have a look at how the spellchecker module corrects sentence faults.

Below is the implementation:

# importing  spellchecker library
from spellchecker import SpellChecker

# Make a spell variable and use it as a spellchecker ()
spellcheck = SpellChecker()
'''Construct a while loop. You must establish a variable called a word and make this variable
take real-time inputs from the user within this loop.'''

while True:
    word = input('Enter a word which may be of wrong spelling')
    # converting the word to lower case
    word = word.lower()
'''If the term is in the spellchecker dictionary, it will say "you spelled correctly.
Otherwise, you must choose the best spelling for that term.'''
   if word in spellcheck:
        print("'{}' it is spelled as correct".format(word))
    else:
        correctwords = spellcheck.correction(word)
        print("The best spellcorrections of given words'{}' is '{}'".format(word, correctwords))

Output:

Enter a word which may be of wrong spelling : eaars
The best spellcorrections of given word eaars is 'ears'

Explanation:

This program will use the spellchecker instance several times. It has a big amount of words stored in it. If you input any incorrect terms that aren’t in the spellchecker dictionary, the spellchecker will correct them. So now you know everything there is to know about this library.

Conclusion:

This was a quick overview of how to create your own spell checker using the Python programming language, which is simple to code, learn, and understand with only a few lines of code.
Related Programs:

Program for Spell Checker in Python Read More »

Python User Input from Keyboard – input() function

Python User Input from Keyboard – input() function

User Input from Keyboard – input() function in Python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)input() function

  • The input() built-in method in Python can read user input from the keyboard.
  • The user’s input is read as a string, which can then be assigned to a variable.
  • We must press the “Enter” button after entering the value from the keyboard. The user’s value is then read by the input() function.
  • The program will pause indefinitely while waiting for user input. There is no way to specify a timeout value.
  • The EOFError is produced and the application is ended if we type EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return).

2)Syntax of input() function

The input() function has the following syntax:

input(prompt)

On the console, the prompt string is printed, and the user is given control to enter the value. Print some helpful information to assist the user in entering the expected value.

3)Getting User Input using input() function

Here’s an example of getting user input and printing it to the console.

Below is the implementation:

value = input("Enter the value ")
print("the value of entered input = ", value)

Output:

Enter the value BTechGeeks
the value of entered input = BTechGeeks

4)Getting the type of entered input value

The value given by the user is always transformed to a string before being allocated to a variable. To be sure, let’s use the type() method to determine the type of the input variable.

Below is the implementation:

value = input("Enter the value which is of type string ")
print("the type of entered input value = ", type(value))
value1 = input("Enter the value which is of type integer ")
print("the type of entered input value = ", type(value1))

Output:

Enter the value which is of type string BTechGeeks
the type of entered input value = <class 'str'>
Enter the value which is of type integer 356
the type of entered input value = <class 'str'>

5)Getting integer as User input

There is no method to acquire a user input of an integer or any other kind. However, we can convert the entered string to an integer using the built-in functions.

Below is the implementation:

value = input("Enter the value ")
intValue = int(value)
print("the type of entered input value = ", type(intValue))

Output:

Enter the value 4312
the type of entered input value = <class 'int'>

6)Getting float as User Input

There is no method to acquire a user input of an float or any other kind. However, we can convert the entered string to an float using the built-in functions.

Below is the implementation:

value = input("Enter the value ")
floatValue = float(value)
print("the type of entered input value = ", type(floatValue))

Output:

Enter the value 4561823.198
the type of entered input value = <class 'float'>

In Python, using the input() function to get user input is fairly simple. It’s primarily used to give the user an option of operation and then change the program’s flow accordingly.
Related Programs:

Python User Input from Keyboard – input() function Read More »

CBSE Class 12 Computer Science Python Syllabus

CBSE Class 12 Computer Science Python Syllabus 2021 | Check 12th CBSE Computer Science Python Exam Pattern & How to Download easily?

CBSE Class 12th Computer Science Syllabus 2021 Free Download: Central Board of Secondary Education (CBSE) released the new and revised Computer Science Python Syllabus for Class 12 students (reduced by 30%) 2021. The deleted syllabus of class 12th CBSE Computer Science python is given here in a detailed way along with the latest syllabus 2021-2022.

So, students are urged to check the Revised CBSE 12th Computer Science Syllabus 2021 & kickstart their preparation for future CBSE Class 12 board exams. Below we have also provided some useful links to access and score well in the upcoming CBSE 12th Computer Science Board Exam 2021. Also, check out the detailed steps on how to download the CBSE Class 12 Computer Science Syllabus 2021 from the official site by heading to the below modules.

Click Here To Download CBSE 12th Computer Science Python Syllabus 2021

CBSE Class 12 Computer Science Python Syllabus 2021-22 (New)

For perfect CBSE 12th Board Exam Preparation, you should have to be familiar with the latest and revised CBSE Class 12 Computer science python syllabus and then need to gather the best books and study resources. Here we have provided the unit-wise syllabus of computer science for cbse class 12 students. Access them online and offline by downloading the latest CBSE Syllabus for Class 12 computer science 2021-2022 from the above link and below topics text.

Unit I: Computational Thinking and Programming – 2 – (80 Theory + 70 Practical)

  • Revision of the basics of Python
  • Functions: scope, parameter passing, mutable/immutable properties of data objects, pass arrays to functions, return values, functions using libraries: mathematical, and string functions.
  • File handling: open and close a file, read, write, and append to a file, standard input, output, and error streams, relative and absolute paths.
  • Using Python libraries: create and import Python libraries
  • Recursion: simple algorithms with recursion: factorial, Fibonacci numbers; recursion on arrays: binary search
  • Idea of efficiency: performance defined as inversely proportional to the wall clock time, count the number of operations a piece of code is performing, and measure the time taken by a program. Example: take two different programs for the same problem, and understand how the efficient one takes less time.
  • Data visualization using Pyplot: line chart, pie chart, and bar chart.
  • Data structures: lists, stacks, queues.

Unit 2: Computer Networks (CN) – (30 Theory + 10 Practical)

  • Structure of a network: Types of networks: local area and wide area (web and internet), new technologies such as cloud and IoT, public vs. private cloud, wired and wireless networks; concept of a client and server.
  • Network devices such as a NIC, switch, hub, router, and access point.
  • Network stack: amplitude and frequency modulation, collision in wireless networks, error checking, and the notion of a MAC address, main idea of routing.
  • IP addresses: (v4 and v6), routing table, router, DNS, and web URLs, TCP: basic idea of retransmission, and rate
    modulation when there is congestion (analogy to a road network), Protocols: 2G, 3G, 4G, WiFi. What makes a protocol have a higher bandwidth?
  • Basic network tools: traceroute, ping, ipconfig, nslookup, whois, speed-test.
  • Application layer: HTTP (basic idea), working of email, secure communication: encryption and certificates (HTTPS), network applications: remote desktop, remote login, HTTP, FTP, SCP, SSH, POP/IMAP, SMTP, VoIP, NFC.

Unit 3: Data Management (DM-2) – (20 Theory + 20 Practical)

  • Write a minimal Django based web application that parses a GET and POST request, and writes the fields to a file – flat file and CSV file.
  • Interface Python with an SQL database
  • SQL commands: aggregation functions – having, group by, order by.

Unit 4: Society, Law, and Ethics (SLE-2) – (10 Theory)

  • Intellectual property rights, plagiarism, digital rights management, and licensing (Creative Commons, GPL, and Apache), open source, open data, privacy.
  • Privacy laws, fraud; cyber-crime- phishing, illegal downloads, child pornography, scams; cyber forensics, IT Act, 2000.
  • Technology and society: understanding of societal issues and cultural changes induced by technology.
  • E-waste management: proper disposal of used electronic gadgets.
  • Identity theft, unique ids, and biometrics.
  • Gender and disability issues while teaching and using computers.

Do Refer: Python Programs for Class 12

Deleted Syllabus of Class 12 Computer Science Python CBSE

Unit I: Computational Thinking and Programming – 2

● Recursion – simple algorithms with recursion: print a message forever, the sum of the first n natural numbers, factorial, Fibonacci numbers, recursion on arrays: binary search
● The idea of efficiency: performance measurement in terms of the number of operations.
● Data-structures: Lists as covered in Class XI, Stacks – Push, Pop using a list, Queues – Insert, Delete using a list. (One of the data structures Stack or Queue. Note: While setting the question paper a student will have an option between Stack and Queue.)

Unit II: Computer Networks

● Web Scripting Client-side (VB Script, JavaScript, PHP) and Server-side (ASP, JSP, PHP), Web 2.0 (for social networking)
● E-commerce payment transactions using online banking, mobile banking, payment apps, and services.

Unit III: Database Management

CREATE TABLE, DROP TABLE, ALTER TABLE, UPDATE ….SET, INSERT, DELETE

1. Suggested Practical List: Python Programming

● Recursively find the factorial of a natural number
● Write a recursive code to find the sum of all elements of a list.
● Write a recursive code to compute the nth Fibonacci number

CBSE 12th Class Computer Science Exam Pattern 2021

Marking Scheme plays a vital role in exam preparation time. It covers all required details about the question paper like how many marks each question carries and many more. From the below tabulated CBSE Class 12 Computer Science Python Exam Pattern 2021, you can easily understand which chapter contains a number of marks and the total number of marks to be gained by the students in the examination.

Chapter NameTheory marksTheory periodsPractical periods
Computational Thinking and Programming – 2407050
Computer Networks1015
Database Management202520
TOTAL7011070

12th CBSE Computer Science Practical Exam Pattern & Syllabus

Students of class 12 should aware of the practical exam pattern and provided important lab syllabus topics before they start preparing for the cbse class 12 computer science board exams.

AreaMarks Allotted
Lab Test12
Report file7
Project8
Viva voce3
Total Marks30

A few of the sample lab assignments are listed below:

Python Programming:

  • Recursively find the factorial of a natural number.
  • Write a recursive code to find the sum of all elements of a list.
  • Write a recursive code to compute the nth Fibonacci number.
  • Read a text file line by line and display each word separated by a #.
  • Read a text file and display the number of vowels/ consonants/ uppercase/ lowercase characters in the file.
  • Create a binary file with a name and roll number. Search for a given roll number and display the name, if not found display the appropriate message.
  • Create a binary file with roll numbers, names, and marks. Input a roll number and update the marks.
  • Remove all the lines that contain the character `a’ in a file and write it to another file.
  • Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).
  • Write a Python program to implement a stack and queue using a list data-structure.
  • Take a sample of ten phishing e-mails (or any text file) and find the most commonly occurring word(s)

Database Management

  • Create a student table and insert data. Implement the following SQL commands on the student table:
  • ALTER table to add new attributes / modify data type / drop attribute
  • UPDATE table to modify data
  • ORDER By to display data in ascending/descending order DELETE to remove tuple(s)
  • GROUP BY and find the min, max, sum, count, and average
  • A similar exercise may be framed for other cases.
  • Integrate SQL with Python by importing the MySQL module.

Computer Science Project for CBSE Class XII

The aim of the class project is to create something that is tangible and useful. This should be done in groups of 2 to 3 students, and should be started by students at least 6 months before the submission deadline. The aim here is to find a real world problem that is worthwhile to solve. Students are encouraged to visit local businesses and ask them about the problems that they are facing. For example, if a business is finding it hard to create invoices for filing GST claims, then students can do a project that takes the raw data (list of transactions), groups the transactions by category, accounts for the GST tax rates, and creates invoices in the appropriate format. Students can be extremely creative here. They can use a wide variety of Python libraries to create user friendly applications such as games, software for their school, software for their disabled fellow students, and mobile applications, Of course to do some of this projects, some additional learning is required; this should be encouraged. Students should know how to teach themselves.

If three people work on a project for 6 months, at least 500 lines of code is expected. The committee has also been made aware about the degree of plagiarism in such projects. Teachers should take a very strict look at this situation, and take very strict disciplinary action against students who are cheating on lab assignments, or projects, or using pirated software to do the same. Everything that is proposed can be achieved using absolutely free, and legitimate open-source software.

How to download CBSE 12th Class Computer Science Syllabus 2021?

Students who want to download the revised CBSE 12th Class Computer Science Python Syllabus 2021 from the official website should follow the steps furnished below and get a pdf formatted 12th Computer Science syllabus 2021-2022.

  • Step 1 – Open the official website of CBSE ie., cbseacademic.nic.in.
  • Step 2 – After entering the home page, tap the ‘Senior secondary curriculum (XI-XII)’ menu.
  • Step 3 – Now, select ‘Academic Electives – (Group-A)’ option and then choose the ‘Computer Science New XII’
  • Step 4 – Once you choose that option, you will be available with the CBSE Class 12 Computer Science Syllabus 2021 to download for free in PDF. So, download and save it for further reference.

FAQs on CBSE Syllabus for Class 12 Computer Science Python 2021

1. How many units are there in the Class 12 CBSE Computer Science Python Syllabus?

Basically, there are four units that include sub-topics of computer science python in the CBSE Class 12 Computer Science Python Syllabus.

2. Is there any reduced syllabus in CBSE 12th Computer Science Syllabus 2021?

Yes, there is a 30% reduction of the syllabus for the academic year 2021-2022. So, you have to check the deleted syllabus of CBSE Class 12 Computer Science Python from our site before preparation.

3. How to download CBSE Syllabus for Class 12 Computer Science 2021 in PDF?

Just by clicking on the link provided in the above article, you can download CBSE Syllabus for Class 12 Computer Science 2021 in PDF format for free of cost.

4. What is the distribution of marks in the CBSE 12th Computer Science 2020-21 Syllabus?

The marks distribution for CBSE 12th Computer Science 2020-21 Syllabus is as follows:

I. Computational Thinking and Programming 2 – 40 Marks,
II. Computer Networks- 10 Marks and
III. Database Management -20 Marks

CBSE Class 12 Computer Science Python Syllabus 2021 | Check 12th CBSE Computer Science Python Exam Pattern & How to Download easily? Read More »

The “in and “not in” operators in Python

The “in” and “not in” operators in Python

In this post, we’ll look over Python membership operators, such as in and not in operators. These operators are used to determine whether or not a given data element is part of a sequence and, in the case of the identity operator, whether or not it is of a specific type.

Python Membership Operators:

These operators aid in validating if a particular element exists in or is a member of the provided data sequence. This data sequence can be a list, string, or tuple.

“in” operator(brief):

It determines whether or not the value is present in the data sequence. It returns a true value if the element is present in the sequence and a false value if it is not present in the sequence.

“not in ” operator (brief) :

This operator examines a sequence for the absence of a value. The out operator is the polar opposite of the in operator. When the element is not found or absent from the sequence, it evaluates to true, and when the element is found in the data sequence, it evaluates to false.

Python “in” and “not in” operators

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1) “in” Operator in Python

In Python, the in operator determines if a given value is a constituent element of a sequence such as a string, array, list, or tuple, among other things.

The statement returns a Boolean result that evaluates to True or False when used in a condition. The statement returns True if the supplied value is found within the sequence. When it isn’t found, though, we get a False.

Let us use an example to gain a better grasp of how the in operator works.

1)Checking if given element is present in list using in operator.

Below is the implementation:

# given list
given_list = ["hello", "this", "is", "BTechGeeks", "Python"]
# given element
element = "BTechGeeks"
# checking if the given element is present in given list or not using in opertor
# it returns true if is present else it returns false
print(element in given_list)

Output:

True

Explanation:

Here it returned true which means the given element BTechGeeks is present in given list.

2)Checking if given element is present in tuple using in operator.

Below is the implementation:

# given tuple
given_tuple = ["hello", "this", "is", "BTechGeeks", "Python"]
# given element
element = "BTechGeeks"
# checking if the given element is present in given tuple or not using in opertor
# it returns true if is present else it returns false
print(element in given_tuple)

Output:

True

Explanation:

Here it returned true which means the given element BTechGeeks is present in given tuple.

3)Checking if given element(string) is present in string using in operator.

Below is the implementation:

# given string
given_string = "hello this is BTechGeeks Python"
# given element
element = "BTechGeeks"
# checking if the given element is present in given string or not using in opertor
# it returns true if is present else it returns false
print(element in given_string)

Output:

True

Explanation:

Here it returned true which means the given element BTechGeeks is present in given string.

2) “not in” Operator in Python

In Python, the not in operator acts in the exact opposite way as the in operator. It likewise tests for the presence of a specified value within a sequence, but the return values are completely different from those of the in operator.

The statement returns False when used in a condition with the supplied value existing inside the sequence. When it is, we get a False, but when it isn’t, we get a True.

Simply replace the in operator with the not in one in the previous example.

Let us use an example to gain a better grasp of how the not  in operator works.

1)Checking if given element is present in list using not in operator.

Below is the implementation:

# given list
given_list = ["hello", "this", "is", "BTechGeeks", "Python"]
# given element
element = "BTechGeeks"
# checking if the given element is present in given list or not using not in opertor
# it returns true if is present else it returns false
print(element not in given_list)

Output:

False

Explanation:

Here it returned False which means the given element BTechGeeks is present in given list.

2)Checking if given element is present in tuple using not in operator.

Below is the implementation:

# given tuple
given_tuple = ["hello", "this", "is", "BTechGeeks", "Python"]
# given element
element = "BTechGeeks"
# checking if the given element is present in given tuple or not using not in opertor
# it returns true if is present else it returns false
print(element not in given_tuple)

Output:

False

Explanation:

Here it returned False which means the given element BTechGeeks is present in given tuple.

3)Checking if given element(string) is present in string using in operator.

Below is the implementation:

# given string
given_string = "hello this is BTechGeeks Python"
# given element
element = "BTechGeeks"
# checking if the given element is present in given string or not using not in opertor
# it returns true if is present else it returns false
print(element not in given_string)

Output:

False

Explanation:

Here it returned False which means the given element BTechGeeks is present in given string.

3)Working of Membership Operators (“in” and “not in” ) in Dictionaries:

We previously explored how the in and not in operators function with various types of sequences. Dictionaries, on the other hand, are not sequences. Dictionaries, on the other hand, are indexed using keys.

So, do the above operators work with dictionaries? If they do, how do they respond accordingly?

Let us provide an example to help us understand.

Below is the implementation:

# given dictionary
dictionary = {"hello": 100,
              "This": 200,
              "BTechGeeks": 300}
# checking using in and not in operators
print(100 in dictionary)
print(100 not in dictionary)

print("BTechGeeks" in dictionary)
print("BTechGeeks" not in dictionary)

Output:

False
True
True
False

First, we created a dictionary dictionary with a certain set of random keys and corresponding random values.

As shown in the result above, “100” in dictionary evaluates to False. In contrast, “BTechGeeks” in dict1 yields True.

As a result, it is evident that the in operator searches for the element among the dictionary keys rather than the values.

As previously stated, the not in operator here also evaluates in the same manner.
Related Programs:

The “in” and “not in” operators in Python Read More »

Program to Print Without Newline in Python

Python Program to Print Without Newline

When people convert from C/C++ to Python, they frequently ask how to print two or more variables or instructions without starting a new line. Because the print() method in Python always returns a newline. Python has a predefined format, so if you use print(a variable), it will automatically go to the next line.

Inside the command prompt, the Python print() built-in function is used to print the specified information. Python print’s default behavior is to append a newline character at the end.

You might want to print a value on the screen when programming, but keep it on the same line as the last value you displayed. You might want a user’s first and last name to show on the same line, for example. But, with Python, how can you print without a newline?

In this article, we’ll look at how to print in Python without using a new line.

Python Program to print without Newline

There are several ways to print without Newline in Python some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1:Using end in print() statement

From Python 3 onwards, a new parameter called end= has been added to print(). This argument removes the newline that is added by default in print().

This is a newline character by default (\n). As a result, we must modify this to prevent printing a newline at the conclusion.

We want the strings in the Python 3 print without newline example below to print on the same line. Simply add end=”” within print() .

There are numerous possibilities available for this decision. To print space-separated strings, we may use a space.

Below is the implementation:

# printing without newLine
print("hello", end=" ")
print("BTechGeeks")

Output:

hello BTechGeeks

We could alternatively use an empty string to print them consecutively and without a space.

# printing without newLine
print("hello", end="")
print("BTechGeeks")

Output:

helloBTechGeeks

Explanation:

Here we can see that it printed the two values without the space

Method #2:Printing the list elements without newline by using end

Consider the following list of items

givenlist= [“hello”, “this”, “is”, “BTechGeeks”, “platform”]

and you want to use a for-loop to print the values within the list So, using for loop and print(), you may display the values within the list by displaying each element of the list in a newline.

Implementation with newline using for loop:

# given list
givenlist = ["hello", "this", "is", "BTechGeeks", "platform"]
# traversing the list using for loop
for item in givenlist:
    print(item)

Output:

hello
this
is
BTechGeeks
platform

The list elements are printed one after the other on a new line in the output. What if you want every item in the list to be on the same line? Use the end parameter inside print() to eliminate the new line in Python and print all items from the list on the same line.

Below is the implementation to print list elements in same line(without newline):

# given list
givenlist = ["hello", "this", "is", "BTechGeeks", "platform"]
# traversing the list using for loop
for item in givenlist:
  # using end
    print(item, end=" ")

Output:

hello this is BTechGeeks platform

Method #3:Printing the list elements without newline by using *

We can print the list without newline by using * symbol.

Below is the implementation:

# given list
givenlist = ["hello", "this", "is", "BTechGeeks", "platform"]
# printing the list using *
print(*givenlist)

Output:

hello this is BTechGeeks platform

Method #4:Using sys module

Another option for printing without a newline in Python is to utilise the built-in module sys.

Here’s a working example of how to use the sys module to output Python strings without newlines.

To interact with the sys module, first use the import keyword to import the sys module. Then, to print your strings, use the sys module’s stdout.write() method.

Below is the implementation:

# importing system module
import sys
sys.stdout.write("hello this is BTechGeeks Platform")
sys.stdout.write("this is BTechGeeks article")

Output:

hello this is BTechGeeks Platformthis is BTechGeeks article

Method #5: By Making our own printf() method as C

In Python, we can also write our own printf() function! Yes, we can do this with the functools module, which allows us to create new functions from old ones with functools.partial()

Let’s apply the same logic to end  keyword argument and develop our printf() method

Below is the implementation:

# importing functools
import functools
# creating printf function using partial() function in functools
printf = functools.partial(print, end=" ")
#using printf
printf("hello this is BTechGeeks Platform")
printf("this is BTechGeeks article")

Output:

hello this is BTechGeeks Platform this is BTechGeeks article

We can even add a semicolon to this (the Python compiler will not protest) to restore our original C printf() code!
Related Programs:

Python Program to Print Without Newline Read More »

Increment Operation in Python

Increment Operation in Python

What is the procedure for performing a Python increment operation? You might want to try extending a comparable increment functionality to Python if you’re coming from a language like C++ or Java.

However, as we will see later in this essay, this is not the case. Let’s have a look at how we may use Python’s Increment (++) operation to achieve comparable results.

Increment Operation in Python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Examples of Increment operation in Python

Before we get into the specific changes, let’s have a look at how you increment a variable in Python.
The code below demonstrates how practically all Python programmers increment integers or related variables.

Implementation Examples:

1)Incrementing number by 1

# given number
number = 19
# increment it by 1
number += 1
print(number)

Output:

20

Explanation:

We started by taking a number and increasing its value by one, giving us 20 in this case.

2)Incrementing number by 200

# given number
number = 19
# increment it by 200
number += 200
print(number)

Output:

219

Explanation:

We started by taking a number and increasing its value by 200, giving us 219 in this case.

3)Incrementing string variable by 1

Let us see what will happen if we increment the string variable by 1

# given number
variable = "vicky"
# increment it by 1
variable += 1
print(variable)

Output:

Traceback (most recent call last):
  File "/home/ff2eb412892e1f6025a70b5a2cffdb91.py", line 4, in <module>
    variable += 1
TypeError: must be str, not int

Explanation:

We got that error because we incremented a string variable with an integer.

4)Incrementing string with another string(string concatenation)

In the above case we incremented the string with number let us see what’s the output when we increment the string with string.

# given number
variable = "vicky"
# increment it by another string
variable += "cirus"
print(variable)

Output:

vickycirus

Explanation:

Here it concatenated the two strings.

5)Incrementing float value by 1

Let us see what will happen if we increment the float value with  integer(1 in this case)

# given number
variable = 1.4
# increment it by another string
variable +=1
print(variable)

Output:

2.4

Explanation:

We started by taking a decimal number and increasing its value by 1, giving us 2.4 in this case.

6)Incrementing float value with float

Let us see what will happen if we increment the float value with float value

# given number
variable = 1.5
# increment it by another string
variable +=1.6
print(variable)

Output:

3.1

Explanation:

We started by taking a decimal number and increasing its value by 1.6, giving us 3.1 in this case.

2)Can we use ++ operator in Python?

Let us check that by implementing it.

Below is the implementation:

# given number
variable = 7
# increment it by another string
variable++
print(variable)

Output:

 File "/home/b1d4000b0d8d478263f6b7213398eaf8.py", line 4
    variable++
             ^
SyntaxError: invalid syntax

There is, however, an issue. Python does not allow the usage of the ++ “operator” by default. The ++ operator, also known as the increment operator in C++ and Java, does not exist in Python.

3)Why does Python lack a ++ operator?

If you want to learn more about this, you’ll need some foundation in programming language design.

The decision to exclude the ++ operator from Python is a design choice. People in charge of adding new features to the Python language believed that a CPP-style increment operator was unnecessary.

When the Python interpreter parses the a++ symbol from our input, it does it in the following way:

  • Because the binary + operator is the addition operator, a++ will be handled as a, +, and +. However, Python expects a number following the first + operator. As a result, it will generate a syntax error on a++ because the second + is not a number.

Similarly, the pre-increment ++a will be handled as follows:

  • In Python, the unary + operator refers to the identity operator. This simply returns the integer that comes after it. This is why it is an integer identity operation.
  • For example, the value of +7 is simply 7, whereas the value of +-7 is -7. This is a unary operator that only works with real numbers.
  • The ++a is parsed as + and +a, while the second +a is handled as (+a), which is merely a sign.
  • As a result, +(+(a)) evaluates to a.

So, even if we intended to increase the value of a by one, we can’t do so using the ++ symbols because this type of operator doesn’t exist.

To perform this type of increase, we must utilize the += operator.

like

number+=1
number-=1

4)How does += Works/Evaluated

You could think it’s an assignment statement because there’s a = symbol.

This is not, however, a typical assignment statement. An augmented assignment statement is what it’s called.

In a standard assignment statement, the right-hand side is evaluated first, then the left-hand side is assigned.

# 4 + 9 is evaluated to 13, before assigning to number
number = 4 + 9

In this enhanced assignment statement, however, the left side is evaluated first, followed by the right side. This is done so that the modified value can be written in-place to the left side.

# Reads the value of number, before adding 8 to it in-place
number += 8

Without using a reassigning statement like a = a + 1, this is the only way to increase a variable. However, in this case, the choice is irrelevant because the interpreter would optimize the code at runtime.

Increment Operation in Python Read More »

Program to Calculate the Standard Deviation

Python Program to Calculate the Standard Deviation

Standard Deviation:

In statistics, the standard deviation is a measure of spread. It’s a metric for quantifying the spread or variance of a group of data values. It is quite similar to variance in that it delivers the deviation measure, whereas variance offers the squared value.

A low Standard Deviation value implies that the data are more evenly distributed, whereas a high number suggests that the data in a set are dispersed from their mean average values. The standard deviation has the advantage of being expressed in the same units as the data, unlike the variance.

Given a list of numbers , the task is to calculate the standard deviation of the given list in python.

Examples:

Example1:

Input:

given list = [34, 14, 7, 13, 26, 22, 12, 19,29, 33, 31, 30, 20, 10, 9, 27, 31, 24]

Output:

The given list of numbers : 
34 14 7 13 26 22 12 19 29 33 31 30 20 10 9 27 31 24 
Standard deviation of the given list = 9.008529001520827

Example2:

Input:

given list = [4, 7, 1, 2, 17, 19, 11, 19, 18, 13, 5, 3, 17]

Output:

The given list of numbers : 
4 7 1 2 17 19 11 19 18 13 5 3 17 
Standard deviation of the given list = 7.042908781360447

Example3:

Input:

given list = [12, 1, 4, 5, 19, 11, 13, 11, 12, 5, 5, 6, 7, 10, 15, 14]

Output:

The given list of numbers : 
12 1 4 5 19 11 13 11 12 5 5 6 7 10 15 14 
Standard deviation of the given list = 4.8425200051213

Python Program to Calculate standard deviation in Python

There are several ways to calculate the standard deviation in python some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1:Using stdev() function in statistics package

In Python, the statistics package has a function called stdev() that can be used to determine the standard deviation. The stdev() function estimates standard deviation from a sample of data instead of the complete population.
stdev ( [data-set], xbar )

Parameters:

[data] : An iterable with real-valued numbers as parameters.
xbar (Optional): Uses the data set's actual mean as a value.

Return type:

Returns the real standard deviation of the values supplied as parameters.

Exceptions :

  • For data-sets with fewer than two values supplied as parameters, StatisticsError is thrown.
  • When the value provided as xbar does not match the actual mean of the data-set, the value is impossible/precision-less.

We’ve built a list and applied the standard deviation operation to the data values in the following example:

Below is the implementation:

# importing statistics
import statistics
# given list
given_list = [34, 14, 7, 13, 26, 22, 12, 19,
              29, 33, 31, 30, 20, 10, 9, 27, 31, 24]
# using stdev() fun to calculate standard devaition
standarddevList = statistics.stdev(given_list)
# print the given list and standard deviation
print("The given list of numbers : ")
for i in given_list:
    print(i, end=" ")
# printing new empty line
print()
# printing the standard deviation of the given list of numbers
print("Standard deviation of the given list =", standarddevList)

Output:

The given list of numbers : 
34 14 7 13 26 22 12 19 29 33 31 30 20 10 9 27 31 24 
Standard deviation of the given list = 9.008529001520827

Method #2:Using std() function in NumPy module

The NumPy module provides us with a number of functions for dealing with and manipulating numeric data items.

Python’s numpy package includes a function named numpy.std() that computes the standard deviation along the provided axis. This function returns the array items’ standard deviation. The standard deviation is defined as the square root of the average square deviation (calculated from the mean). The standard deviation for the flattened array is calculated by default. The average square deviation is generally calculated using x.sum()/N, where N=len (x).

The standard deviation for a range of values can be calculated using the numpy.std() function, as demonstrated below.

Below is the implementation:

# importing numpy
import numpy as np
# given list
given_list = [34, 14, 7, 13, 26, 22, 12, 19,
              29, 33, 31, 30, 20, 10, 9, 27, 31, 24]
# using std() fun to calculate standard devaition
standarddevList = np.std(given_list)
# print the given list and standard deviation
print("The given list of numbers : ")
for i in given_list:
    print(i, end=" ")
# printing new empty line
print()
# printing the standard deviation of the given list of numbers
print("Standard deviation of the given list =", standarddevList)

Output:

The given list of numbers : 
34 14 7 13 26 22 12 19 29 33 31 30 20 10 9 27 31 24 
Standard deviation of the given list = 8.754716541864452

Method #3:Using std() in pandas Module

The Pandas module allows us to work with a bigger number of datasets and gives us with a variety of functions to apply to them.

We may conduct different statistics operations on the data values using the Pandas module, one of which is standard deviation, as shown below

Below is the implementation:

# importing pandas
import pandas as pd
# given list
given_list = [34, 14, 7, 13, 26, 22, 12, 19,
              29, 33, 31, 30, 20, 10, 9, 27, 31, 24]
# converting the given_list to DataFrame
dataList = pd.DataFrame(given_list)
# calculating the  standard devaition using std() function
standarddevList = dataList.std()

# print the given list and standard deviation
print("The given list of numbers : ")
for i in given_list:
    print(i, end=" ")
# printing new empty line
print()
# printing the standard deviation of the given list of numbers
print("Standard deviation of the given list =", standarddevList)

Output:

The given list of numbers : 
34 14 7 13 26 22 12 19 29 33 31 30 20 10 9 27 31 24 
Standard deviation of the given list = 0 9.008529
dtype: float64

Explanation:

In this example, we built a list and then used the pandas.dataframe() function to convert the list into a data frame. Using the std() function, we calculated the standard deviation of the values in the data frame.
Related Programs:

Python Program to Calculate the Standard Deviation Read More »

How to Perform the Python Division Operation

How to Perform the Python Division Operation?

In general, the data type of an expression is determined by the types of its arguments. This rule applies to the majority of operators: for example, when we add two numbers, the result should be an integer. However, this does not function effectively in the case of division because there are two separate expectations. Sometimes we want division to produce an exact floating point number, but other times we want a rounded-down integer result.

If you tried to split an unequal number of candies equally, you would only have a few remaining candies. Those who remain after division are referred to as remainders.

In this post, we will look at an arithmetic operation called Python Division.

Examples:

Input:

number1=17
number2=4

Output:

number1/number2=4.25
number1//number2=4

Performing Division Operation in Python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Division Operation

Python includes a number of built-in operators and functions for performing mathematical calculations.

The ‘/’ operator is used to execute division operations on data values of both the float and int data types.

The Python ‘/’ operator has the advantage of being able to handle both decimal and negative values.

Syntax:

numb1/numb2

Example1:

Dividing two positive numbers

Below is the implementation:

# given two numbers
# given first number numb1
numb1 = 73
# giveen second number numb2
numb2 = 25
# dividing the given two numbers numb1 and numb2
print(numb1, "/", numb2, "=", numb1/numb2)

Output:

73 / 25 = 2.92

Example2:

Dividing one positive number and one negative number

Below is the implementation:

# given two numbers
# given first number numb1
numb1 = -73
# giveen second number numb2
numb2 = 25
# dividing the given two numbers numb1 and numb2
print(numb1, "/", numb2, "=", numb1/numb2)

Output:

-73 / 25 = -2.92

Example3:

Dividing two negative numbers

Below is the implementation:

# given two numbers
# given first number numb1
numb1 = -73
# giveen second number numb2
numb2 = -25
# dividing the given two numbers numb1 and numb2
print(numb1, "/", numb2, "=", numb1/numb2)

Output:

-73 / -25 = 2.92

Example4:

Dividing one decimal number with the integer

Below is the implementation:

# given two numbers
# given first number numb1
numb1 = 73.153
# giveen second number numb2
numb2 = 25
# dividing the given two numbers numb1 and numb2
print(numb1, "/", numb2, "=", numb1/numb2)

Output:

73.153 / 25 = 2.92612

Example5:

Dividing two decimal numbers

Below is the implementation:

# given two numbers
# given first number numb1
numb1 = 22.5
# giveen second number numb2
numb2 = 4.5
# dividing the given two numbers numb1 and numb2
print(numb1, "/", numb2, "=", numb1/numb2)

Output:

22.5 / 4.5 = 5.0

2)Division Operation on Two Tuples

Tuple:

Python Tuple is a type of data structure that is used to store a sequence of immutable Python objects. The tuple is similar to lists in that the value of the items placed in the list can be modified, however the tuple is immutable and its value cannot be changed.

The Python floordiv() method, in conjunction with the map() function, can be used to divide data values contained in a Tuple data structure.

The floordiv() method in Python is used to divide all of the elements of a data structure, i.e. it divides the data structure element by element. Furthermore, the Python map() function applies any passed/provided function or operation on a set of iterables such as tuples, lists, and so on.

Syntax:

tuple(map(floordiv, tuple1, tuple2))

The floordiv() method divides the items using integer division, which returns only the integer portion of the quotient and ignores the decimal portion.

Below is the implementation:

from operator import floordiv

# given two tuples
# given tuple1
tuple1 = (17, 27, 13, 25)
# given tuple2
tuple2 = (7, 4, 2, 6)
# performing division on tuple 1 and tuple 2
division = tuple(map(floordiv, tuple1, tuple2))
# printing the division of tuple 1 and tuple 2
print("printing the division of tuple 1 and tuple 2 : " + str(division))

Output:

printing the division of tuple 1 and tuple 2 : (2, 6, 6, 4)

3)Division Operation on two dictionaries

Python division operations can be performed on dictionary components using the Counter() function and the ‘//’ operator.

The Counter() function stores the dictionary key-value data as dict keys and the dict element count as related values.

The ‘//’ operator divides the data elements at the integer level.

Syntax:

{key: dictionary1[key] // dictionary2[key] for key in dictionary1}

Below is the implementation:

# importing collections from Counter
from collections import Counter
# given two dictionaries
dictionary1 = {'hello': 830, 'This': 250, 'BTechGeeks': 64}
dictionary2 = {'hello': 420, 'This': -5, 'BTechGeeks': 4}
# using counter to count frequency of elements in two dictionaries
dictionary1 = Counter(dictionary1)
dictionary2 = Counter(dictionary2)
# dividing two dictionaries based on keys
division = Counter(
    {key: dictionary1[key] // dictionary2[key] for key in dictionary1})
# print the result after dividing two dictionaries
print("Dividing two dictionaries gives =" + str(dict(division)))

Output:

Dividing two dictionaries gives ={'hello': 1, 'This': -50, 'BTechGeeks': 16}

Explanation:

In the preceding example, we used the Counter() method to store the key-value pairs of the input dictionary in such a way that the input dictionary now has the key as the dictionary items and the value as the count of items existing in the dict.

In addition, we provided the keys to the ‘//’ operator, who performed the division operation.

4)Difference between “/” and “//” operators

The fundamental and most likely only distinction between the ‘/’ and ‘//’ division operators is that the ‘/’ operator returns float values as the result of division, whereas the ‘//’ operator returns the full quotient ( the integer as well as the decimal part).

The ‘//’ division operator, on the other hand, returns an integer value as a result of division, i.e. only the integer component of the quotient value.

Below is the implementation:

print(17/4)
print(17//4)

Output:

4.25
4

Conclusion:

As a result of this article, we now understand how to do division operations in Python and ways to perform division operation in Python language.
Related Programs:

How to Perform the Python Division Operation? Read More »

Different Ways to convert seconds into Hours and Minutes

Python program to convert seconds into day, hours, minutes and seconds

In this post, we will look at various Python techniques for converting seconds to hours and minutes.

Date and Time

Python, as a multipurpose language, can be used for a variety of reasons. Python includes a number of packages that help us with data manipulation tasks.

To achieve the same result in timestamp conversion, i.e. conversion of seconds to hours or minutes, numerous strategies might be considered.

Examples:

Input:

timeSeconds=30000

Output:

converting given time in seconds 30000 = 8 hrs 20 minutes

Different Ways to convert seconds into Hours and Minutes in Python

There are several ways to convert seconds into hours and minutes in python some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1: Using mathematical formula

We will write a generic function which converts the given time into hours and minutes

First, we convert the supplied seconds value to the 24 hour format.

timeseconds = timeseconds % (24*3600)

Furthermore, because one hour is equal to 3600 seconds and one minute is equal to 60 seconds, we use the below mathematical logic to convert seconds to hours and minutes.

timehour = timeseconds/3600

timeminutes = timeseconds//60

Below is the implementation:

def convertSec(timeseconds):
    secondValue = timeseconds % (24 * 3600)
    timeHour = secondValue // 3600
    secondValue %= 3600
    timeMinutes = secondValue // 60
    secondValue %= 60
    print("converting given time in seconds",
          timeseconds, "=", timeHour, "hrs", timeMinutes, "minutes")


# given time in seconds
timeseconds = 30000
# passing given time in seconds to convertSec function to convert it to minutes and hours
convertSec(timeseconds)

Output:

converting given time in seconds 30000 = 8 hrs 20 minutes

Method #2: Using time module in python

The Python time module includes time. By giving the format codes to the strftime() function, you can display the timestamp as a string in a certain format.

The function time.gmtime() is used to convert the value supplied to it into seconds. Furthermore, the time.strftime() function converts the value supplied from time.gmtime() into hours and minutes using the format codes provided.

Below is the implementation:

import time
givenseconds = 30000
#converting given time in seconds to hours and minutes
temp = time.gmtime(givenseconds)
resultantTime = time.strftime("%H:%M:%S", temp)
#printing the given time in seconds to hours and minutes
print("converting given time in seconds", givenseconds,
      "=", resultantTime)

Output:

converting given time in seconds 30000 = 08:20:00

Method #3: Using datetime module in Python

The Python datetime module has a number of built-in functions for manipulating dates and times. The date and time. The timedelta() function manipulates and represents data in the correct time format.

Below is the implementation:

import datetime
# given time in seconds
givenSeconds = 30000
#converting given time in seconds to hours and minutes
resultantTime = datetime.timedelta(seconds=givenSeconds)
# printing the given time in seconds to hours and minutes
print("converting given time in seconds", givenSeconds,
      "=", resultantTime)

Output:

converting given time in seconds 30000 = 8:20:00

Method #4:Using divmod function

You may get the result quickly with only two mathematical operations by using the divmod() function, which performs a single division to generate both the quotient and the remainder.

This is similar to method 1

Below is the implementation:

# given time in seconds
timeSeconds = 30000
# storing it in another variable
givenSeconds = timeSeconds
# converting it into minutes and seconds
timeMinutes, timeSeconds = divmod(timeSeconds, 60)
# converting it into hours and minutes
timeHour, timeMinutes = divmod(timeMinutes, 60)
# printing the given time in seconds to hours and minutes
print("converting given time in seconds", givenSeconds,
      "=", timeHour, "hrs", timeMinutes, "minutes")

Output:

converting given time in seconds 30000 = 8 hrs 20 minutes

Related Programs:

Python program to convert seconds into day, hours, minutes and seconds Read More »

Create a Thread using Class in Python

Creating a Thread using Class in Python

In this article, we will discuss how we can create thread in python by extending class from Thread class or calling a member function of the class.

Python provides a threading module to create and manage threads.

Extend Thread class to create Threads :

Let’s create a FileLoadTh class by extending Thread class provided by the threading module where it mimics functionality of a File loader and it’s run() method sleeps for sometime.

When we start thread by calling start() function, it will invoke run() method of Thread class and overriden run() method will be executed which may contain any custom implementation.

It is better to wait for other threads to finish calling join() method on FileLoaderTh class object before returning from main thread.

from threading import Thread
import time
# FileLoadTh extending Thread class
class FileLoaderTh(Thread):
   def __init__(self, fileName, encryptionType):
       # Calling Thread class's init() function
       Thread.__init__(self)
       self.fileName = fileName
       self.encryptionType = encryptionType
   # Overriding run() of Thread class
   def run(self):
       print('Loading started from file : ', self.fileName)
       print('Encryption Type : ', self.encryptionType)
       for i in range(5):
           print('Please wait loading... ')
           time.sleep(3)
       print('Loading finished from file : ', self.fileName)
def main():
   # Create an object of Thread
   th = FileLoaderTh('threadDemo.csv','DOC')
   # calling Thread class start() to start the thread
   th.start()
   for i in range(5):
       print('Inside main function-------')
       time.sleep(3)
   # Wait for thread to finish
   th.join()
if __name__ == '__main__':
   main()
Output :
Loading started from file :  threadDemo.csv
Inside main function-------
Encryption Type :  DOC
Please wait loading...
Inside main function-------
Please wait loading...
Inside main function-------
Please wait loading...
Please wait loading...
Inside main function-------
Please wait loading...
Inside main function-------
Loading finished from file :  threadDemo.csv

Create a Thread from a member function of a class :

Now let’s create a thread that executes loadcont() memeber function of FileLoadTh class. For that we can create a object and then pass the function with object to target argument of Thread class constructor.

So both main() function and loadcont() member function will run in parallel and at the end main() function will wait for other threads calling join() function on the same object.

import threading
import time
class FileLoaderTh():
   def __init__(self):
       pass
   
   def loadcont(self, fileName, encryptionType):
       print('Loading started from file : ', fileName)
       print('Encryption Type : ', encryptionType)
       for i in range(5):
           print('Loading ... ')
           time.sleep(3)
       print('Loading finished from file : ', fileName)
def main():
   # Creating object of FileLoaderTh class
   fileLoader = FileLoaderTh()
   # Create a thread using member function of FileHolderTh class
   th = threading.Thread(target=fileLoader.loadcont, args=('threadDemo.csv','DOC', ))
   # Start a thread
   th.start()
   # Print some logs in main thread
   for i in range(5):
       print('Inside main Function')
       time.sleep(3)
   # Wait for thread to finish
   th.join()
if __name__ == '__main__':
   main()
Output :
Loading started from file :  threadDemo.csv
Encryption Type :  DOC
Inside main Function
Loading ...
Inside main Function
Loading ...
Inside main Function
Loading ...
Inside main Function
Loading ...
Loading ...
Inside main Function
Loading finished from file :  threadDemo.csv

 

Create a Thread using Class in Python Read More »