Subscribe Us

Showing posts with label discussion. Show all posts
Showing posts with label discussion. Show all posts

R - Programming

 



Features Of R : 

1) R is a well-developed, simple and effective programming language which includes decision making , flow control, recursive, functions input and output methods

2) R has an effective data handling and storage facility which is important for statistical analysis.

3) R Provides a variety of operators for calculations on arrays, lists, vectors and matrices.

4) R provides a large, coherent and integrated collection of packages and tools for data analysis including mathematical symbols. Dynamic and interactive graphics are available through additional packages 

5) R and its libraries implement a wide variety of statistical and graphical techniques, including  linear and non linear modelling, classical statistical tests, time - series analysis, classification,clustering and others

6) R is easily extensible through function and extensions. R community is noted for its active contribution in terms of packages. For computationally intensive tasks, C, C++ and Fortran code van be linked and called at run time. Advanced users can write C/C++, Java , .NET or Python code to manipulate R objects directly

7) Since R was  inherited from a language called S , R has stronger objective-oriented programming facilities than  most statistical computation languages 

Identifiers:

The unique name given to variable like function or object is known as an identifier . Following are the rules for naming an identifier.

a)     Identifier can be a combination of letters, digits, period, and underscore(_).

b)     It must start with a letter or a period. If it starts with a period, it cannot be followed by a digit.

c)     Reserved word in R cannot be used as identifiers

Examples of some valid identifiers are: total, sum, .date, .date.of.birth,sum_of_two

Example of some invalid identifiers are : tot@l,2um, _prod, TRUE, .0wl

Earlier version of R used underscore  (_) as an assignment operator. So, the period (.) was used extensively in variable names having multiple words.

Constants :

Constants or literals, as the name suggest, are entities whose values cannot be altered. Basic type of constants are numeric and character constants. They are built-in constants also.  

All numbers fall under this category. They can be of type integer, double, or complex, We can check the type of constants by typeof() function.

Variables:

A variable provides us with named storage that our programs manipulate. A variable in R can store an atomic vector, group of atomic vectors or a combination of many R objects. A valid variable name consists of letters, numbers and the dot or underline characters. The rule for naming a variable is same as that of any identifiers which is already discussed above.

The variable can be assigned values leftward, rightward and equal to operator. The values of the variables can be printed using print () or cat ()function. The cat()  function combines multiple items into a continuous print output.

Operators :

R has several operator to perform tasks arithmetic, logical and bitwise operations. R provides following types of operators . They are

a)     Arithmetic operator

b)     Relational Operator

c)     Logical Operator

d)     Assignment Operator

e)     Miscellaneous Operator

Arithmetic operator:

These operators are used to carry out mathematical operations, like addition, subtraction, multiplication, division. The arithmetic operators are applied for vectors. Even if we give a single value, it is considered as a vector with length one.

 

  

Relational operator :

Relational operator are used to compare between values. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value.

 

 

Logical operator :


 Logical operator are applicable only to vectors of type logical, numeric or complex. All numbers greater than 1 are considered as logical value TRUE. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is Boolean value.

Operator

Description

!

Logical Not, Takes each element of the vector and gives the opposite logical value

&

Element wise logical And. It combines each element of the first vector with corresponding element of the second vector and gives an output TRUE if both the values are  TRUE.

&&

Logical AND. It takes first element of both the vectors and gives  TRUE only if both elements are TRUE

|

Element-wise logical OR. It combines each element of the first vector with the corresponding element of the second vector and gives an output TRUE if one of the elements is TRUE

||

Logical OR. It takes first element of both the vectors and gives an output TRUE if one of the element is TRUE

 

Assignment Operator :

These operators are used to assign values to variables or vectors. The operators <- and = can be used almost interchangeably to assign values to a variables in the same environment.

The <<- operator is used for assigning values to variables in the parent environments

Operators

Description

<-,<<-,=

Leftward assignment

->,->>

Rightward assignment

 

 

Miscellaneous operator :

These operator are used for specific purpose. They are not used for mathematical or logical computation.

Operators

Description

:

Colon. It creates a range of numbers in sequence for a vector.

%in%

This operator is used to check whether an element belongs to a vector or not. The result will be a Boolean value either TRUE or FLASE.

%*%

This operator is used to multiply a matrix with its transpose

 

 

