Abdullah  Kozey

Abdullah Kozey

1617738420

Unformatted input/output operations In C++

In this article, we will discuss the unformatted Input/Output operations In C++. Using objects cin and cout for the input and the output of data of various types is possible because of overloading of operator >> and << to recognize all the basic C++ types. The operator >> is overloaded in the istream class and operator << is overloaded in the ostream class.

The general format for reading data from the keyboard:

cin >> var1 >> var2 >> …. >> var_n;

  • Here, var1var2, ……, varn are the variable names that are declared already.
  • The input data must be separated by white space characters and the data type of user input must be similar to the data types of the variables which are declared in the program.
  • The operator >> reads the data character by character and assigns it to the indicated location.
  • Reading of variables terminates when white space occurs or character type occurs that does not match the destination type.

#c++ #c++ programs #c++-operator overloading #cpp-input-output #cpp-operator #cpp-operator-overloading #operators

What is GEEK

Buddha Community

Unformatted input/output operations In C++
Abdullah  Kozey

Abdullah Kozey

1617738420

Unformatted input/output operations In C++

In this article, we will discuss the unformatted Input/Output operations In C++. Using objects cin and cout for the input and the output of data of various types is possible because of overloading of operator >> and << to recognize all the basic C++ types. The operator >> is overloaded in the istream class and operator << is overloaded in the ostream class.

The general format for reading data from the keyboard:

cin >> var1 >> var2 >> …. >> var_n;

  • Here, var1var2, ……, varn are the variable names that are declared already.
  • The input data must be separated by white space characters and the data type of user input must be similar to the data types of the variables which are declared in the program.
  • The operator >> reads the data character by character and assigns it to the indicated location.
  • Reading of variables terminates when white space occurs or character type occurs that does not match the destination type.

#c++ #c++ programs #c++-operator overloading #cpp-input-output #cpp-operator #cpp-operator-overloading #operators

f-strings in Python - Explained with Code Examples

When you're formatting strings in Python, you're probably used to using the format() method.

But in Python 3.6 and later, you can use f-Strings instead. f-Strings, also called formatted string literals, have a more succinct syntax and can be super helpful in string formatting.

In this tutorial, you'll learn about f-strings in Python, and a few different ways you can use them to format strings.

What are f-Strings in Python?

Strings in Python are usually enclosed within double quotes ("" ) or single quotes (''). To create f-strings, you only need to add an f  or an F before the opening quotes of your string.

For example, "This" is a string whereas f"This" is an f-String.

How to Print Variables using Python f-Strings

When using f-Strings to display variables, you only need to specify the names of the variables inside a set of curly braces {}. And at runtime, all variable names will be replaced with their respective values.

If you have multiple variables in the string, you need to enclose each of the variable names inside a set of curly braces.

The syntax is shown below:

f"This is an f-string {var_name} and {var_name}."

▶ Here's an example.

You have two variables, language and school, enclosed in curly braces inside the f-String.

language = "Python"
school = "freeCodeCamp"
print(f"I'm learning {language} from {school}.")

Let's take a look at the output:

#Output
I'm learning Python from freeCodeCamp.

Notice how the variables language and school have been replaced with Python and freeCodeCamp, respectively.

How to Evaluate Expressions with Python f-Strings

As f-Strings are evaluated at runtime, you might as well evaluate valid Python expressions on the fly.

▶ In the example below, num1 and num2 are two variables. To calculate their product, you may insert the expression num1 * num2 inside a set of curly braces.

num1 = 83
num2 = 9
print(f"The product of {num1} and {num2} is {num1 * num2}.")

Notice how num1 * num2 is replaced by the product of num1 and num2 in the output.

#Output
The product of 83 and 9 is 747.

I hope you're now able to see the pattern.

In any f-String, {var_name}, {expression} serve as placeholders for variables and expressions, and are replaced with the corresponding values at runtime.

Head over to the next section to learn more about f-Strings.

How to Use Conditionals in Python f-Strings

Let's start by reviewing Python's if..else statements. The general syntax is shown below:

if condition:
  # do this if condition is True <true_block>
else:
  # do this if condition is False <false_block>

Here, condition is the expression whose truth value is checked.

  • If the condition evaluates to True, the statements in the if block (<true_block>) are executed.
  • If the condition evaluates to False, the statements in the else block (<false_block>) are executed.

There's a more succinct one-line equivalent to the above if..else blocks. The syntax is given below:

<true_block> if <condition> else <false_block>

In the above syntax,<true block> is what's done when the condition is True, and <false_block> is the statement to be executed when the condition is False.

This syntax may seem a bit different if  you haven't seen it before. If it makes things any simpler, you may read it as, "Do this if condition is True; else, do this".

This is often called the ternary operator in Python as it takes 3 operands in some sense – the true block, the condition under test, and the false block.

▶ Let's take a simple example using the ternary operator.

Given a number num, you'd like to check if it's even. You know that a number is even if it's evenly divisible by 2. Let's use this to write our expression, as shown below:

num = 87;
print(f"Is num even? {True if num%2==0 else False}")

In the above code snippet,

  • num%2==0 is the condition.
  • If the condition is True, you just return True indicating that num is indeed even, and False otherwise.
#Output
Is num even? False

In the above example, num is 87, which is odd. Hence the conditional statement in the f-String is replaced with False.

How to Call Methods with Python f-Strings

So far, you've only seen how to print values of variables, evaluate expressions, and use conditionals inside f-Strings. And it's time to level up.

▶ Let's take the following example:

author = "jane smith"
print(f"This is a book by {author}.")

The above code prints out This is a book by jane smith.

Wouldn't it be better if it prints out This is a book by Jane Smith. instead? Yes, and in Python, string methods return modified strings with the requisite changes.

The title() method in Python returns a new string that's formatted in the title case - the way names are usually formatted (First_name Last_name).

To print out the author's name formatted in title case, you can do the following:

  • use the title() method on the string author,
  • store the returned string in another variable, and
  • print it using an f-String, as shown below:
author = "jane smith"
a_name = author.title()
print(f"This is a book by {a_name}.")

#Output
This is a book by Jane Smith.

However, you can do this in just one step with f-Strings. You only need to call the title() method on the string author inside the curly braces within the f-String.

author = "jane smith"
print(f"This is a book by {author.title()}.")

When the f-String is parsed at runtime,

  • the title() method is called on the string author, and
  • the returned string that's formatted in title case is printed out.

You can verify that in the output shown below.

#Output
This is a book by Jane Smith.

You can place method calls on any valid Python object inside the curly braces, and they'll work just fine.

How to Call Functions Inside Python f-Strings

In addition to calling methods on Python objects, you can also call functions inside f-Strings. And it works very similarly to what you've seen before.

Just the way variable names are replaced by values, and expressions are replaced with the result of evaluation, function calls are replaced with the return value from the function.

▶ Let's take the function choice() shown below:

def choice(c):
  if c%2 ==0:
    return "Learn Python!"
  else:
    return "Learn JavaScript!"

The above function returns "Learn Python!" if it's called with an even number as the argument. And it returns "Learn JavaScript!" when the argument in the function call is an odd number.

▶ In the example shown below, you have an f-String that has a call to the choice function inside the curly braces.

print(f"Hello Python, tell me what I should learn. {choice(3)}")

As the argument was an odd number (3), Python suggests that you learn JavaScript, as indicated below:

#Output
Hello Python, tell me what I should learn. Learn JavaScript!

If you call the function choice() with an even number, you see that Python tells you to learn Python instead. 🙂

print(f"Hello Python, tell me what I should learn. {choice(10)}")
#Output
Hello Python, tell me what I should learn. Learn Python!

And that ends our tutorial on a happy note!

Conclusion

In this tutorial, you've learned how you can use f-Strings to:

  • print values of variables,
  • evaluate expressions,
  • call methods on other Python objects, and
  • make calls to Python functions.

Original article at https://www.freecodecamp.org

Related Posts

Explains string formatting using the format() method.

#python 

Python range() Function Explained with Examples

In Python, can use use the range() function to get a sequence of indices to loop through an iterable. You'll often use range() in conjunction with a for loop.

In this tutorial, you'll learn about the different ways in which you can use the range() function – with explicit start and stop indices, custom step size, and negative step size.

Let's get started.

Understanding Python's range() Function

Before looking at the different ways of using the range() function, you've got to understand how it works.

The range() function returns a range object.  
This range object in turn returns the successive items in the sequence when you iterate over it.

As stated above, the range function does not return a list of indices. Rather, it returns a range object which returns the indices as and when you need them. This makes it memory-efficient as well.  

You can use the range() function with the following general syntax:

range(start,stop,step)

When you use this syntax in conjunction with a loop, you can get a sequence of indices from start up to but not including stop , in steps of step.

  • You must specify the required argument stop, which can be any positive integer. If you specify a floating point number instead, you'll run into a TypeError as shown:
my_range = range(2.5)

  • If you don't specify the start index, the default start index of 0 is used.
  • If you don't specify the step value, the default step size of 1 is used.

In the subsequent sections, you'll learn about the different ways of using the range() function.

How to Use Python's range() Function to Loop Through Any Iterable

As mentioned in the previous section, you only need one positive integer to use the range() function. The syntax is shown below:

range(stop)

You can use the above line of code to get a sequence from 0 through stop-1 : 0, 1, 2, 3,..., stop-1.  

▶ Consider the following example where you call range() with 5 as the argument. And you loop through the returned range object using a for loop to get the indices 0,1,2,3,4 as expected.

for index in range(5):
  print(index)
  
#Output
0
1
2
3
4

If you remember, all iterables in Python follow zero-indexing. This is why it's convenient to use range() to loop through iterables.

An iterable of length len has 0, 1, 2, ..., len-1 as the valid indices. So to traverse any iterable, all you need to do is to set the stop value to be equal to len. The sequence you'll get – 0, 1, 2, ..., len-1 – is the sequence of valid indices.

▶ Let's take a more helpful example. You have a list my_list. You can access all items in the list by knowing their indices, and you can get those indices using range() as shown below:

my_list = ["Python","C","C++","JavaScript","Julia","Rust","Go"]
for index in range(len(my_list)):
  print(f"At index {index}, we have {my_list[index]}")

Remember, you can use Python's built-in function len to get the length of any iterable. In the above code, you use both the valid indices, and the list items at those valid indices. Here's the output:

Notice how my_list is 7 items long, and the indices obtained are from 0 through 6, as expected.

Sometimes, you may need to use negative integers instead. In this case, if you use only the stop argument, you'll not get the desired output, though the code doesn't throw an error.

This is because the default start value is assumed to be 0, and you cannot count up from 0 to -5.

for index in range(-5):
  print (index)
  
  
#Output
#NOTHING HERE

How to Use Python's range() Function with Explicit Start and End Indices

You may not always want to start at zero. You can start at any arbitrary index by setting the start value to the index that you'd like to start from. The syntax is as follows:

range(start,stop)

In this case, you'll be able to get the sequence: start, start + 1, start + 2, and so on up to stop-1.

▶ In the example below, you're starting at 10, count all the way up to but not including 15 in steps of 1.

for index in range(10,15):
  print(index)

#Output
10
11
12
13
14

In the previous section, you saw how using only the stop argument won't work when you need negative integers. However, when you specify start and stop indices explicitly, you can as well work with negative integers.

▶ In this example, you're trying to count up from -5 in steps of 1. Always keep in  mind that the counting stops at the value that's one less than the stop index.

for index in range(-5,0):
  print(index)
  
#Output
-5
-4
-3
-2
-1

How to Use Python's range() Function with a Custom Step Size

Instead of traversing an iterable sequentially, you may sometimes want to stride through it, accessing every k-th element. This is when the optional step argument comes in handy. The general syntax is shown below:

range(start,stop,step)

When you use this syntax and loop through the range object, you can go from start to stop-1 with strides of size step.

  • You'll get the sequence: start, start + step, start + 2*step, and so on up to start + k*step such that  start + k*step < stop and start + (k+1)*step > stop.

▶ In the example below, you'd like to go from 0 to 20 in steps of 2. Notice how the last index printed out is 19. This is because, if you take another step, you'll be at 21 which is greater than 20.

Always remember, the last value you get can be as close to stop as possible, but can never be stop.

for index in range(1,20,2):
  print(index)

#Output
1
3
5
7
9
11
13
15
17
19

How to Use Python's range() Function with a Negative Step Size

So far, you've learned to use the range() function with start and stop indices, and a specific step size, all the while counting up from start to stop.

