Floating-Point and Integer Numbers in Python

Welcome to chapter 6 of our python course. Previously, we introduced integers and saw how they may be combined with strings and stored in variables. Today, we'll take a closer look at the python number types and how they're stored in variables to see what actions are possible.

What you'll learn in this tutorial is how to:

  • Add, subtract, multiply, and divide numbers.
  • Work with modular.
  • Use exponents.
  • Use expressions.
  • Use a predetermined number of decimal places to round numbers
  • Use strings to format and show numeric data.

With this in mind, let`s start.

How are integers created?

Integers can be created by simply inputting a number. For example, the tutorial variable is assigned the integer 6 in the following way:

>>>Tutorial = 6

In this case, the integer literal is 6 since it is written into the code exactly as it appears. Using int () and str (), you can turn a string containing an integer into a number (). Commas or decimal points are commonly used to separate digits in huge quantities written by hand. When compared to 1000000, the value 1,000,000 is easier for reading. Use underscores (_) instead of the commas (,) if you want to separate digits in an integer literal. Integer literals of one million can be expressed in one of the following ways:

There is no limit to the size of an integer, which may seem unexpected given that computers have a finite quantity of storage. Atom`s interactive window may be used to enter in the largest number you can think of and Python will be able to run it with no problem.

Floating-Point Numbers

Numbers having decimal places are called floating-point numbers. -1.75 is a floating-point number, just like 1.0. float is the name of the data type for floating-point numbers:

>>> type (1.0)

<class 'float'>

A floating-point literal or a text converted to a float using float () may be used to construct floats, much like integers.

It is possible to express a floating-point literal in any one of three ways. There are various ways to construct a float literal with a value of one million.

To produce integer literals, you can utilize the first two techniques. An E notation float literal is also used in the third technique.

Exponential notation - what is it?

Numerical values that might otherwise result in a lengthy string of digits in decimal form can be expressed using the E notation.

You can use E notation to write a floating-point literal by starting with an integer and ending with a value. The number before e is multiplied by 10 raised to power the value that is after e. This means that 1e6 is comparable to 1×106.

Displaying very big floating-point integers with E notation is also possible in Python.

It is true that floats have a maximum size, unlike integers. Your system's maximum floating-point number will vary, but a value like 2e400 should be much beyond the capability of the majority of PCs. 2e400 is equal to 2×104°°, which is a staggeringly large digit!

When you get close to maximum allowed float value, the specialized float inf is returned by Python.

The symbol "inf" represents infinity, and it simply indicates that the number you're attempting to compute exceeds the computer's maximum supported floating-point value. Inf is still a float type:

A negative floating-point value that exceeds your computer's minimum floating-point number is represented by the -inf keyword in Python.

If you're a coder, you're unlikely to see inf and -inf unless you deal with exceedingly high numbers.

Let's see whether we grasp numbers correctly.

Exercise 1: Create two variables, num1 and num2, by writing a python program. Integer literals 25000000 should be allocated to both num1 and num2, one written with underscores and the other without. Two distinct lines should be used to print num1 and num2.

Mathematical expressions and operators

In this session, Math operations such as multiplication, subtraction, addition and division will be covered. We'll also pick up a few coding standards for expressing mathematical ideas.

PEP 8 Recommendations

Anywhere you can, keep your whitespace free of trailing spaces. A backslash, space, and newline do not constitute a line continuation indication because they are both hidden. Pre-commit hooks in many projects including CPython itself reject it, and some editors do not save it.

Assigning (=), augmenting (+=, -=, etc.), comparing (==,!=, >, =, >=), Booleans, and comparison operators (is, isn't, is, isn't), as well as any other binary operators, should always be enclosed in a single space on either side (and, or, not).

If operators of the lowest priority are used, consider separating them with whitespace. Each binary operator should have precisely the same number of whitespaces on either side.

Addition

The + operator is used to perform addition operations:

>>> 1 + 2

"Operands" refers to the values placed before and after the plus sign (+). This example uses two integers, but the type of operands does not have to be the same.

Adding an int to a float is as simple as this:

The sum of 1.0 and 2 is a float, as shown is 3.0. When a float is multiplied by another float, the output is always another float. It is always an int when two integers are added together.

PEP 8 proposes using a space to separate the operands of an operator.

Despite the fact that Python is capable of evaluating 1+1, many programmers prefer the more readable 1+1. All of the operators in this section should follow this general rule of thumb.

Subtraction

To perform subtraction, you need to use the - operator between the integers.

An int is always produced when two integers are subtracted. The outcome is always a float when one of the operands is a float.

To express negative values, the - operator can be used as follows:

>>> -3

Output: -3

Even though it may appear to be strange, subtracting a negative from another number is possible.

The first of the four instances are the most in line with PEP 8. It's possible to make it extra clear that the second - is altering 3 by placing parenthesis around it.

In order to make your code clearer, it is recommended that you utilize parenthesis. Despite the fact that computers are able to run code, humans are only able to read it. Your code should be as readable and understandable as possible.

Multiplication

Use the * operator to multiply two numbers:

There are no exceptions to this rule when it comes to multiplication. When you multiply two integers, you get an int, and when you multiply a float by a number, you get a float.

Division

When two numbers are to be divided, the / operator is used:

The / operator always returns a float, unlike addition, subtraction, and multiplication, which yield integers. You may use int () to ensure that the result of dividing two numbers is an integer:

It is important to note that the int () function discards any fractional parts of the number

The floating-point number 2.5 is obtained by dividing 5.0 by 2, while the integer 2 is obtained by subtracting .5 from the result of int (2.5).

Floor Division operator