Strings:

Strings are created in R by writing any value within a pair of single quote or double quotes. However, internally R stores every strings within  double quotes, even if we create them with single quote. The quotes at the beginning and end of a string should be both double quotes or both single quotes. They cannot be mixed. Another feature of string is that double quotes can be inserted into a string staring and ending with single quote. Similarly single quote can be inserted into a string a staring and ending with double quotes.

Reading String :

We can read string from keyboard using the readLines () function . It lets the user to enter one-line string at the terminal . The syntax as follows :

a <- readLines("stdin", n=1);



Share:

HTML & Javascript

 





Four Arithmetic Operation with the help of HTML & Javascript 


<!DOCTYPE html>

<html>

<head>

<title>Four function calculators</title>

<script language="javascript">

function Addition()

 {

  var x,y,c,c1,z,sp, c2,c3;

  x=parseInt(document.calculator.x.value);

  y=parseInt(document.calculator.y.value);

  c=document.getElementById("c");

  c1=document.getElementById("c1");

  sp=document.getElementById("sp");

  c2=document.getElementById("c2");

  c3=document.getElementById("c3");

  if(c.checked==true)

  {

  z=x+y;

  //alert(z);

  sp.innerHTML=z;

  c1.checked=false;

  c2.checked=false;

  c3.checked=false;

  }


// body...

}

function Substraction()

 {

  var x,y,c,c1,z,sp,c2,c3;

  x=parseInt(document.calculator.x.value);

  y=parseInt(document.calculator.y.value);

  c=document.getElementById("c");

  c1=document.getElementById("c1");

  sp=document.getElementById("sp");

  c2=document.getElementById("c2");

  c3=document.getElementById("c3");

  if(c1.checked==true)

  {

  z=x-y;

  //alert(z);

  sp.innerHTML=z;

  c.checked=false;

  c2.checked=false;

  c3.checked=false;



  }


// body...

}

function multiplication()

{

var x,y,c,c1,z,sp,c2,c3;

x=parseInt(document.calculator.x.value);

y=parseInt(document.calculator.y.value);

c=document.getElementById("c");

c1=document.getElementById("c1");

sp=document.getElementById("sp");

c2=document.getElementById("c2");

  c3=document.getElementById("c3");

if (c2.checked==true) 

{

z=x*y;

//alert(z);

sp.innerHTML=z;

c.checked=false;

c1.checked=false;

c3.checked=false;

}

}

function division()

{

var x,y,c,c1,z,sp,c2,c3;

x=parseInt(document.calculator.x.value);

y=parseInt(document.calculator.y.value);

c=document.getElementById("c");

c1=document.getElementById("c1");

sp=document.getElementById("sp");

c2=document.getElementById("c2");

  c3=document.getElementById("c3");

if (c3.checked==true) 

{

z=x/y;

//alert(z);

sp.innerHTML=z;

c.checked=false;

c1.checked=false;

c2.checked=false;

}

}

</script>

</head>

<body>

<form name="calculator">

Enter first Number<input type="text" name="x"><br>

Enter second number<input type="text" name="y"><br>

Answer:<span id="sp"></span>

<input type="checkbox" name="c" id="c" value="add" onclick="Addition();">Add

<input type="checkbox" name="c1" id="c1" value="sub" onclick="Substraction();">Sub

<input type="checkbox" name="c2" id="c2" value="multiplication" onclick="multiplication();">multi

<input type="checkbox" name="c3" id="c3" value="division" onclick="division();">div


</body>

</html>

Share:

Tableau

 



Tableau Worksheet 


 Tableau worksheets are powerful analytical tools, but the real utility of this

application is in being able to share the analysis with other people in your

organization. An executive overview such as the one shown in Figure 1‑8 not

only breaks down sales by state, but it also enables the viewer to see how

different customer segments and product categories are performing. In addition,

the overview graphically displays profitability using different colors.

In Tableau terminology, this type of display that combines information from

more than one sheet is called a dashboard.


Tableau can use many different types of data sources, ranging from text

and Excel to all the best databases in the world.


The Tableau worksheet includes a number of elements that you’ll use as you

build your analysis. These include the following:

1) Data pane: This is the area that appears along the left side of the worksheet (in the Side bar) and contains two sections: one labeled Dimensions and one labeled Measures. These sections hold the fields that you can add to the work area to perform the analysis. The Side bar also has a tab labeled Analytics that’s used to add things like trend lines to a visualization.


2) Shelves and cards: These are the areas in the workspace with names like Pages, Filters, Marks, and so on where you drag fields from the Data pane to produce a visualization. Your visualization will change depending on where you drop a field, so later chapters will provide much more detailed information about using shelves and cards.

Understanding Tableau worksheets

Tableau has three different types of pages that you can use to create and present your data analysis results. These include worksheets, dashboards, and stories. 

You need to know the following:

 You use worksheets to create visualizations. 

You use dashboards to combine two or more worksheets that you want to share.

You use stories as a means of stepping people through worksheets and dashboards with commentary to guide them through your analysis.

Getting to Know the Tableau Desktop Environment

Getting to know Tableau Desktop means getting to know several different pages and workspaces. What you see in Tableau will depend on what you are trying to accomplish. Rather than presenting a cluttered workspace overloaded with controls and dialogue boxes, Tableau provides visual cues to suit the task at hand. 

Looking at the Tableau Start page

Tableau works with all kinds of source data that can be located almost anywhere as long as it’s accessible to the user. That source could be an Excel file, a text file, or a database. To do anything in Tableau, then, you first have to specify your data source or sources. That’s why, when you first start Tableau, you see the Start page shown in Figure




Tableau works using your existing data, so you must have access to some type of source data first. The page contains three distinct sections: 

Connect: You use this section when you want to start a new data connection in your Tableau workbook. Tableau Desktop has two editions, and the type of edition you’re using will change the options you have to choose from. Tableau Desktop Personal Edition is for connections to file- based data sources like Excel and Microsoft Access, and also includes several cloud-based data sources. Tableau Desktop Professional Edition allows you to go beyond the files and additionally connect to databases hosted on servers. 

Open: You use this section to open and continue working on an existing Tableau workbook. The existing workbook can be one that you’ve created or one of the samples that Tableau Software provides for training purposes. 

Discover: This section gives you easy access to training resources as well as news about Tableau.

 

Working with Dimensions and Measures

You’ve probably noticed that Tableau separates data fields into dimensions and measures,  It’s useful to understand how Tableau decides what fields to place in each area.

Understanding dimensions

Tableau treats any field that contains qualitative, categorical information such as text or dates as dimensions. These types of fields typically produce labels when you add them to the Rows or Columns shelves in a view. Dimensions enable you to provide detail in a view and to effectively slice or categorize your data.

Understanding measures

Measures are fields that contain quantitative (or numeric) values that you can do math on (sum, count, and so on). These types of fields typically produce the axes on a chart and are the numbers we use to evaluate whether results are good or bad. As a rule of thumb, most measures are numbers and most dimensions are non-numeric. Think about it in these terms. If you do math on it, it is probably a measure. If you use it to slice the data, it is a dimension. However, in some cases, a number may be a dimension. For example, while an order id may be a number, would you ever add up your order #’s or take an average of order #? You may, however, look at the Total Sales amount by order, so using the order id as a dimension would be preferred.

Modifying Your View

Tableau gives you a number of different tools to help you modify the view of the visualization. We take a quick look at a couple of them here. 

Transpose: This button swaps the position of the items on the Columns and Rows shelves. By clicking this button, you can quickly switch between horizontal and vertical bar charts, for example.  

Sort Descending: This button sorts a Dimension list in descending order.

Sort Ascending: This button sorts a Dimension list in ascending order.

Show Me: This displays the Show Me palette so that you can quickly choose different chart types.

 Understanding Data Sources

Modern companies live on data. They gather data on everything from inventory costs to labor costs to the smallest details  involving sales. All this raw data can then be transformed, aggregated, and analyzed into submission to create useful business information that can help drive competitive decision making. But before any of the data can be analyzed, it needs to be stored in an accessible and useful form. Now we take a look at what this means.

Considering how data is stored 

To actually use or analyze data, the data needs to be stored in a standardized format. In the days before computers, this typically meant writing everything down in a ledger. The ledger contained a number of columns that were used for specific purposes, such as the date of the transaction, the type of transaction, the amount of money involved, names of the people  involved, and other various details. All of this information was written in by hand, but the bookkeepers always followed the sameformat so that the information could be more easily understood. When computers came along, it quickly became clear that the old handwritten ledger could be replaced by a computerized database. What was also clear is the fact that the database needed to have a formal structure similar to that of the old-time ledger, because this formal structure made it possible for the computer to process the data. 

One very important thing to remember about databases is that they all have a defined structure.

Using file-based data sources

Unfortunately, people sometimes use tools to do jobs that aren’t totally appropriate for a given task. There is the old saying, “if all you have is a hammer, everything looks like a nail.” Using file-based sources like Excel instead of a database is an easy option for many of us, but needs to be done with care. Tableau will read the first few values of each column in the file and will determine a default data type. However, when connecting to a database, Tableau can pick up the definitions of fields from that database,  taking it more likely for your fields to be consistent. One of the reasons that people like to use file-based sources like Excel as a database is because they are so flexible. People don’t like to be told that they have to enter a valid date or other specific information that may not readily be at hand. Or, a user might decide that she would like to remove a column or use a different name for an existing column. Either way, if you’ve created a visualization in Tableau based upon the existing structure (and  hoping for valid data), your analysis could mysteriously stop functioning properly. As with any data source, be aware that you need consistency in your structure and keep an eye out for errors. 


Share:

C Array




In C, array is a composite data type. Because we can create an array with the help of primitive data type like int, chat, double etc.

Syntax for creation of one Dimensional array in C

int a[5];

Here a is the array name, type is int. total allocation is 5(5*4=20bytes) here index starts from 0(zero)

Initialization of an array :

int a[]={1,2,3,4,5,6}

if you want access element from above mentioned array, then you can access it with help of index. for example the index of value 3 is 2.

if you want to access all the element from an array, then you can use loop

example : for loop

for(i=0;i<6;i++)

{

   printf("%d\n", a[i]);

}

to calculate size of an array, use the formula :

l=sizeof(a)/sizeof(a[0])


Question & Answer


Choose correct or the best alternative in the following:

Q.1 What is the output of the following program?

main ( )

{ int x = 2, y = 5;

if (x < y) return (x = x+y); else printf (“z1”);

printf(“z2”);

}

(A) z2 (B) z1z2

(C) Compilation error (D) None of these

Ans: D

There is no compilation error but there will no output because function is returning a

value and if statement is true in this case.

Q.2 Choose the correct one

(A) Address operator can not be applied to register variables

(B) Address operator can be applied to register variables

(C) Use of register declaration will increase the execution time

(D) None of the above

Ans: D

A register access is much faster than a memory access, keeping the frequently

accessed variables in the register will lead to faster execution of programs.

Q.3 What is the following program doing?

main ()

{ int d = 1;

do

printf(“%d\n”, d++);

while (d < = 9);}

(A) Adding 9 integers (B) Adding integers from 1 to 9

(C) Displaying integers from 1 to 9 (D) None of these

Ans: C

d starting from 1 is incrementing one by one till d=9 so the printf statement is printing

numbers from 1 to 9.

Q.4 What is the output of the following program?

main ( )

{ extern int x;

x = 20;

printf(“\n%d”, x);

}


(A) 0 (B) 20

(C) error (D) garbage value

Ans: C

Output of the given program will be “Linker error-undefined symbol x”. External

variables are declared outside a function.

Q.5 If x is one dimensional array, then pick up the correct answer

(A) *(x + i) is same as &x[i] (B) *&x[i] is same as x + i

(C) *(x + i) is same as x[i] +1 (D) *(x + i) is same as *x[i]

Ans: A

num[i] is same as *(num+i)

Q.6 Consider the following declaration

int a, *b = &a, **c = &b;

The following program fragment

a = 4;

**c = 5;

(A) does not change the value of a (B) assigns address of c to a

(C) assigns the value of b to a (D) assigns 5 to a

Ans: D

The given statements assigns 5 to a

Q.7 Choose the correct answer

(A) enum variable can not be assigned new values

(B) enum variable can be compared

(C) enumeration feature increase the power of C

(D) None of the above

Ans: C

The enumerated data types give an opportunity to invent our own data typeand define

what value the variable of this data type can take.

Q.8 The content of file will be lost if it is opened in

(A) w mode (B) w+ mode

(C) a mode (D) a+ mode

Ans: A

When the mode is writing, the contents are deleted and the file is opened as a new file.

Q.9 Consider the following code segment:

int a[10], *p1, *p2;

p1 = &a[4];

p2 = &a[6];

Which of the following statements is incorrect w.r.t. pointers?

(A) p1 + 2 (B) p2 – 2

(C) p2 + p1 (D) p2 – p1

Ans: C


Addition of two pointers is not allowed.

Q.10 The second expression (j – k) in the following expression will be evaluated

(i + 5) && (j – k)

(A) if expression (i + 5) is true.

(B) if expression (i + 5) is false.

(C) irrespective of whether (i + 5) is true or false.

(D) will not be evaluated in any case.

Ans: A

In a compound logical expression combined with &&, the second expression is

evaluated only if first is evaluated in true.


In the for statement: for (exp1; exp2; exp3) { … }

where exp1, exp2 and exp3 are expressions. What is optional?

(A) None of the expressions is optional.

(B) Only exp1 is optional.

(C) Only exp1 and exp3 are optional.

(D) All the expressions are optional.

Ans: D

All the expressions are optional. For (;;) is a valid statement in C.

Q.12 The output of the following code segment will be

char x = ‘B’;

switch (x) {

case ‘A’: printf(“a”);

case ‘B’: printf(“b”);

case ‘C’: printf(“c”);

}

(A) B (B) b

(C) BC (D) bc

Ans: D

Since there is no break statement, all the statement after case’B’ are executed.

Q.13 What will be the output of the following code segment?

main( ) {

char s[10];

strcpy(s, “abc”);

printf(“%d %d”, strlen(s), sizeof(s));

}

(A) 3 10 (B) 3 3

(C) 10 3 (D) 10 10

Ans: A

strlen(s) give the length of the string, that is 3 and sizeof(s) give the size of array s

that is 10.

Q.14 Which of the following is the odd one out?

(A) j = j + 1; (B) j =+ 1;

(C) j++; (D) j += 1;

Ans: B

j=+1 is odd one out as rest all means incrementing the value of variable by 1.

Q.15 Which of the following is true for the statement:

NurseryLand.Nursery.Students = 10;

(A) The structure Students is nested within the structure Nursery.

(B) The structure NurseryLand is nested within the structure Nursery.

(C) The structure Nursery is nested within the structure NurseryLand.

(D) The structure Nursery is nested within the structure Students.

Ans: C

The structure Nursery is nested within the structure NurseryLand.

Q.16 What will be the output of the following code segment, if any?

myfunc ( struct test t) {

strcpy(t.s, “world”);

}

main( ) {

struct test { char s[10]; } t;

strcpy(t.s, “Hello”);

printf(“%s”, t.s);

myfunc(t);

printf(“%s”, t.s);

}

(A) Hello Hello (B) world world

(C) Hello world (D) the program will not compile

Ans: D

The program will not compile because undefined symbol s for myfunc( ) function.

Structure should be defined before the main and the function where it is called.

Q.17 If a function is declared as void fn(int *p), then which of the following statements is

valid to call function fn?

(A) fn(x) where x is defined as int x;

(B) fn(x) where x is defined as int *x;

(C) fn(&x) where x is defined as int *x;

(D) fn(*x) where x is defined as int *x;

Ans: B

Function void fn(int *p) needs pointer to int as argument. When x is defined as int

*x, then x is pointer to integer and not *x.

Q.18 What is the following function computing? Assume a and b are positive integers.

int fn( int a, int b) {

if (b == 0)

return b;

else

return (a * fn(a, b - 1));

}

(A) Output will be 0 always (B) Output will always be b

(C) Computing ab (D) Computing a + b

Ans: A

The output is always be 0 because b is decremented in recursive function fn each time

by 1 till the terminating condition b==0 where it will return 0.

Q.19 What is the output of the following C program?

# include <stdio.h>

main ( )

{

int a, b=0;

static int c [10]={1,2,3,4,5,6,7,8,9,0};

for (a=0; a<10;+ + a)

if ((c[a]%2)= = 0) b+ = c [a];

printf (“%d”, b);

}

(A) 20 (B) 25

(C) 45 (D) 90

Ans: A

printf statement will print b which is sum of the those values from array c which get

divided by 2, that is 2+4+6+8=20.

Q.20 If a, b and c are integer variables with the values a=8, b=3 and c=-5. Then what is the

value of the arithmetic expression:

2 * b + 3 * (a-c)

(A) 45 (B) 6

(C) -16 (D) -1

Ans: A

the value of the arithmetic expression is 45 as 2*3+3*(8—5)=6+3*13=6+39=45

Thank you, Keep Learning

Share:

R Vector



In R, Vector is a collection of same data type just like one Dimensional array in C.

we can create vector as follows 

v=c()

or 

v=c(1,2,3,4,5)

first statement is the creation of empty vector whereas second statement is the creation of the vector with some value.

to calculate length of vector we can use length function like 

x=length(v)

To Access any element from vector, we can use index position, here index position starts from 1 (where as in c Array index position starts from 0)

i.e, if you want to access 4 from above vector, then you can write x=v[4]

To access all the element from the vector 

x = c(1,3,4,7)

n = length(x)

for(i in 1:n)

{

print(x[i])

}

Thank You , Keep Learning

Share:

Java String




In java, String is a final class. which is inherit from object class.  

we can use final keyword against variable, function and class. if you use final keyword against a variable, then the variable will be constant. 

if you use final keyword against class, then it can not be inherited, and if you use it against function , then you cannot be overridden the function. 

So from above discussion, we can say String is a class which cannot be inherited .

a) Creation of  String :

String s= "hello"

b) Calculate length of the String 

int l= s.length();

c) Access the element with respect of index:

char c= s.charAt(i), where i represents the index

if you want access all the element from a string then we can use either use for loop or for-each loop

ex. for loop

for(i=0;i<s.length();i++)

{

 System.out.print(s.charAt(i));

}

d) Convert String to Character Array

Char t[]=s.tocharArray();

Thank you, keep learning

Share:

Python List

 



What is List : 

In python, list is a collection of any data type which is mutable, i.e means we can change the value of list  

list Creation

we can create list in two ways

a) Empty List : L=[]

b) With some values : L1=[1,2,3,4,5,6]

After creation of empty list we can add some number with the help of append and extend function. 

for accessing list element we can use the index of the element. i.e if we want to access 3 from above mentioned list(L1), then we have to write, x= L1[2],  where 2 is the index of 3.

if you want to access all the element, then you can use range function as follows:

for i in range (0,len(L1)):

    print(L1[i])

Here, i represents the index of individual element. 

Lists are pretty useful, but only if you can get at the things inside them. You can already go through the elements of a list in order, but what if you want, say, the fifth element? You need to know how to access the elements of a list. Here’s how you would access the first element of a list:

animals = ['bear', 'tiger', 'penguin', 'zebra']

bear = animals[0]


How do you make a two- dimensional (2D) list?

That’s a list in a list like this: [[1,2,3],[4,5,6]].

Aren’t lists and arrays the same thing?

It depends on the language and the implementation. In classic terms, lists are very different from arrays because of how they’re implemented. In Ruby, lists are referred to as arrays. In Python, they’re referred to as lists. Just call these lists for now, since that’s what Python calls them. 

How come a for- loop can use variables that aren’t defined yet?

It defines that variable, initializing it to the current element of the loop iteration, each time through. 

Why does for i in range(1, 3): only loop two times instead of three times?

The range() function only does numbers from the first to the last, not including the last. So itstops at two, not three, in the above. This turns out to be the most common way to do this kind of loop.

What does elements.append() do?

It simply appends to the end of the list. Open up the Python shell and try a few examples with a list you make. Any time you run into things like this, always try to play with them interactively in the Python shell.

What is While loop

A while- loop will keep executing the code block under it as long as a boolean expression is True. they do is simply do a test like an if- statement, but instead  of  running the code block once, they jump back to the “top” where the while is and repeat. It keeps doing this until the expression is False. Here’s the problem with while- loops: Sometimes they do not stop. This is great if your intention is to just keep looping until the end of the universe. Otherwise you almost always want your loops to end eventually. To avoid these problems, there’s some rules to follow:

1. Make sure that you use while- loops sparingly. Usually a for- loop is better.

2. Review your while statements and make sure that the thing you are testing will become False at some point.

3. When in doubt, print out your test variable at the top and bottom of the while- loop to see what it’s doing.


String Delimiters, Part I

A string in Python is a sequence of characters. For Python to recognize a sequence of characters, like hello, as a

string, it must be enclosed in quotes to delimit the string.

For this whole section on strings, continue trying each set-off line of code in the Shell. Try

"hello"

Note that the interpreter gives back the string with single quotes. Python does not care what system you use. Try

'Hi!'

Having the choice of delimiters can be handy.

Figure out how to give Python the string containing the text: I’m happy. Try it. If you got an error, try it with another type of quotes, and figure out why that one works and not the first.

There are many variations on delimiting strings and embedding special symbols. 

Note: A string can have any number of characters in it, including 0. The empty string is ’’ (two quote characters

with nothing between them). Many beginners forget that having no characters in the middle is legal. It can be useful.

Strings are a new Python type. Try

type('dog')

type('7')

type(7)

The last two lines show how easily you can get confused! Strings can include any characters, including digits. Quotes

turn even digits into strings.

String Concatenation

Strings also have operation symbols. Try in the Shell (noting the space after very):

'very ' + 'hot'

The plus operation with strings means concatenate the strings. Python looks at the type of operands before deciding

what operation is associated with the +. Think of the relation of addition and multiplication of integers, and then guess the meaning of

3*'very ' + 'hot'

Were you right? The ability to repeat yourself easily can be handy. Predict the following and then test. Remember the last section on types:

7+2

'7'+'2'

Python checks the types and interprets the plus symbol based on the type. Try

'7'+2

With mixed string and int types, Python sees an ambiguous expression, and does not guess which you want - it just gives an error! 

This is a traceback error. These occur when the code is being executed. In the last two lines of the traceback it shows the Python line where the error was found, and  then a reason for the error. Not all reasons are immediately intelligible to a starting programmer, but they are certainly worth checking out. In this case it is pretty direct. You need to make an explicit conversion, so both are strings if you mean concatenation, ’7’ + str(2), or so both are int if you mean addition, int(’7’) + 2.



Share:
Powered by Blogger.

Ad Code

Responsive Advertisement

Ad Code

Responsive Advertisement

Featured post

Search This Blog

Recently added book names

THE HTML AND CSS WORKSHOP   | MICROSOFT POWER BI COOKBOOK   | MongoDB in Action, 2nd Edition  | ADVANCED DEEP LEARNING WITH PYTHON   | Cracking Codes with Python An Introduction to Building and Breaking  | Moris Mano Degital Design 3rd Edition  | Beginning App Development with Flutter by Rap Payne  |react hooks in Action - John Larsen   | Artificial Intelligence A Modern Approach Third Edition Stuart Russel  | Data Structures and Algorithms - Narasimha Karumanchi   | Thomas S.M. - PostgreSQL High Availability Cookbook - 2017  | Gunnard Engebreth PHP 8 Revealed Use Attributes the JIT Compiler   | ICSE Class X Computer Application Notes   | INTERNET OF THINGS PROJECTS WITH ESP32   | 100 aptitude trick(102pgs)s   | OBJECT_ORIENTED_PROGRAMMING Question & Answer   | C questions and answer   | Full_Book_Python_Data_Structures_And_Algorithm   | Jira 8 Administration Cookbook Third Edition  | KALI LINUX WIRELESS PENETRATION TESTING BEGINNERS GUIDE THIRD EDITION - Cameron Buchanan, Vivek Ramachandran  HTML5 & javascript By :- Jeanine Meyer   | Python For Beginners Ride The Wave Of Artificial Intelligence   | HackingTheXbox   | Introduction to Algorithms 3rd.Edition - (CLRS)   | The C++ Programming Language - Bjarne Stroustrup   | Modern C++ Programming Cookbook - Marius Bancila   | Java The Complete Reference Eleventh Edition   Data_Communications and Networking 4th Ed Behrouz A Forouzan   | DevOps with Kubernetes - Hideto Saito   | The-Linux-Command-Line-A-Complete-Introduction   | Assembly Language for X86 Processors KIP R. Irvine   | Effective_Modern_C++ - Scott Meyer

Contact Form

Name

Email *

Message *

Followers

Mobile Logo Settings

Mobile Logo Settings
image

Computer Training School Regd. under Govt. of West Bengal Society Act 1961

Header Ads Widget

Responsive Advertisement

Hot Widget

random/hot-posts

Recent in Sports

Popular Posts

Most Popular

Popular Posts

Labels

Blogger templates