If you need to count down from an integer, you can specify a negative value for step. The general syntax is:

range(start,stop,<negative_step>)
  • The range object can now be used to return a sequence that counts down from start in steps of negative_step, up to but not including stop.
  • The sequence returned is start, start - negative_step, start - 2*negative_step, and so on up to start - k*negative_step such that start - k*negative_step > stop and start - (k+1)*negative_step < stop.
  • There's no default value for negative step – you must set negative_step = -1 to count down covering each number.

▶ In this example, you'd like to count down from 20 in steps of -2. So the sequence is 20, 18, 16, all the way down to 2. If you go another 2 steps lower, you'll hit 0, which you cannot as its smaller than the stop value of 1.

for index in range(20,1,-2):
  print(index)
  
#Output
20
18
16
14
12
10
8
6
4
2

It's easy to see that start > stop to be able to count down.

for index in range(10,20,-1):
  print(index)
  
 #Ouput
 #Nothing is printed - the sequence is empty.

▶ In the above example, you try counting down from 10 to 20 which is impossible. And you don't get any output which is expected.

How to Use Python's range() and reversed() Functions to Reverse a Sequence

If you need to access the elements of an iterable in the reverse order, you can use the range() function coupled with the reversed() function.

Python's built-in reversed() function returns a reverse iterator over the values of a given sequence.

▶ Let's take our very first example, where we used range(5). In the example below, we call reversed() on the range object. And we see that we've counted down from 4 to 0.

for index in reversed(range(5)):
  print (index)
  
#Output
4
3
2
1
0

As you can see, this is equivalent to using range(4,-1,-1). If you prefer, you may use the reversed() function instead of negative_step argument discussed in the previous section.

Conclusion

In this tutorial, you've learned the different ways in which you can use the range() function. You can try a few examples to get a different sequence each time. This practice will help you use range() effectively when looping through iterables.

Original article source at https://www.freecodecamp.org

#python

Tamale  Moses

Tamale Moses

1624240146

How to Run C/C++ in Sublime Text?

C and C++ are the most powerful programming language in the world. Most of the super fast and complex libraries and algorithms are written in C or C++. Most powerful Kernel programs are also written in C. So, there is no way to skip it.

In programming competitions, most programmers prefer to write code in C or C++. Tourist is considered the worlds top programming contestant of all ages who write code in C++.

During programming competitions, programmers prefer to use a lightweight editor to focus on coding and algorithm designing. VimSublime Text, and Notepad++ are the most common editors for us. Apart from the competition, many software developers and professionals love to use Sublime Text just because of its flexibility.

I have discussed the steps we need to complete in this blog post before running a C/C++ code in Sublime Text. We will take the inputs from an input file and print outputs to an output file without using freopen file related functions in C/C++.

#cpp #c #c-programming #sublimetext #c++ #c/c++

Dicey Issues in C/C++

If you are familiar with C/C++then you must have come across some unusual things and if you haven’t, then you are about to. The below codes are checked twice before adding, so feel free to share this article with your friends. The following displays some of the issues:

  1. Using multiple variables in the print function
  2. Comparing Signed integer with unsigned integer
  3. Putting a semicolon at the end of the loop statement
  4. C preprocessor doesn’t need a semicolon
  5. Size of the string matters
  6. Macros and equations aren’t good friends
  7. Never compare Floating data type with double data type
  8. Arrays have a boundary
  9. Character constants are different from string literals
  10. Difference between single(=) and double(==) equal signs.

The below code generates no error since a print function can take any number of inputs but creates a mismatch with the variables. The print function is used to display characters, strings, integers, float, octal, and hexadecimal values onto the output screen. The format specifier is used to display the value of a variable.

  1. %d indicates Integer Format Specifier
  2. %f indicates Float Format Specifier
  3. %c indicates Character Format Specifier
  4. %s indicates String Format Specifier
  5. %u indicates Unsigned Integer Format Specifier
  6. %ld indicates Long Int Format Specifier

Image for post


A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a non-negative integer in the range [0 to 4294967295]. The signed integer is represented in twos-complement notation. In the below code the signed integer will be converted to the maximum unsigned integer then compared with the unsigned integer.

Image for post

#problems-with-c #dicey-issues-in-c #c-programming #c++ #c #cplusplus