The operator (//), often known as the floor division operator, can be used instead of the cumbersome int (5.0 / 2):

First, the / operator splits the numbers on each side of it, and then rounds down to an integer. When one of the values is negative, you may not get the expected result.

For instance, -3 / 2 produces -2. The first step is to divide -3 by 2 to get -1.5. Then -2 is rounded to the nearest -2. -1.5. 3 / 2 returns 1, on the other hand, since both values are positive.

A float number is returned if one operand is a float value, as seen in the preceding example. And that's why 9// 3, and 5.0// 2, respectively, return the integers 3 and 2.0, respectively.

When you divide a number by 0, the following happens:

If Python encounters a ZeroDivisionError, it warns you that you've just attempted to violate a universal law.

Exponents

When you use the ** operator, you can multiply an integer by a power.

Integers are not required to be used as exponents. Floats are another option:

Raising a number to power 0.5 implies taking the square root of that number. The square root of nine is a float, thus even though nine`s data type is an int, Python generates a float 3.0. If both operands of an expression are integers, the ** operator returns an integer and if one of the operands is floating-point number it returns a float.

It's also possible to raise numbers to negative powers like shown below:

If you divide a number raised to a positive power by 1, then you have raised the number to the negative power. As a result, 2 ** -1 equals 1 / (2 ** 1), which is equal to 1 / 2 or 0.5. It's easy to see how 2 ** -2 may be represented as 1 / (2 ** 2), 1 / 4 or 0.25.

Using the Modulus Operator

5% of 3 is 2, so 3 divides 5 once and gives a remainder of 2. Seven also divides 20 twice, leaving 6 as a remainder. In the previous example, 16 divided by 8 is 0, thus 16 % 8 equals 0. The outcome of dividing the value to the right of % by the number to the left is always 0.

Determining the divisibility of two numbers is a typical use of percent. Number n, for example, is only an odd number when n % 2 is zero. What do you suppose is returned by 1% 0? Let's give this a try.

When you divide one by zero, you get 1 which is the remainder of 1 % 0. Nevertheless, Python throws a ZeroDivisionError since it is impossible to divide 1 by 0.

An error like ZeroDivisionError has little impact on your project in interactive window of IDLE. Even if a prompt window will pop up, you can continue to write code in your editor until the error is fixed.

The execution of a script is halted if Python discovers an error while running it. The software crashes in other words.

When you use the percent operator with negative values, things get a little more complicated:

Python has a well-defined behavior that produces these outcomes, even if they appear surprising at first. To find an integer's residual after multiplying it by another number, Python utilizes the formula r = x- (y * (x / y)).

Arithmetic Expressions

Complex expressions can be created by combining operators in new and interesting ways. Python can calculate or evaluate an expression to yield a result made up of integers, operators, and parentheses.

An example of an arithmetic expression is shown below.

Evaluating expressions follows the same set of guidelines as performing standard arithmetic operations. These rules were presumably taught to you as the sequence of operations in school.

Among the operators that have equal precedence are these operators "*," "/," "%," and "%". Thus, 2*3 - 1 yields 5, rather than 4, when divided by 3. Because the * operator takes precedence over the - operator, 2*3 is evaluated first.

In the above example, you may have noticed that the requirement requiring a space before and after each operator was not followed. Whitespace in complex expressions is addressed in PEP 8:

If the operators with the lowest priority are being used, then whitespace should be added around them. Using a single space and the equal number of whitespaces on both sides of a binary operator is perfectly acceptable.

Even if parenthesis isn’t essential, it's always good to include them to indicate the order in which steps should be taken.

Conclusion

In this lesson, you've learned how to use Python's numbers with expressions. In the next chapter, you'll learn how to employ math functions and number techniques and learn how to avoid typical mistakes that might lead to program failures.

How to use Variables in Python?

Welcome back! This is the fifth lesson in our Python programming course. In the last chapter, we discussed how string data types are used in Python. In this tutorial, we’re going to discuss variables in python and the rules for naming them in Python. In addition, you'll learn the fundamentals of working with numbers and strings.

What are variables?

All programming languages use variables as a fundamental building block of their language. It is the allocation of memory that is dedicated to data storage and manipulation. Variables are program elements that keep track of data. The following is an example of a variable.

x = 100

It's called x in the diagram below, and it has a value of 100 in it. In this case, the variable name is x, and the data it contains is the number.

For a variable, its data type is just the type of data it contains.

Data types - what are they?

If a variable has a certain data type, it can be used with any mathematical, relational, or logical operation without resulting in an error; this is known as the data type in programming. There are many different types of data, such as strings and integers, that are used to categorize different kinds of information.

How do computers store Python variables?

As a Python programmer, we don't have to do anything to free up space. Garbage collection handles this.

There are two types of memory:

Stack memory

Stack memory is used to hold all functions and their calling references. The lifo rule governs how a stack operates. Continuous blocks make up the stack memory. When a function is called, the variables it returns are kept in the program's call stack, where they can be freed upon function completion and the program's exit successfully.

Heap memory

Heap memory refers to the memory allocated at run time when each instruction is performed. A heap is used to store global variables, which can be shared by all functions in the program, rather than the local variables defined within a function. Here, x = 23 is an example.

Number types in Python

Integers, floats, and complex numbers are all available as numeric types in Python. In this tutorial, we'll learn about integers because we'll be using them to show how variables work.

For simplicity's sake, an integer is a number that does not include a decimal point or fraction. They might be both positive and negative at the same time. For example, the numbers 1, 2, 3, 500, and 10000000.

The int class contains all integer variables. The class name can be found using the type () method, as illustrated in the example below.

Python's Rules for Variable Naming

  • When naming a variable, it should begin with a letter or an underscore (_). For example, Age, _age, and Age.
  • There are no special characters allowed in the variable name, except for the underscore (_). There are several examples of this: age_, _age
  • Variables are case-sensitive. Therefore, age and Age are two different things.
  • However, the variable name can have numbers at the end, but not at the start. Age1 is a good illustration of this.
  • Python keywords should not be used in the name of a variable. Reserved words are another term for keywords. True, False, None, and Def.

Techniques for naming a variable with numerous words.

  • Camel Case: As a visual aid, the second and following words are capitalized. For example, pythonTutorial
  • Pascal Case: Similar to Camel Case, except that the initial letter is capitalized instead of being lowercase. For example, PythonTutorial
  • Snake Case: Underscores divide each word. For example, python_tutorial

Variable Assignment

A variable refers to an item's specific name. Instead of having to declare or specify a variable like in other programming languages, Python simply uses the equals (=) sign to create a variable and assign a value.

As stated, "n is allocated the value of 300" in the example above. You can then use n in a statement or expression, and its actual value will be substituted for n.

Just like with a literal value, variables can be shown directly from the interpreter prompt in a REPL session, without the usage of print ().

In the future, if you use n again and alter its value, the new value will be used:

Chained assignment in Python allows the same value to be assigned to many variables at the same time:

The above-chained assignment gives the variables a, b, and c the value 300 at once.

Python's Variable Types

Python has two types of variables: global variables and local variables. To utilize the variable in other parts of your program or module, you need to declare it as a global one. It is common practice in Python to use local variables when creating new variables.

Using the following program, you can see how Python variables function by comparing the local and global variables.

  1. Using Python, let's create a global variable called "f" and assign it the value 101, which is printed in the output.
  2. f is a new local scoped variable declared by function f. When this variable is set to its default value, "I'm studying Python." is printed as an output. This Python declared variable is distinct from the global variable "f" specified before.
  3. A function call's local variable f is disposed of once the execution has completed. At line 12, the global variable f=101 is displayed when printing the value of "f" once more.

You can utilize a global variable in a function in Python if you include the global keyword in the variable definition.

  1. The "f" variable is global in scope and has been assigned a value of 101, which is printed in the output of the code.
  2. The variable f is declared to exist by using the keyword global. That which was previously defined as a globally applicable variable will be used here. When we print the value, it comes out to 101.
  3. Inside the function, we modified the value of "f." The new value of the variable "f" remains even after the function call has ended. Line 12 prints the value "changing global variable" when value of "f." is printed.

Variables are statically typed in many programming languages. A variable's data type is specified when it is created, and any value that is assigned to it must always be of the same type.

However, Python variables are exempt from this rule. It is possible in Python to give a variable a value of one type and then change it to another type later on:

In reality, what happens when you assign a value to a variable?

This is an important subject in many programming languages, but the answer in Python is a little different.

Since Python is a highly object-oriented language, every piece of data in a program is an object of some type or class. This will be brought up again and again in the course of these tutorials.

References to objects

Take a look at the following coding:

Translators are instructed to perform the following actions when provided with a statement print (300).

  • Creating and supplying the value 300 to an integer object
  • The console will show it.

As you can see, the built-in type () function creates an integer object.

An object can be referenced by a Python variable's symbolic name, which serves as a pointer or reference. After assigning a variable name to an object, you can use that name to refer to the object. However, the object itself still contains the data. For instance,

An integer object with the value of 300 is created and the variable n is assigned as an identifier.

n is a pointer to an integer object, and the following code confirms that:

Then consider the following assertion:

What happens if it is executed? A new object is not created. Since n points to the same item, m points to a new symbolic name or reference.

Next, you may try something like this:

Python now constructs a new integer object named m, which has a value of 400.

Finally, let's consider that the following statement is executed:

As a result, Python generates a string object named "foo" and uses that as a pointer in n.

The integer object 300 is no longer mentioned anywhere. There is no way to get in touch with it.

The lifespan of an item will be mentioned at various points in this series of tutorials. When an item is first created, at least one reference to it is made, which marks the beginning of its life. A reference to an object can be added or destroyed at any moment during its lifetime, as you saw in the example above. As long as there is at least one reference to the thing, it lives on.

Objects are no longer accessible when the number of references to them reaches zero. Its time had come to an end at that moment. The allocated RAM allocated to Python will eventually be reclaimed so that it can be utilized for something else. Garbage collection, as it's called in computer jargon, is a very simple way to manage your own memory.

Object identity

Every Python object is assigned a unique identifier number when it is created. No two objects will ever share an identifier, even if their lives overlap for a period of time. It is not possible to utilize the same identifier for an object after its reference count reaches zero and it is garbage collected.

A Python object's id can be obtained using the id () function, which is part of the standard library. Id () can be used to verify that two variables are actually pointing at one another:

Even after an assignment such as this, which results in the same number being returned for id(n), it is clear that these two numbers point to the same thing. As soon as m is reassigned to the value 400, they no longer point to the same item, but rather to different things, take into account the following:

M and n are both 30-valued integers in this example. The id(m) and id(n) are identical in this example, While running the program, the interpreter makes use of previously created objects for numbers in the [-5, 256] range. As a result, if you assign different integer values in this range to different variables, they will all refer to the same thing.

Delete a variable

Python variables can also be deleted by use of function del "variable name". Python's error "variable name is not defined" indicates that you've erased the variable in the following example of the language's delete variable function.

Variable type casting

Test the concatenation of several data types such as string and integer. The number "99" will be added to the word "Guru," for example, A Type Error will arise if the number is not expressed as a string when declaring variables in Python. This differs from Java, which does not require the number to be declared as a string.

You will obtain an undefined result if you run the following code.

a="Guru"

b = 99

print a+b

Use print(a+str(b)) to concatenate both a and b into a string.

what is type casting?

This is the process of changing one data type to another. Data type conversion is necessary in some scenarios. For instance, you may want to combine two numbers where one of the variables' existing values is an integer and the other is a string. Python typecasting is required before addition, as it must transform a string's data type to an integer.

Types of conversions in type casting

  • Explicit conversion

Type casting in Python can be done using a variety of functions.

  1. The INT () function is used to specify integer literals. A string literal is converted to an integer value.
  2. Use STR () to convert an integer to a string ().
  • Implicit conversion

Data types in Python are implicitly converted by the Python interpreter, which means that the user is not required to intervene in the process. See the examples below for a better understanding of the subject.

Conclusion

Congratulations! Your perseverance has paid off. The focus of this session was on Python variables, object references, and identity, as well as the naming conventions for Python identifiers and a brief discussion of integers. Let’s meet in our next tutorial as we discuss about Python data types and how they're put to use.

How to use Strings in Python?

Welcome to the fourth lesson of this python course. Our previous session taught us how to utilize the print function in python, so we have a firm grasp of the terminology and the functions themselves. In this lesson, we'll cover a few more Python terms, such as:

  • Strings
  • Operators
  • Input function

Also, we'll build a simple program to print out an imagined dog so that we may better grasp how these concepts are employed. So, let's get started now.

Why do we need to understand these terms?

Programming is a lot like building a structure out of blocks. Even with just a few types of children's toy blocks and some time and imagination, you can build anything. Because we'll be utilizing these phrases all the time in programming, it's critical that you know what they mean and how to use them.

What exactly are the strings?

An alphabet, word, or other character collection is referred to as a "string." As one of the most fundamental data structures, it serves as a framework for manipulating data. An in-built string class called "str" is available in Python. After they've been produced, strings are "immutable," which means that they can't be rewritten. Because of the immutability of strings, we must generate new ones each time we want to represent newly computed values.

Quotes are used to denote a string. There are a variety of ways to accomplish this:

  • Single quotation marks, as in the following example: For "double" quotations in your string, use "single" quotes."
  • Use double quotation marks. Using single quotations in your string is easy with double-quotes.

"Double quotes allow you to embed 'single' quotes in your string."

  • If you want to use triple quotes, you can do so in the following way: (""" """), (''' ''')

Triple quoted strings to make it possible to work with a set of multiple-line strings and include all of the whitespaces that accompany them.

The fact that a string cannot be changed results in an error if you try to do so. The adjustments require the creation of a new string.

Instead, use this method.

The built-in len() function can be used to determine the length of a string:

String slicing in python

Strings can be sliced and indexed since they are a sequence of characters. A string's indexing starts at 0 and is based on each character in the string.

The initial character in the string is C, which is located at position 0 of the index. The final syllable is a period, which is the string's sixteenth character. When you want to access characters in the opposite direction, you can use -1 as an index. when it's strung together, Chocolate and cookie are separated by a whitespace, which has its own index, 9 in this example. Slicing is a good way to verify this.

For the same reason as for other sequential data types, you can read and manipulate Python strings using their associated index numbers. It is possible to slice an object using its index values in Python to select a specific element or a subset of elements. You don't have to write a loop expression to identify or access specific substrings in a string. Slicing does this for you automatically.

Suppose you were trying to find the cookie substring in the following string. What's the best way to go about it?

Range slicing is used in these situations. The range slicing syntax is as follows:

Alternatively, you might use a negative stop index:

In this case, when you slice a sentence without giving an end index, you get characters from the first index to its last. In the same way, slicing a string without a starting index indicates that you begin at the beginning and end at the end.

Additionally, the stride parameter can be accepted by string-slicing as a third argument, which specifies the number of characters to advance once the initial one is picked from the string. In the default configuration, stride has a value of 1.

stringnu = "1020304050"

print (stringnu [0:-2:2])

Striding allows you to reverse a string, which is a really cool feature. With a stride of -1, you can begin at the end of the string and move forward one character at a time. With a value of -2, you can start at the end and move two characters at the same time.

String operations

String operations such as slicing and range slicing are frequent. As simple as adding, string concatenation is also available.

Concatenating a string with another data type, on the other hand, will fail.

You attempted to concatenate an integer value with a string, which is not permitted. Integer addition or string concatenation is not understood implicitly by the interpreter. However, give this a try:

The reason for this is that you used concatenation after you turned the integer into a string.

A string can be repeated using the * method.

wordsig = 'hip '

line1 = wordsig * 2 + 'hurray! '

print (line1 * 3)

To manipulate strings, Python comes with several built-in methods and utility functions. It is possible to use these built-in techniques to replace substrings, to put some words in a paragraph in capital letters, and to locate the position of a string within another text.

  • capitalizes the first character in the string returned by capitalize().
  • islower(): will return true/false when all characters in the string are lowercase/uppercase.
  • If a substring is passed to find(substring), it will be returned at the string's lowest index. When searching for substrings, you may optionally specify a start and end index for each location in the string that you want to search for. If the substring is not found, it returns -1.
  • count(substring) returns the number of times a substring appears in the string. The string's start and stop indexes are also programmable.
  • isspace() When the string has a whitespace character, the value is true. Otherwise, it is false. A space, a tab, and a new line are all whitespace characters. When working with real-world datasets, this can come in handy because the proper spacing may not be encoded properly during format conversion.
  • A function called lstrip() eliminates all leading whitespace from a string. It's a feature that comes in handy when dealing with real-world datasets.
  • If the string contains just digits, isdigit() returns true; otherwise, it returns false.
  • All instances of the substring are replaced with new using replace (sub-strings, new). A third argument, max, can be specified to replace as many of the substring occurrences as the value of max allows in the string. This is not an in-place replacement, so the immutable attribute of the string remains intact.
  • split(delimiter="") provides a list of substrings based on the specified delimiter (or a space if none is provided).

Python string formatting

Multiple string formatting options are available in Python. To better understand these formatting strings, let`s dive right in.

% Format

Python has a built-in modulo percent operation. The interpolation operator is the name given to it. There is a percent followed by the data type that must be prepared or transformed. This operation then replaces the word "percent datatype" with one or more components of that type:

Percent d is used for integers, whereas percent s is used for strings; you've seen both. Octal values can be converted to octal equivalents with this type of conversion, as can Hexadecimal values with this type, and Floating-Point Decimal Format with this type.

Python string formatter class

One of the built-in string classes is the formatter class. The format () method can be used to perform sophisticated variable substitutions and value formatting. Rewriting public methods such as format () and vformat () allows you to build your own string formatting techniques (). There are a number of methods that are designed to be replaced by subclasses, such as parse (), get field, get value, check unused arguments, format field, and convert field ().

Template strings

Templates allow substitutions based on dollars rather than percentages. A major reason for template syntax creation in Python Version 2.4 was that, despite the strength of percent string formatting, errors are easy to make, because the forms that follow '%'are extremely restrictive. This is a common blunder when it comes to percent formatting: forgetting to include the e in percent (variable).

substitution () and safe_substitute() are two methods specified within templates (). You can use them in the following ways:

Safe substitution () is an advantage to employing a template, in addition to other advantages.

String literal formatting

In Python 3, this is yet another way to format strings. A prefixed 'f' or 'F' string literal is known as a formatted string literal or f-string. Within curly brackets, you may include identifiers that will be utilized in your string.

What's the point of adding another string formatting option? well, this is because practicality and simplicity are appealing.

To demonstrate why f-strings are the best way to format strings in Python, check out the examples below.

Please note that the preceding code is only compatible with Python 3.6 and above. With f-strings, Python expressions can be used inside curly braces, which is a significant benefit of using them.

What's the point of having so many string formatting options?

Syntax is the most important consideration here. For the most part, it boils down to the trade-off between simplicity and the amount of verbosity you're willing to sacrifice. People with a C programming background will find it easy to use the percent sign to format strings, for example. Using the format () function can be more verbose, but it provides a wider range of options.

Input function with strings

While your application is running, you can utilize input routines to get data from the user. A key benefit of this approach is that it does not rely on preexisting values or file content to function. The syntax for the input function is as follows.

input([prompt])

Input functions will cause our application to pause. After the user inserts the text into the Python shell or command line, the application resumes.

input(message)

In order to prompt the user for text, you'll need to provide a message. It's important that a user understands what they need to do by reading this message. As a result, a user may wonder why the software isn't progressing. For example,

input ("Enter email address: ")

print ("Confirm it is your email address:")

In order to request an email address from a user, we've implemented the input () method. Messages in brackets are displayed on the same line where a user is expected to enter text in the command line.

Note that as soon as a user inputs data into the input () function, it is automatically converted to a string.

How to draw an imaginary dog.

Using the fundamentals of strings that we've learned in this lesson; we'll construct a simple program that prints out an image of a dog.

Let's open up our favorite coding editor, Atom, and get started. Before looking at the solution, I advise you to give it a shot on your own.

  • Step 1: In the code editor where the hello.py file is loaded, write the print function () to print out the upper body of our dog image.
  • Step 2: Insert double quotes or single quotes inside the print function. This shows the output will be a string.
  • Step 3: Write "o" in the speech marks.
  • Step 4: Close the speech marks and reopen the speech marks. This is because we want to add another string to the same print function. Add hyphens to represent the neck and upper body.
  • Step 5: Add a plus sign between the strings to concatenate the strings.
  • Step 6: Create another function to print the legs. Same way we did the upper body, we will now print the legs. Inside this function, we create a string and write four slashes to represent legs. Now our dog program is complete, save the file and run the code using one of the methods we learnt in the previous tutorial. The results should be:

Conclusion

Congratulations! You've made it this far. You have learned about string slicing, what strings are, and explored a variety of string-related processes. Many approaches to formatting strings have also been discussed. But don't forget that practice is the key to mastering any skill! I'll see you in the next tutorial.

Writing First Code in Python (Hello World)

The "Hello, World!" program is a computer programming classic that has stood the test of time. For beginners, "Hello, World!" is a simple and full first program that introduces the basic syntax of programming languages and can be used to evaluate systems and programming environments.

The more you learn about Python, the more you may use it for your own purposes. Data analyst, application developer, or the ability to automate your work processes are all examples of jobs that can be automated.

This Python 3 tutorial will show you how to create a simple "Hello, World" program. Python's basic syntax and components include the following:

  • Variable-types
  • Data structures
  • Math operators
  • loops
  • Different function calls
  • Input and output functions
  • Interfaces and classes
  • APIs memorize the syntax.

Python`s IDE

An IDE (Integrated Development Environment) is a software development tool. Integrated development environments (IDEs) include a variety of software development-specific tools. Examples of these instruments include:

  • Build, execution, and debugging tools
  • An editor intended to handle code (such as syntax highlighting)
  • The use of some type of version control

There are many distinct programming languages supported by IDEs, as well as a wide range of additional functionality. Because of this, they can be very huge and take a long time to download and install. Using them correctly may necessitate additional training.

Definition of function?

A function is a piece of code that serves a single purpose and can be reused multiple times. Functions provide for greater modularity and code reuse in your program. Functions have the benefit of being well-known by a variety of names. Functions, methods, subroutines, procedures, etc. are all referred to in different ways by different programming languages. Think about what we'll be talking about later in this session if you come across any of these terms.

Print function – What is it?

Since you all learned Python by printing Hello, World! you might think that there is nothing new to learn about the Python Print function. As with any language, learning to use the Print function in Python or any other is like taking your first baby steps into a new world of programming. When studying a programming language, it's easy to get caught up in the more advanced concepts and lose sight of the simplicity and usefulness of basic functions.

Today's tutorial is all about Python's Print function; you'll learn about one of the most underappreciated functions.

For example, in Python3, parenthesis is required or else you'll get a syntax error as illustrated in the image below.

In Python3, print () is not a statement but a function, as demonstrated by the above output. First things first, let's see what the print () function returns.

Built-in functions and methods are returned by this method, which indicates that it is a Python function.

A new line or vertical space between the two outputs can be added by simply using the print () function without sending any arguments in.

The command Palette

The Command Palette, which is possibly Atom's most essential command, is shown to us on that welcome page. The command palette will appear if you press Ctrl+Shift+P while in an editor pane.

Writing the first Program

Packages from the Atom community are available to help you assemble and run programs. We'll be utilizing "script" to run our application in this example.

go to file>settings>install

Install script by searching for it in the search bar. It should appear under "Packages" in the Settings menu after installation. Please be aware that script does not support human input. The "apm" package manager can be used to install packages on Mac OS or Linux.

Creating our first project

Go to File > Add Project Folder in atom and pick a directory to serve as the project's root directory.

In the folder, right-click the folder and select "New File," type "hello."py," and click "OK."

Now that you've made your adjustments, you can open the new file in the editor by clicking on it and then saving it.

Then, in the Print dialog box, type "hello, world!"

To execute the script, use CTRL+SHIFT+B. You may also use View > Toggle Command Palette and type Script: Run to execute a script.

You can also use your terminal to run the python file by navigating to the file directory containing your hello.py file and running this command

python hello.py

How to edit and save files in atom

File editing is rather simple. You can use your mouse and keyboard to navigate and edit the content of the page. A separate editing mode or key commands are not provided. Take a look at the list of Atom packages if you prefer editors that have modes or more advanced key commands. Many programs are available that mimic popular design elements.

You may save a file by selecting File > Save from the menu bar or by pressing Ctrl+S. There are two ways to save the current material in your editor: by selecting File > Save As or using Ctrl+Shift+S. Finally, you can save all open files in Atom by selecting File > Save All.

How to open directories in atom

The majority of your time will be spent working on projects with numerous files, not just single files. Take advantage of the File > Open Folder menu option and select an appropriate folder from the drop-down menu. File > Add Project Folder or hitting Ctrl+Shift+A can also be used to add other directories to your current Atom window.

The command line utility, atom, allows you to open unlimited number of directories by supplying their paths to it. The command atom./hopes./dreams, for example, can be used to simultaneously open the hopes and dreams directories.

An automated Tree View will be displayed on the side of Atom if one or more directories are open.

When you use the Tree View, it's a breeze to see the whole file and directory structure of your project. You can open, rename, and delete files, as well as create new ones, using this window.

In order to toggle between concealing and showing it, use Ctrl+, use the tree-view: toggle command from the Menu Bar, or press Alt+ to bring focus to it. The A, M, and Delete keys can be used to add, move, or remove files and directories in the Tree view. It's also possible to access these choices by right-clicking on a file or folder in the Tree view, as well as copying or pasting its path into your clipboard.

How is python executed?

Unlike functional programming languages that used a single long list of instructions, Python uses code modules that may be switched out. Cpython is the default Python implementation. It is the most often used Python implementation.

Python does not translate its code into a form that hardware can understand, known as machine code. As a result, it turns it into byte code. Python does have a compiler, but it doesn't compile to a machine language. CPUs are unable to decode the byte code (.pyc or.pyo). We'll run the bytes through Python's virtual machine interpreter.

To convert a script into an executable, the Python source code follows these steps:

First, the python compiler reads a python source code or instruction from the command line. It ensures proper formatting of the instruction by inspecting the grammar of each line. The translation is immediately interrupted if an error is found, and an error message is presented.

Assuming there are no errors and the Python source code or instructions are properly formatted, the compiler proceeds to translate them into a form known as "Byte code," which is an intermediate language.

The Python interpreter is invoked by executing bytes of code in the Python Virtual Machine (PVM). PVM is a Python virtual machine (PVM) that turns bytecode into machine code. If there is a problem with the interpretation, the conversion will be interrupted and an error notice will be displayed.

Conclusion

Congratulations for completing your first program. Beginners who want to learn Python can benefit greatly from this guide. To get the most out of this lesson, you may want to play around with the Print function a little more and discover more features that were not covered.

How to Install Python Software?

The first step to becoming a Python coder is to install or update Python on your computer. Python can be installed in a variety of ways, including through the official Python.org distribution, a software package manager, the IoT (Internet of Things) and scientific computing, just to name a few.

In this article, we'll be using official Python distributions, which are often the best option for beginners.

What will you learn from this?

  • How to check if you have the right Python release installed on your computer before proceeding.
  • Installation of Python3 on Windows pc and Linux machine.
  • How to use Python on the web with the help of online interpreters.

INSTALLING REQUIRED PYTHON ENVIRONMENTS

Installing the most recent versions of Python and the packages you'll need to experiment with is a good place to start when learning Python. To create an environment, you need a certain Python version, as well as the necessary packages. Consequently, separate environments are required if you wish to create or utilize apps that have varied Python or package version needs.

Python environment - what is it?

Python's virtual environment is a valuable tool for managing dependencies and separating projects. It's possible to install Python site packages (third-party libraries) in a specific project directory rather than the entire system Python.

Which are the package and environment managers Available?

  • Pip: With a virtual environment, you may use pip, a Python package manager, which stands for "Pip Installs Packages”. This is a tool for creating isolated environments.
  • Conda: Conda is an open-source package management and environment management system that operates on Windows, Mac OS X, and Linux. Installing, running, and updating packages and their dependencies is a breeze thanks to Conda. You can quickly build, save, load and swap environments on your own computer using Conda. Software for any language may be packaged and distributed using this tool.

In windows

On Windows, there are three installation options:

  • Using Microsoft store.
  • Using the available complete installer.
  • Windows subsystem for Linux implementation.

You'll learn how to check the current release of Python installed on your Windows machine in this section. You'll also discover which of the three installation options is best for you.

Installation

Step 1: Install Python based on your choice of version.

Python 2 and Python 3 are available, each with its syntax and way of doing things.

Here we are going to download python 3 for this course.

Step 2: Download an executable installation file for Python.

Open on your browser and head to the python.org website. On this page click on downloads. Here you can find the latest version of python. Choose the version you require and click Download. For this example, we go with Python 3.10.2.

When you select download, a list of available executable installers with varied operating system requirements will appear. Select the installer that best suits your system's operating system and download it. Let's say we go with the Windows installer (64 bits).

Step 3: Run the Installer Script

If the Python 3.10.2 Windows 64-bit installation was downloaded, run the installation program by double clicking it. Make sure both checkboxes at the bottom are selected before clicking Install New.

Now installation process begins when you click the Install Now button. Wait for a few minutes for installation process to finish.

you should see the screen below if the installation is complete. Now you have python installed in your computer.

Step 4: On Windows, check to see if Python is installed.

To see if Python has been installed successfully on your system. Observe the instructions.

  • Go to the windows search box on the bottom left corner of your display and write "cmd" and click enter. A command prompt window in black will open and this is where you write your commands for execution.
  • Enter 'python --version' into the prompt and press enter.
  • If python is successfully installed on your windows, the version of python that you have installed will be displayed.

In Linux

When installing python in Linux distros, there are two ways involved:

  • Using the Linux os`s package manager: On most Linux distributions, this is the most popular installation technique. It entails using the command line to execute a command.
  • Or building python from source code: Using a package manager is easier than using this method. It requires performing a set of instructions from the command line as well as verifying that you have all of the essential dependencies to compile the Python source code.

You'll find out how to know if your Linux computer has a current version of Python in this section and which of the two installation techniques should you choose?

How to check the python version?

Many Linux versions include Python, but it is unlikely to be the most recent update, and it may even be Python 2 rather than Python 3. Try the following command in a terminal window:

$ python –version

If you have Python installed on your computer, this command should return a version number.

If your current Python version isn't the most recent Python 3 version available, you'll want to upgrade.

Installation

Step 1: Installing Python requires first downloading and installing the necessary development packages

A new version of Debian has been released; therefore, we need to update our old version to the new one.

Open the terminal in your Linux machine. Then run “apt update” in your Linux terminal to update the system before you begin installing python. Then, run "apt-get upgrade" in your terminal to upgrade the system.

then, run " apt install build-essential zlib1g-dev \libncurses5-dev libgdbm-dev libnss3-dev \libssl-dev libreadline-dev libffi-dev curl" to install the build essentials.

Step 2: Download the most recent version

Navigate to your browser in python.org and click on downloads. You will see the latest version of python with a download button, but this is the windows version, instead, navigate to the Linux/UNIX link below it to download the Linux version.

Download the most recent version of Python3 from the official Python website.

You will receive an archive file ("tarball") containing Python's source code when the download is complete.

Step 3: Unzip the tarball folder to a convenient location.

A tar.gz file is a collection of compressed files that may be downloaded in order to conserve space and bandwidth. The tarball, another name for the.tar file, is a container for other files that may be carried about on a flash drive. Because of the extension, gzip is the most extensively used compression application in use. These files can be unzipped in the same way as a standard zipped file:

Run “tar –xvzf a.tar.gz” in the terminal to unzip.

Step 4: The downloaded script must be configured.

Type cd Python-3.*. /configure in your terminal once you've unzipped the Python package and press enter.

Step 5: Begin the build procedure

Use this command below if you need to install an updated version alongside the old version in case you don`t want to delete the old one:

$ sudo make install

Step 6: Verify that the installation is working properly.

Open your terminal and type command below and click enter.

python --version

Python3 has been successfully installed once the output says Python 3.x.

Conclusion

Congratulations! For your system, now you have access to the most recent update of Python. Your Python adventure is just getting started.

Introduction to Python

Greetings! I sincerely hope everything is going well for you all. In this course, we are going to learn step-by-step how to program in Python. The course covers all you need to know about the Python language, from installation to advanced topics. In addition, we'll talk about Python career jobs and do a few projects to strengthen your skills. According to my research, Python is among the top programming languages in use today. (I mean, no offense). Since I am also a Python programmer, I may sound a little prejudiced, but I can certainly declare that I am a huge fan of the language. This tutorial series is meant for absolute beginners with no prior knowledge of python programming, it is also of great help for experienced python programmers looking to brush up on their knowledge. Anyway, let’s start by answering a few questions:

What is Python?

Python is a high-level scripting language for system administration, text processing, and web tasks. Its core language is short and easy to learn, while modules can be added to do a virtually infinite number of functions. It is a genuine object-oriented programming language that runs on a wide range of systems. Python was born out of a desire to build a computer language that was both easy to learn for beginners and powerful enough for advanced users. Python's small, crisp syntax reflects this background, as does the thoroughness with which notions are implemented, without removing the flexibility to program in a more traditional approach. As a result, Python is a fantastic first programming language that provides all of the power and advanced capabilities that users will require in the future. Most experienced programmers claim that Python has restored the fun they normally had during programming, suggesting that van Rossum's inspiration is adequately conveyed in the language itself.

Why Python?

Even those, who aren't computer programmers, have found themselves using it, to perform mundane tasks like raising money because of its relatively low learning curve.

Readability and maintainability

Building a system that is easy to maintain and update requires careful consideration of the quality of the program code. Because of the language's syntactic rules, you may express yourself in Python without writing any more code. With Python, you may use English phrases instead of punctuation, which makes it easier to understand than other computer languages. You don't have to write any more code when using Python to create custom apps. If the code is well-structured, it will make it easier to keep and improve the product.

Compatibility

Code written in this programming language may be executed on a variety of systems and tools thanks to interpreters for this language. When it comes to creating dynamic web pages, Python is also an interpreted programming language. '" There's no need to recompile the application to operate on many operating systems. As a result, changing the code doesn't require recompilation. You don't need to recompile the updated application code to see how the changes affect it. Code updates may be made more rapidly and without increasing development time by using this feature.

Robust Standard Library

Python outweighs other languages because of its vast and robust standard library. You can select from a wide choice of modules in the standard library to meet your specific requirements. If you're building web apps, dealing with operating system interfaces, or working with internet protocols, you can make use of specific packages. The documentation for the Python Standard Library can also help you learn about different modules.

A lot of customizable tools

As an open-source coding language, Python can lower software development costs significantly. Some of the Python modules, libraries, and development tools, all of which are open-source and free, may help you get things done faster. Open-source Python development tools are also available, so you may tailor your project to your exact needs. Flask, Pyramid, and Cherrypy are some of the best Python frameworks for web development.

Make Complex Software Development Easier

Python may be used to build both desktop and web-based applications. Python may also be used to create complex scientific and numerical applications. Easy-to-use Python capabilities make it possible to perform data analysis and visualizations. Data analysis tools can be used to construct custom big data solutions without requiring additional effort or time. You may make your collected data more visually attractive and useful by utilizing its data visualization tools and APIs. Many Python programmers also use Python for AI and NLP jobs.

Python for Cloud Computing

This programming language is used for cloud computing, web and software development, as well as task automation and data analysis.

Since everything is stored in the cloud, you may access it at any time and from anywhere. Web-based software may be used without any installation, an application can be hosted online, and a remote file storage and database system built using cloud computing can be set up. For that purpose, we have different modules like raspberry pi and ESP32 or ESP8266 boards which use python.

The ESP32 is the latest sibling of the ESP8266, which is a microcontroller. For a nominal additional fee, it boosts the device's power and capabilities while also including Bluetooth. The M5 Stack is one of the greatest iterations of these boards. Piezo speakers, batteries, a card reader, and a color screen are all included in this device.

Is python supported?

Python has a big and active community of developers that respond to concerns and build new features at a pace that many commercial software developers would consider exceptional (if not downright shocking). A source-control system is used by Python programmers to coordinate their work remotely. The PEP (Python Enhancement Proposal) procedure must be followed and must be accompanied by improvements to Python's sophisticated regression testing infrastructure for any changes. A far cry from the early days of Python, when an email to the author would suffice, altering Python nowadays is about as complicated as upgrading commercial software. This is a good thing given Python's present vast user base.

What are the technical strengths of python?

  • Python is object-Oriented. Python was designed from the bottom up to be an object-oriented language. Polymorphism, operator overloading, and multiple inheritances are all supported by its class model, but Python's straightforward syntax and type make OOP a breeze to implement. Even if you don't grasp the terminology, you'll find it far easier to learn with Python than with any other OOP language. Later in the course, we'll get to understand this.
  • The language is free to use. Python may be used and distributed without cost. You may get the full Python system's source code for free from the Internet, just like you can with other open-source software like TCL, Perl, Linux, and Apache. If you want to use it in your products, you can do so without fear of violating copyright laws. Python's source code can even be sold if you want to.
  • Python is portable. In addition to being written in ANSI C (American National Standards Institute), Python's standard implementation operates on nearly every major operating system now in use. Python, for example, can run on everything from a PDA to a supercomputer today.
  • Python is easy to use. Python programs may be run by just typing in the code and pressing enter. Unlike in languages like C or C++, there are no intermediary phases of compilation and linking. In many circumstances, you may see the consequence of a program modification as quickly as you type it in Python, which provides for an engaging programming experience and a speedy turnaround following program changes.
  • It is mixable. There are several ways in which Python applications can be "glued" together with other languages. Python's C API, for example, allows C applications to be called by Python programs. As a result, you can tailor the Python system to your own needs, and you can run Python applications in any environment or system.

What are the weaknesses of python?

  • Slow Speed. It is a combination of interpreted and dynamically-typed languages. The execution of line by line is generally sluggish. This slowness may be attributed to Python's dynamic nature, which is also to blame for the language's inability to execute code quickly. Since performance isn't a high priority, Python isn't used in projects.
  • It is not memory efficient. Because of this, Python must make some compromises to keep things simple for programmers. When programming with Python, you'll need a lot of RAM. This could be a problem when you're writing programs, especially if memory efficiency is important.
  • It is weak in mobile computing. When it comes to server-side programming, Python is the most often used language. Python isn't used in client-side or mobile apps for the reasons listed below. When compared to other languages, Python is a poor memory manager and a slow processor.
  • Database access. Python is a breeze to learn and use. Despite this, when we're using the database, it falls behind. While JDBC and ODBC are well-known technologies, Python's database access layer remains basic. Because of this, Python isn't used by big businesses that need to work with complicated old data smoothly.
  • Errors in the code. At any point in time, the data type of a Python variable can change. If an integer number is saved in a variable that is later transformed to a string, there is a risk of runtime issues. The upshot is that Python programmers must properly test their software.

What kinds of jobs are there in Python?

  1. Python Developer. For someone who knows Python, being a Python developer is the quickest path to employment. One can work by using Python to
  • Create web applications
  • Enhance the data algorithms
  • Analyze and solve data-related issues
  • Adopting measures to safeguard personal and financial information
  • Useful, testable, and efficient code writing
  1. Product manager. Product managers are in charge of discovering new user features, identifying market gaps, and making a case for why specific products should be developed. Many firms are increasingly looking for product managers who are fluent in Python because of the importance of data in their job.
  2. Data analyst. When it comes to sorting through large amounts of data, utilizing Python modules like SciPy and Pandas has proven to be a popular method.
  3. Someone has to teach Python, right? Someone who knows Python may immediately think of teaching computer science, but it is far from the only teaching opportunity open to those with this skill set. Python tutors are in high demand at nearly every institution, coding boot camp, and online coaching platform.

How much do jobs as a Python programmer pay?

Now, let's have a look at How to install Python Environment:

HOW TO INSTALL PYTHON ENVIRONMENT

In windows

Python is installed on Windows in a few simple procedures.

Step 1: Install Python based on your choice of version.

Python 2 and Python 3 are available, each with its syntax and way of doing things.

Here we are going to download python 3 for this course.

Step 2: Download an executable installation file for Python.

Use browser to Navigate to the Download for Windows area of the official Python website.

Choose the version you require and click Download. For example, I go with Python 3.9.1.

When you select download, a list of available executable installers with varied operating system requirements will appear. Select the installer that best suits your system's operating system and download it. Let's say we go with the Windows installer (64 bits).

Step 3: Run the Installer Script

The Python 3.9.1 Windows 64-bit installation was downloaded.

Run the installation program. Make sure both checkboxes at the bottom are selected before clicking Install New.

Now installation process begins when you click the Install Now button.

A few minutes after starting the installation process, you should see the screen below.

Step 4: On Windows, check to see if Python is installed.

To see if Python has been installed successfully on your system. Observe the instructions.

  • Go to the command prompt and type "cmd."
  • Enter 'python' into the prompt.
  • If python is successfully installed on your windows, the version of python that you have installed will be displayed.

In Linux

Step 1: Installing Python requires first downloading and installing the necessary development packages.

A new version of Debian has been released.

Run "apt-get upgrade" in your terminal.

then, "libssl-dev libreadline-dev libffi-dev curl"

Step 2: Download the most recent version.

Python has several versions that are available on their website.

Download the most recent version of Python3 from the official Python website. You will receive a.tar.xz archive file (a "py") containing Python's source code when the download is complete.

Step 3: Unzip the py folder to a convenient location.

To extract the file, either use an extractor program or the Linux tar command.

Step 4: The downloaded script must be configured.

Type cd Python-3.*. /configure in your terminal once you've unzipped the Python package and run it

Step 5: Begin the build procedure

Use this command below if you want to install the new version alongside the old version in case you don`t want to delete it:

$ sudo make install

Step 6: Verify that the installation is working properly.

To test it, type the following command into your terminal:

python3 --version

Python 3 has been successfully installed once the output says Python 3.x.

Conclusion

Congratulations! You've just completed the basics of Python, now you know its strengths and where it falls short, as well as what kinds of employment you may expect to be able to land as a python programmer. Let’s meet in the next chapter as we begin coding.

How to use IF Else in Python

Hello friends, I hope you all are doing great. In today's tutorial, I am going to show you How to use IF Else in Python. It's our 5th tutorial in python series. In our previous lectures, we have covered the detailed Introduction to Python and then we have also discussed Data Types in Python & How to use Strings in Python. So, now it's time to move on a little further. In today's tutorial, we will cover If else statement in python and its not that difficult to understand but quite an essential one as its use a lot in programming projects. So, let's get started with How to use IF Else Statement in Python:

How to use IF Else Statement in Python

  • IF Else Statement in python takes a Boolean Test Expression as an input, if this Boolean expression returns TRUE then code in IF body will get executed and if it returns FALSE, then code in ELSE body will be executed.
  • You can understand it better by looking at its Flow Chart in right figure.
  • Here's the syntax of IF Else statement in python:
if number == 10: print(number) else: print('Number is not equal to 10"
  • We use if, in our daily life, it is part of our conversation, most of the time.
  • For example, I say, If I win a lottery then I will go to a world tour! If I clear the test then I will throw a party.
  • Here's another example, that if you are working late hours let say, overtime duty then you will get extra money, else you will not get the extra money.
Let's work with an example:
  • Suppose, we have a food chain and our customer has a voucher for it.
  • He has a voucher number (which is a code) written on it, by showing it, he can get a discount or he can get a free meal.
  • If he is providing a correct secret code, then he will get a free meal offer. Otherwise, he will not be able to avail any offer.
  • So, let's design this simple code using If Else statement:

Offer = 500 (This is, by default, price of a meal)

  • We will take the input from the user.

voucher_number = input("please enter your voucher number: ")

  • Whatever the number he will enter, it will get stored in that "voucher_number".
  • Now let's check if the code, that he has entered is correct or not.
  • We will need to use the IF statement here and first let's add this condition:

if voucher_number=="9753":

  • If the voucher number is matching with the company generated number, then the offer will be:

offer -=300

  • If the code is correct then deduct the amount as a discount.
  • Then print("congratulations, you have got a discount")
  • Then print("your remaining offer has " + str(offer))
  • Run the program
  • See the image, it says to enter the voucher number in the output window:
Suppose I put the wrong code. It will exit the program. Now what error he will face, if he put the wrong Voucher number, Let’s see what will be the next task.
  • We will use else statement for this, if the condition is not correct.
  • I have simply printed the message in else body, as shown in below figure:

Relational Operators in Python

As we are discussing IF Else statement, so we should also have a look at relational operators in python:
  • Relational Operators are used to find a relation between two variables or data packets.
  • We use relational operators in test expressions of IF Else statements.
  • We have five types of Relational Operators i.e.
    • Greater than >
    • Less than <
    • Greater than equals to >=
    • Less than equals to <=
    • Equals to ==
  • Let's understand them with an example. Now I have to check which number is greater so I will write it as:
if first_number > second_number:          print(" First number is greater than second number.") else:        print(“second number is greater than first number.") So, that was all about How to use IF Else statement in Python. If you have any questions, ask in comments. In the next, lecture, we will have a look at How to design a simple calculator in python. Till then take care & have fun !!! :)

How to use Arithmetic Operators in Python

Hello friends, I hope you all are ding great. In today's tutorial, I am going to show you How to use Arithmetic Operators in Python. It's our fourth tutorial in Python series. Arithmetic operators are required in mathematical problem solving. We will first have a look at the arithmetic operators and after that, we also discuss different builtin arithmetic functions in Python Math module. So, let's get started:

Arithmetic Operators in Python

  • Arithmetic operators ( +, -, *, /, ^ etc. ) are used to perform simple arithmetic operations in python.
  • So, let's open up your PyCharm and perform a simple task using these operators, as shown in below figure:
  • I used a single star for multiplication and a double star for the square power.
  • It is showing the results of the operations, which it is performing respectively.
Now let's design a simple calculator using these arithmetic operators but before that let's have a look at How to take input from user in python.

Getting Input from users in Python

  • If we want to work dynamically, we will learn how we get values from users.
  • It quite simple in python, you will just need to use an input method here.
  • It will take input from the user and store it in the assigned variable.
  • If you want to take the full name, age, and qualification of the player, you will write it as shown in the image:

Now I will talk about type conversion and we will make a simple program that will calculate the salary of an employee so that we can learn to perform basic calculations: Type conversion in Python In this part, I will tell you, what is Type Conversion in Python? And why it is required? Let's follow the step.
  • Suppose we want to count the salary of an employee. See the steps in the image.
  • Here I put int. before the fourth string, which is basic pay, but I have put the bonus in the whole numbers and it will be unable to do the concatenation because it is allowing it as a string. So, I typed the data and run it, see the results.

  • You can also use the second method as you can put int. where you are performing calculations, as shown in the image.
  • You can convert it by using three major data types i.e. int, float, string.

Simple Calculator in Python

Now we will design a simple calculator in which the user will enter 1st & 2nd number and our code will perform these operations with those operators like addition, subtraction, division, and multiplications. I typed the following strings below:
  • first_number = float(input("Enter first number : "))
  • second_number = float(input("Enter second number : "))
  • print("All Arithmetic Operations are as under.")
  • print(first_number + second_number)
  • print(first_number - second_number)
  • print(first_number * second_number)
  • print(first_number / second_number)
  • print(first_number ** second_number)
  • I converted the type of first and second strings.
  • Run the program
  • You can see in the printed screen all the arithmetic operations are performed respectively.
  • All the values are in floating points because we converted it into the float.
  • You can also convert it in integer and check it.
  • I wrote 9 and 5 and enter it, results are shown in above figure.

Operator Precedence in Python

Let's suppose, we have a variable here.
  • Profit = 15 + 30 * 25
  • Now let's print it using: print(profit)
  • Run the program.
  • The answer will be 765 in the output window.
Python follows the standard order of precedence. First, it will perform multiplication and then it will perform the addition. However, we can change the order using parenthesis.
  • Suppose, we want to operate the addition method first.
  • So, I will place parenthesis before and after both terms.
  • Then it will perform the addition method first then multiplication.
  • I will write it as:

profit = (15 + 30) * 25

  • Run the program and answer will be 1125.
Now I will expand the equation and will do subtraction with it, let’s see what happens.

profit = (15 + 30) * 25 - 10

  • Run the program and answer will be 1115.
  • If we add parenthesis to it as:

profit = (15 + 30) * (25 - 10)

  • Run the program and we will get 675.
Numbers and Importing Math’s Function in Python In this part of the lecture, I will discuss predefined functions about numbers in Python and I will also show you, how to import math modules for the advanced predefined function and methods, predefined for numbers. So let's get started. round()
  • Suppose we have a variable as, number = 3.7.
  • I want easily round it using:

print(round(number))

  • Run the program and it will round the figure to 4.
abs()
  • Suppose I have negative value -8 and I want to find the absolute value of it.
  • I will use abs() and it It will return 8, as shown in below figure:
min()
  • If I want to find the minimum value among the two numbers. I will write it as:

 print(min(9, 4.5)

  • It will return the minimum value as, 4.5.
max()
  • You can do the exact opposite of min, if you want to find out the maximum value among the two numbers.

print(max(9, 4.5)

pow()
  • If I want to calculate the multiples of itself i.e. square, cube etc. then I will write it as:

print(pow(5, 3)

  • The first number will be base and the second one will be the power.
  • Run the program & it will show the answer, 125.

Import a Math Module in Python

Now let's have a look at How to import a math module in python code:
  • Python Math library has a lot of builtin functions, which we can easily import by writing this statement at the top of our code.

from Math import *

  • By writing this statement we are simply saying that get access to all the functions of Math Library.
Now, let's have a look at few of its functions: sqrt()
  • Suppose I want to take the square root of number = 72
  • I write it as

print (sqrt(number))

  • Run the program and it will return as 8.4 something, as shown in below figure:
Here's the complete list of functions in Python Math Module:
List of Functions in Python Math Module
Function Description
ceil(x) It returns the previous integer value.
copysign(x, y) It will assign sign of y to x.
fabs(x) It returns the absolute value.
factorial(x) It returns the factorial value.
floor(x) It returns the next integer value.
fmod(x, y) It divides x by y and returns the remainder.
frexp(x) It returns the mantissa and exponent as pair value.
fsum(iterable) It returns an accurate floating point sum of values in the iterable
isfinite(x) It returns TRUE, if the number is finite i.e. neither infinite nor NaN.
isinf(x) It returns TRUE, if the number is infinite.
isnan(x) It returns TRUE, if the number is NAN.
ldexp(x, i) It returns x * (2**i).
modf(x) It returns the fractional and integer values.
trunc(x) It returns the truncated integer value.
exp(x) It returns e**x
expm1(x) It returns e**x - 1
log(x[, base]) It returns the logarithmic value to the base e.
log1p(x) It returns the natural logarithmic value of 1+x.
log2(x) It returns the base-2 logarithmic value.
log10(x) It returns the base-10 logarithmic value.
pow(x, y) It returns x raised to the power y.
sqrt(x) It returns the square root of x.
acos(x) It returns the arc cosine of x.
asin(x) Returns the arc sine of x.
atan(x) Returns the arc tangent of x.
atan2(y, x) Returns atan(y / x)
cos(x) Returns the cosine of x
hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
sin(x) Returns the sine of x
tan(x) Returns the tangent of x
degrees(x) Converts angle x from radians to degrees
radians(x) Converts angle x from degrees to radians
acosh(x) Returns the inverse hyperbolic cosine of x
asinh(x) Returns the inverse hyperbolic sine of x
atanh(x) Returns the inverse hyperbolic tangent of x
cosh(x) Returns the hyperbolic cosine of x
sinh(x) Returns the hyperbolic cosine of x
tanh(x) Returns the hyperbolic tangent of x
erf(x) Returns the error function at x
erfc(x) Returns the complementary error function at x
gamma(x) Returns the Gamma function at x
lgamma(x) Returns the natural logarithm of the absolute value of the Gamma function at x
pi Mathematical constant, the ratio of circumference of a circle to it's diameter (3.14159...)
e mathematical constant e (2.71828...)
So that was all about arithmetic operators in Python. I hope now you got the clear idea of how powerful python is. So, that was all for today. In the next lecture, we will have a look at How to create IF Loop in Python. Till then take care and have fun !!! :)

How to use String in Python

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to use String in Python. It's our 3rd tutorial in Python series. We have discussed strings in our previous lecture How to use Data Types in Python. String is a most commonly used data type in python that's why I have created a separate lecture on it. Python has many built-in string operations, which we will discuss today in detail. So, let's get started with String in Python:

How to use String in Python

  • String Data Type is used to store or collect one or more characters or sequence of characters, we can place any alphanumerical or special character in a string.
  • Let's create a string in python, it has a simple syntax, as shown below:

first_var = "Hello World"

  • There are two sorts of strings, we can use in python:
    • Single Line.
    • Multiple Lines.
  • The above-given example is for a single line, like if you want to write an email or product name, etc.
Multiple Lines String in Python
  • If you want to write an essay, story, report etc. then you will need to use Multiple Lines string, which is created by placing triple quote around the data, as shown in below figure:
  • As you can see in above figure, we have written multiple lines in welcome string.

Strings Operators

  • If you are using an apostrophe, you will need to use use double quotes, otherwise, the interpreter will not be able to understand it and will give you a syntax error, as shown in below figure:
  • But if I write in double-quotes, then it will work fine, as shown in below figure:

Escape sequences in Python

  • If you are using double quotes in the same string, then you will need to use a backward slash ( \ ), as shown in the image.
  • Run the program and see the result in the console window:
Now I have another escape sequence ( \n )
  • If I want to add a new line break then I will use escape sequence ( \n ).
  • As you can see in below figure, I have printed the name & age of Richard in separate lines using escape sequence ( \n ).
Tab escape sequence is \t
  • I wrote it with tab escape sequence ( \t ) and run the program, see the six spaces in the printed window:
Some useful points before I move further:
  • You can use backward slash and forward slash \/ like this.
  • You cannot use the backward slash at the end of the string before the end of the quote.
  • You will use double backward slash ( \\ ), if you want to print one.

Concatenation in Python

  • In concatenation, we connect multiple strings together, we use ( + ) sign in order to concatenate strings.
  • Let's understand it with an example, as shown in below figure:
  • As you can see in above figure, I have printed multiple strings in a single line using ( + ) sign.

 String Formatting In Python

When we use multiple strings, it gets harder to concatenate those strings, and it is difficult to remember each string format and codes. In such cases, we need to format those strings. Let's understand it with an example:
  • In String Formatting, we simply place our variables in curly brackets, as shown in below figure:
  • No need to add multiple quotes and + symbol, instead simply use curly brackets for variables.

String Indexes in Python

In python, when we store a string, it goes with an index for each of its element one by one, because it is a sequence of characters. Let's understand it with an example:
  • For example, I saved the name "Ali Haider" in a string then each of its character has an index assigned with it.
  • I have shown the string and the index starting with a comment # in below image:
  • So, that means index of  A=0, L=1, I=2, (for blank space, it is also a character and its index is 3), H=4, a=5, i=6, d=7, e=8 and r=9.
  • After that, I have printed first three characters of that string by writing a range of [0:3], it eliminates the ending index and shows the result as from 0 to 2, which makes the word Ali. (see above image )
  • If you want to print till the final value, then you wont need to write the last index, you will just write it as [0: ].
  • If I write in this way, print(player_name[:]), then it will print the whole string again.
  • You can also write negative indexes like print(player_name[-1]) and it will print from the right side.
Before moving further, I will tell you a magical feature that only Python allows.
  • Type print("a" * 30) and check the magic in print window:

Builtin String Functions in Python

Python has numerous excellent builtin string functions, which we can access using  DOT ( . ) operator. These builtin functions are quite helpful, so let's have a loot at few of them: string.upper()
  • This upper() function will make characters of the string uppercase, as shown in below figure:
  • If, I write print(Precaution.isupper()), It will check the string, whether its uppercase or not.
  • If string will be in uppercase it will return True and if it's not in uppercase, it will return False.
string.lower()
  • Now let's convert string characters to lowercase by using lower() function.
  • When I type print(precaution.lower()), It will print the whole string in lowercase, as shown in below figure:
string.replace()
  • Now if we want to replace any word, then we need to use print(precaution.replace("WEAR", 'BUY')), It will replace the WEAR word with BUY, as shown in the image:
So, that was all about How to use Strings in Python. I have tried to cover all the main points and rest we will keep on covering in coming lectures. In the next lecture, we will have a look at How to use Arithmetic Operators in Python. Till then take care & have fun !!! :)

How to use Data Types in Python

Hello friends, I hope you all are doing great. In today's tutorial, I am going to show you How to use Data types in Python. It's our 2nd tutorial in Python series. In our first tutorial, we have seen a detailed introduction to python and we have also installed PyCharm IDE to work on python. Today, we will understand data types in detail as in order to design an efficient program, you need to select correct data types. Incorrect selection may cause memory loss and may slow your application. So, let's get started with data types in Python:

Data types in Python

  • Data Types are used for the classification or categorization of similar data packets. There are numerous data types available in python, which we can use depending on our projects' requirement.
  • Let's understand data types with an example: Suppose you have some digital data i.e. ON & OFF then you can save this data in Boolean data type but what if your data ranges from 1 to 10, then you need to use integer data types instead of Boolean.
  • You can save Boolean data in integer data type but that will be a redundant i.e. we are allocating more space to our data by specifying integer, when we can easily assign Boolean to it.
  • Here's the flow chart of available data types in Python language:
Now let's have a look at these data types one by one:

Numeric in Python

  • Numeric data types are used to deal with all types of numerical data packets i.e. integer, float etc.
  • Numeric data types are further divided into 3 types, which are:
    • Integer.
    • Float.
    • Complex Number.
Integer in Python
  • Integer (int) data type only holds integer numbers, it could be positive or negative.
  • We can't save decimal numbers in integer data type.
  • Here's a declaration of a variable x and it is assigned a value a of integer 20:

x = int(20)

Float in Python
  • Float data types are used to hold decimal numerical values i.e. 2.13, 3.14 etc.
  • We can also save whole numbers in float data types.
  • Here's a declaration of a variable x and it is assigned a value a of float 20.5:

x = float(20.5)

Complex Numbers in Python
  • Complex Number data types is used to keep complex numbers in it. Complex numbers are those numerical values which have real & imaginary part.
  • That's the versatility of python language, I haven't seen complex number data type in any other programming language.
  • Here's a declaration of a variable x and it is assigned a complex number 1+3j:

x = complex(1+3j)

Dictionary in Python

  • Dictionary data type is sued to save data in key -> value  form. The data is unordered but the value is paired with its key.
  • Dictionary data is placed inside curly brackets i.e. {1:"Jones", 2:"IronMan", 3:"Football", 4: "Mosque"}.
  • Here's a declaration of a variable x and it's assigned a dictionary data type:

x = dict(name="John", age=36)

Boolean in Python

  • Boolean is the simplest data type of all and has just two values assigned to it i.e. True or False.
  • Although it's quite simple but its too handy as we have to use it a lot in IF statements. ( We will cover that later )
  • Here's a declaration of a variable x, assigned a Boolean data type and it's TRUE:

x = bool(1)

Sequence Type in Python

  • Sequence Type data types are used to save data in characters form.
  • We can't save numerical data in sequence type but we can convert the two. ( We will discuss that later )
  • Sequence Types are further divided into 3 types, which are:
    • String.
    • List.
    • Tuple.
Strings in Python
  • A string is used to save one or more characters and it's the most commonly used data type.
  • Let's understand it with a simple example: You must have seen greeting messages on different projects, we save such data in strings.
  • We will discuss strings in detail in our next lecture, where we will perform different operations using strings.
  • Here's a declaration of a variable x, which is assigned a string "Hello World":

x = str("Hello World")

List in Python
  • List data type is used to collect an ordered data, not necessarily of the same type.
  • List data is displayed with square brackets.
  • We will discuss this in our upcoming lectures in detail, here's a declaration of list:

x = list(("apple", "banana", "cherry"))

Tuple in Python
  • Tuple data type is used to arrange ordered data, it's quite similar to list but the data is displayed with small brackets.
  • Here's a Tuple declaration:

x = tuple(("apple", "banana", "cherry"))

So, we have discussed all these data types in python and if you are not understanding any of them yet then no need to worry as we are going to use them a lot in our coming projects, so you will get them. Before moving to next lecture, let's discuss variables in python a little:

Variables in Python

  • Variable is a temporary location in computer's memory, which is used to save the data.
  • As the name implies, we can change its value using different operations or information given to the program.
  • Typically, a program consists of commands that instruct the computer what to do with variables.
  • Variables are assigned with tag name, using which we call the value saved in it.
  • For examples: x = 5, here x is the name of the variable and 5 is its value.
  • In python, we can use special characters, letters, and any number as a variable name.
  • Wide spaces and signs with meanings like "+" and "-" are invalid in python.
  • You should remember that the names of variables are case sensitive. As the uppercase letter "A" and lowercase letter "a" are considered as different variables.
  • As variables are used to save data thus they also assigned a data type. So, a variable could be of int, float or string. (as we seen above)
  • In python, it's not necessary to define variable data type, python sets it dynamically.
  • There are some variables, which are reserved and we cannot use them.
  • We can also change the variables later and assign it to a new variable.
  • For example, I have set a value 10 in a variable eat.

eat=100

  • Then I added and stored the value of eat+10 in a variable cot.

cot = eat + 10

  • So, now cot will be 110.
Types of Variables Here I have set some examples of Variables and their types.
  • X = 456 #integer
  • X = 456L #Long integer
  • X = 4.56 #double float
  • X = "world" #string
  • X = [1, 2] #list
  • X = (0, 1, 2) #tuple
  • X = open('world.py' , 'r') #file
You may assign a single value to multiple variables at the same time.
  • Variable x, y, and z are assigned with the same memory location with the value of 1.

x = y = z = 1

  • Let's create few variables in python, I have created first_name, date_of_birth & last_name, as shown in below figure:
  • I have printed first_name and its appeared in the output panel.
So, that was all about Python Data Types & variables. I hope you have enjoyed today's lecture. In our next lecture, we will have a look at Strings in Python. Till then take care & have fun !!! :)
Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir