Parallel Assignment In Python Convert

Variables, Assignment and Input¶

The = , augmented = and del Statements

Variables hold the state of our program. In Variables we’ll introduce variables, then in The Assignment Statement we’ll cover the basic assignment statement for changing the value of a variable. This is followed by an exercise section that refers back to exercises from Simple Numeric Expressions and Output. In Input Functions we introduce some primitive interactive input functions that are built-in. This is followed by some simple exercises that build on those from section The Assignment Statement. We’ll cover the multiple assignment statement in Multiple Assignment Statement. We’ll round on this section with the del statement, for removing variables in The del Statement.

Variables¶

As a procedural program makes progress through the steps from launch to completion, it does so by undergoing changes of state. The state of our program as a whole is the state of all of the program’s variables. When one variable changes, the overall state has changed.

Variables are the names your program assigns to the results of an expression. Every variable is created with an initial value. Variables will change to identify new objects and the objects identified by a variable can change their internal state. These three kinds of state changes (variable creation, object assignment, object change) happen as inputs are accepted and our program evaluates expressions. Eventually the state of the variables indicates that we are done, and our program can exit.

A Python variable name must be at least one letter, and can have a string of numbers, letters and ‘s to any length. Names that start with or have special significance. Names that begin with are typically private to a module or class. We’ll return to this notion of privacy in Classes and Modules. Names that begin with are part of the way the Python interpreter is built.

Example variable names:

Tip

Tracing Execution

We can trace the execution of a program by simply following the changes of value of all the variables in the program. For programming newbies, it helps to create a list of variables and write down their changes when studying a program. We’ll show an example in the next section.

Python creates new objects as the result of evaluating an expression. Python assigns these objects to new variables with an assignment statement. Python removes variables with a del statement. The underlying object is later garbage-collected when there are no more variables referring to the object.

Some Consequences. A Python variable is little more than a name which refers to an object. The central issue is to recognize that the underlying object is the essential part of our program; a variable name is just a meaningful label. This has a number of important consequences.

One consequence of a variable being simply a label is that any number of variables can refer to the same object. In other languages (C, C++, Java) there are two kinds of values: primitive and objects, and there are distinct rules for handling the two kinds of values. In Python, every variable is a simple reference to an underlying object. When talking about simple immutable objects, like the number 3, multiple variables referring to a common object is functionally equivalent to having a distinct copy of a primitive value. When talking about mutable objects, like lists, mappings, or complex objects, distinct variable references can change the state of the common object.

Another consequences is that the Python object fully defines it’s own type. The object’s type defines the representation, the range of values and the allowed operations on the object. The type is established when the object is created. For example, floating point addition and long integer objects have different representations, operations of adding these kinds of numbers are different, the objects created by addition are of distinct types. Python uses the type information to choose which addition operation to perform on two values. In the case of an expression with mixed types Python uses the type information to coerce one or both values to a common type.

This also means the “casting” an object to match the declared type of a variable isn’t meaningful in Python. You don’t use C++ or Java-style casting.

We’ve already worked with the four numeric types: plain integers, long integers, floating point numbers and complex numbers. We’ve touched on the string type, also. There are several other built-in types that we will look at in detail in Data Structures. Plus, we can use class definitions to define new types to Python, something we’ll look at in Data + Processing = Objects.

We commonly say that a static language associates the type information with the variable. Only values of a certain type can be assigned to a given variable. Python, in contrast, is a dynamic language; a variable is just a label or tag attached to the object. Any variable can be associated with an object of any type.

The final consequence of variables referring to objects is that a variable’s scope can be independent of the object itself. This means that variables which are in distinct namespaces can refer to the same object. When a function completes execution and the namespace is deleted, the variables are deleted, and the number of variables referring to an object is reduced. Additional variables may still refer to an object, meaning that the object will continue to exist. When only one variable refers to an object, then removing the last variable removes the last reference to the object, and the object can be removed from memory.

Also note that expressions generally create new objects; if an object is not saved in a variable, it silently vanishes. We can safely ignore the results of a function.

Scope and Namespaces. A Python variable is a name which refers to an object. To be useful, each variable must have a scope of visibility. The scope is defined as the set of statements that can make use of this variable. A variable with global scope can be referenced anywhere. On the other hand, a variable with local scope can only be referenced in a limited suite of statements.

This notion of scope is essential to being able to keep a intellectual grip on a program. Programs of even moderate complexity need to keep pools of variables with separate scopes. This allows you to reuse variable names without risk of confusion from inadvertantly changing the value of a variable used elsewhere in a program.

Python collects variables into pools called namespaces . A new namespace is created as part of evaluating the body of a function or module, or creating a new object. Additionally, there is one global namespace. This means that each variable (and the state that it implies) is isolated to the execution of a single function or module. By separating all locally scoped variables into separate namespaces, we don’t have an endless clutter of global variables.

In the rare case that you need a global variable, the global statement is available to assign a variable to the global namespace.

When we introduce functions in Functions, classes in Classes and modules in Components, Modules and Packages, we’ll revisit this namespace technique for managing scope. In particular, see Functions and Namespaces for a digression on this.

apiaVeryLongNamea_name__str___hidden

The Assignment Statement¶

Assignment is fundamental to Python; it is how the objects created by an expression are preserved. We’ll look at the basic assignment statement, plus the augmented assignment statement. Later, in Multiple Assignment Statement, we’ll look at multiple assignment.

Basic Assignment¶

We create and change variables primarily with the assignment statement. This statement provides an expression and a variable name which will be used to label the value of the expression.

variable=expression

Here’s a short script that contains some examples of assignment statements.

example3.py

  1. We have an object, the number , which we assign to the variable .
  2. We have an expression , which creates a floating-point number, which we save in the variable .
  3. We have another expression, , which creates a floating-point number; we save this in so that we can print it. This script created three new variables.

Since this file is new, we’ll need to do the chmod +x example3.py once, after we create this file. Then, when we run this progam, we see the following.

#!/usr/bin/env python# Computer the value of a block of stockshares=150price=3+5.0/8.0value=shares*priceprintvalue

Augmented Assignment¶

Any of the usual arithmetic operations can be combined with assignment to create an augmented assignment statement.

For example, look at this augmented assignment statement:

This statement is a shorthand that means the same thing as the following:

Here’s a larger example

portfolio.py

First, we’ll do the chmod +x portfolio.py on this file. Then, when we run this progam, we see the following.

The other basic math operations can be used similarly, although the purpose gets obscure for some operations. These include , , , , , , , and .

Here’s a lengthy example. This is an extension of Craps Odds in Numeric Types and Expressions.

In craps, the first roll of the dice is called the “come out roll”. This roll can be won immediately if the number is 7 or 11. It can be lost immediately if the number is 2, 3 or 12. All of the remaining numbers will establish a point and the game continues.

craps.py

There’s a 22.2% chance of winning, and a 11.1% chance of losing. What’s the chance of establishing a point? One way is to figure that it’s what’s left after winning or loosing. The total of all probabilities always add to 1. Subtract the odds of winning and the odds of losing and what’s left is the odds of setting a point.

Here’s another way to figure the odds of rolling 4, 5, 6, 8, 9 or 10.

By the way, you can add the statement to confirm that these odds all add to 1. This means that we have defined all possible outcomes for the come out roll in craps.

Tip

Tracing Execution

We can trace the execution of a program by simply following the changes of value of all the variables in the program.

We can step through the planned execution of our Python source statements, writing down the variables and their values on a sheet of paper. From this, we can see the state of our calculation evolve.

When we encounter an assignment statement, we look on our paper for the variable. If we find the variable, we put a line through the old value and write down the new value. If we don’t find the variable, we add it to our page with the initial value.

Here’s our example from craps.py script through the first part of the script. The variable was created and set to , then the value was replaced with , and then replaced with . The variable was then created and set to . This is what our trace looks like so far.

win:0.00.160.22
lose:0  

Here’s our example when craps.py script is finished. We changed the variable several times. We also added and changed the variable .

win:0.00.160.22 
lose:0.00.0270.0830.111
point:1.00.770.66 

We can use this trace technique to understand what a program means and how it proceeds from its initial state to its final state.

As with many things Python, there is some additional subtlety to assignment, but we’ll cover those topics later. For example, multiple-assignment statement is something we’ll look into in more deeply in Tuples.

#!/usr/bin/env python# Total value of a portfolio made up of two blocks of stockportfolio=0portfolio+=150*2+1/4.0portfolio+=75*1+7/8.0printportfolio
#!/usr/bin/env python# Compute the odds of winning on the first rollwin=0win+=6/36.0# ways to roll a 7win+=2/36.0# ways to roll an 11print"first roll win",win# Compute the odds of losing on the first rolllose=0lose+=1/36.0# ways to roll 2lose+=2/36.0# ways to roll 3lose+=1/36.0# ways to roll 12print"first roll lose",lose# Compute the odds of rolling a point number (4, 5, 6, 8, 9 or 10)point=1# odds must total to 1point-=win# remove odds of winningpoint-=lose# remove odds of lostingprint"first roll establishes a point",point
point=0point+=2*3/36.0# ways to roll 4 or 10point+=2*4/36.0# ways to roll 5 or 9point+=2*5/36.0# ways to roll 6 or 8printpoint

Input Functions¶

Python provides two simplistic built-in functions to accept input and set the value of variables. These are not really suitable for a complete application, but will do for our initial explorations.

Typically, interactive programs which run on a desktop use a complete graphic user interface (GUI), often written with the module or the module. Interactive programs which run over the Internet use HTML forms.

The primitive interactions we’re showing with and are only suitable for very simple programs.

Important

Python 3.x

In Python 3, the function will be renamed to .

The Python 2 function will be removed. It’s that useless.

Note that some IDE’s buffer the program’s output, making these functions appear to misbehave. For example, if you use Komodo, you’ll need to use the “Run in a New Console” option. If you use BBEdit, you’ll have to use the “Run in Terminal” option.

You can enhance these functions somewhat by including the statement . This module silently and automatically enhances these input functions to give the user the ability to scroll backwards and reuse previous inputs.

You can also . This module allows you to define sophisticated keyword auto-completion for these functions.

The Function¶

The first way to get interactive input is the function. This function accepts a string parameter, which is the user’s prompt, written to standard output. The next line available on standard input is returned as the value of the function.

([prompt]) → string¶

If a prompt is present, it is written to .

Input is read from and returned as a string.

The function reads from a file often called . When running from the command-line, this will be the keyboard, and what you type will be echoed in the command window or Terminal window. If you try, however, to run these examples from Textpad, you’ll see that Textpad doesn’t have any place for you to type any input. In BBEdit, you’ll need to use the item in the menu.

Here’s an example script that uses .

rawdemo.py

When we run this script from the shell prompt, it looks like the following.

MacBook-3:Examples slott$ python rawdemo.py yes?why not? you said why not?
  1. This program begins by evaluating the function. When is applied to the parameter of , it writes the prompt on standard output, and waits for a line of input.
    1. We entered .
    2. Once that line was complete, the input string is returned as the value of the function.
    3. The function’s value was assigned to the variable .
  2. The second statement printed that variable along with some text.

If we want numeric input, we must convert the resulting string to a number.

stock.py

We’ll chmod +x stock.py this program; then we can run it as many times as we like to get results.

MacBook-3:Examples slott$ ./stock.py shares: 150 dollars: 24 eights: 3 value 3656.25

The mechanism is very limited. If the string returned by is not suitable for use by , an exception is raised and the program stops running. We’ll cover exception handling in detail in Exceptions.

As a teaser, here’s what it looks like.

MacBook-5:Examples slott$ python stock.py shares: a bunch Traceback (most recent call last): File "stock.py", line 3, in <module> shares = int( raw_input("shares: ") ) ValueError: invalid literal for int() with base 10: 'a bunch'
#!/usr/bin/env python# show how raw_input worksa=raw_input("yes?")print"you said",a
#!/usr/bin/env python# Compute the value of a block of stockshares=int(raw_input("shares: "))price=float(raw_input("dollars: "))price+=float(raw_input("eights: "))/8.0print"value",shares*price

The Function¶

In addition to the function, which returns the exact string of characters, there is the function. This applies the function to the input, which will typically convert numeric input to the appropriate objects.

Important

Python 3

This function will be removed. It’s best not to make use of it.

The value of the function is .

Multiple Assignment Statement¶

The basic assignment statement can do more than assign the result of a single expression to a single variable. The assignment satement can also assign multiple variables at one time.

The essential rule is that the left and right side must have the same number of elements.

For example, the following script has several examples of multiple assignment.

line.py

When we run this program, we get the following output

MacBook-3:Examples slott$ ./line.py y = 1.25 *x+ 0.5

We set variables , , and . Then we computed and from those four variables. Then we printed the and .

The basic rule is that Python evaluates the entire right-hand side of the = statement. Then it matches values with destinations on the left-hand side. If the lists are different lengths, an exception is raised and the program stops.

Because of the complete evaluation of the right-hand side, the following construct works nicely to swap to variables. This is often quite a bit more complicated in other languages.

We’ll return to this in Tuples, where we’ll see additional uses for this feature.

#!/usr/bin/env python# Compute line between two points.x1,y1=2,3# point onex2,y2=6,8# point twom,b=float(y1-y2)/(x1-x2),y1-float(y1-y2)/(x1-x2)*x1print"y=",m,"*x+",b
a,b=1,4b,a=a,bprinta,b

The del Statement¶

An assignment statement creates or locates a variable and then assigns a new object to the variable. This change in state is how our program advances from beginning to termination. Python also provides a mechanism for removing variables, the del statement.

The del statement looks like this:

delobject 〈 , ... 〉

Each object is any kind of Python object. Usually these are variables, but they can be functions, modules or classes.

The del statement works by unbinding the name, removing it from the set of names known to the Python interpreter. If this variable was the last remaining reference to an object, the object will be removed from memory. If, on the other hand, other variables still refer to this object, the object won’t be deleted.

The del statement is typically used only in rare, specialized cases. Ordinary namespace management and garbage collection are generally sufficient for most purposes.

Interactive Mode Revisited¶

When we first looked at interactive Python in Command-Line Interaction we noted that Python executes assignment statements silently, but prints the results of an expression statement. Consider the following example.

The first two inputs are complete statements, so there is no response. The third input is just an expression, so there is a response.

It isn’t obvious, but the value assigned to isn’t correct. Because we didn’t see anything displayed, we didn’t get any feedback from our computation of .

Python, however, has a handy way to help us. When we type a simple expression in interactive Python, it secretly assigns the result to a temporary variable named . This isn’t a part of scripting, but is a handy feature of an interactive session.

This comes in handy when exploring something rather complex. Consider this interactive session. We evaluate a couple of expressions, each of which is implicitly assigned to . We can then save the value of in a second variable with an easier-to-remember name, like or .

Note that we created a floating point object (2.964...), and Python secretly assigned this object to . Then, we computed a new floating point object (3.141...), which Python assigned to .

What happened to the first float, 2.964...? Python garbage-collected this object, removing it from memory.

The second float that we created (3.141) was assigned to . We then assigned it to , also, giving us two references to the object. When we computed another floating-point value (15.205...), this was assigned to .

Does this mean our second float, 3.141... was garbage collected? No, it wasn’t garbage collected; it was still referenced by the variable .

>>> pi=355/113.0>>> area=pi*2.2**2>>> area15.205309734513278
>>> 335/113.02.9646017699115044>>> 355/113.03.1415929203539825>>> pi=_>>> pi*2.2**215.205309734513278>>> area=_>>> area15.205309734513278

Variables, Assignment and Input Function Exercises¶

Variables and Assignment¶

  1. Extend Previous Exercises. Rework the exercises in Numeric Types and Expressions.

    Each of the previous exercises can be rewritten to use variables instead of expressions using only constants. For example, if you want to tackle the Fahrenheit to Celsius problem, you might write something like this:

    You’ll want to rewrite these exercises using variables to get ready to add input functions.

    #!/usr/bib/env python# Convert 8 C to FC=8F=32+C*(9./5.)print"celsius",C,"fahrenheit",F
  2. State Change. Is it true that all programs simply establish a state?

    It can argued that a controller for a device (like a toaster or a cruise control) simply maintains a steady state. The notion of state change as a program moves toward completion doesn’t apply because the software is always on. Is this the case, or does the software controlling a device have internal state changes?

    For example, consider a toaster with a thermostat, a “browness” sensor and a single heating element. What are the inputs? What are the outputs? Are there internal states while the toaster is making toast?

Input Functions¶

Refer back to the exercises in Numeric Types and Expressions for formulas and other details. Each of these can be rewritten to use variables and an input conversion. For example, if you want to tackle the Fahrenheit to Celsius problem, you might write something like this:

  1. Stock Value. Input the number of shares, dollar price and number of 8th’s. From these three inputs, compute the total dollar value of the block of stock.

  2. Convert from |deg| C to |deg| F. Write a short program that will input ° C and output ° F. A second program will input ° F and output ° C.

  3. Periodic Payment. Input the principal, annual percentage rate and number of payments. Compute the monthly payment. Be sure to divide rate by 12 and multiple payments by 12.

  4. Surface Air Consumption Rate. Write a short program will input the starting pressure, final pressure, time and maximum depth. Compute and print the SACR.

    A second program will input a SACR, starting pressure, final pressure and depth. It will print the time at that depth, and the time at 10 feet more depth.

  5. Wind Chill. Input a temperature and a wind speed. Output the wind chill.

  6. Force from a Sail. Input the height of the sail and the length. The surface area is 1/2 × h × l. For a wind speed of 25 MPH, compute the force on the sail. Small boat sails are 25-35 feet high and 6-10 feet long.

C=raw_input('Celsius: ')F=32+C*(9./5.)print"celsius",C,"fahrenheit",F

Variables and Assignment Style Notes¶

Spaces are used sparingly in Python. It is common to put spaces around the assignment operator. The recommended style is

Do not take great pains to line up assignment operators vertically. The following has too much space, and is hard to read, even though it is fussily aligned.

This is considered poor form because Python takes a lot of its look from natural languages and mathematics. This kind of horizontal whitespace is hard to follow: it can get difficult to be sure which expression lines up with which variable. Python programs are meant to be reasonably compact, more like reading a short narrative paragraph or short mathematical formula than reading a page-sized UML diagram.

Variable names are often given as ; variable names typically begin with lower-case letters. The style is also used, but is less popular.

In addition, the following special forms using leading or trailing underscores are recognized:

  • : used to avoid conflicts with Python keywords. For example:
  • : used for special objects or attributes, e.g. , or . These names are reserved; do not use names like these in your programs unless you specifically mean a particular built-in feature of Python.
  • : means that the variable is “private”.
a=12b=a*math.log(a)aVeryLongVariable=26d=13


In this section, you will be introduced to two different kinds of data in Python: variables and strings. Please follow along by running the included programs and examining their output.

Variables[edit]

A variable is something that holds a value that may change. In simplest terms, a variable is just a box that you can put stuff in. You can use variables to store all kinds of stuff, but for now, we are just going to look at storing numbers in variables.

lucky=7print(lucky)7

This code creates a variable called , and assigns to it the integer number . When we ask Python to tell us what is stored in the variable , it returns that number again.

We can also change what is inside a variable. For example:

changing=3print(changing)3changing=9print(changing)9different=12print(different)12print(changing)9changing=15print(changing)15

We declare a variable called , put the integer in it, and verify that the assignment was properly done. Then, we assign the integer to , and ask again what is stored in . Python has thrown away the , and has replaced it with . Next, we create a second variable, which we call , and put in it. Now we have two independent variables, and , that hold different information, i.e., assigning a new value to one of them is not affecting the other.

You can also assign the value of a variable to be the value of another variable. For example:

red=5blue=10print(red,blue)510yellow=redprint(yellow,red,blue)5510red=blueprint(yellow,red,blue)51010

To understand this code, keep in mind that the name of the variable is always on the left side of the equals sign (the assignment operator), and the value of the variable on the right side of the equals sign. First the name, then the value.

We start out declaring that is , and is . As you can see, you can pass several arguments to to tell it to print multiple items on one line, separating them by spaces. As expected, Python reports that stores , and holds .

Now we create a third variable, called . To set its value, we tell Python that we want to be whatever is. (Remember: name to the left, value to the right.) Python knows that is , so it also sets to be .

Now we're going to take the variable, and set it to the value of the variable. Don't get confused — name on the left, value on the right. Python looks up the value of , and finds that it is . So, Python throws away 's old value (), and replaces it with . After this assignment Python reports that is , is , and is .

But didn't we say that should be whatever value is? The reason that is still when is , is because we only said that should be whatever is at the moment of the assignment. After Python has figured out what is and assigned that value to , doesn't care about any more. has a value now, and that value is going to stay the same no matter what happens to .

Note:
The interplay between different variables in Python is, in fact, more complex than explained here. The above example works with integer numbers and with all other basic data types built into Python; the behavior of and (you will encounter these complex data types later) is entirely different, though. You may read the chapter on data types for a more detailed explanation of what variables really are in Python and how their type affects their behavior. However, it is probably sufficient for now if you just keep this in mind: whenever you are declaring variables or changing their values, you always write the name of the variable on the left of the equals sign (the assignment operator), and the value you wish to assign to it on the right.

String[edit]

A 'string' is simply a list of characters in order. A character is anything you can type on the keyboard in one keystroke, like a letter, a number, or a backslash. For example, "" is a string. It is five characters long — , , , , . Strings can also have spaces: "" contains 11 characters, including the space between "" and "". There are no limits to the number of characters you can have in a string — you can have anywhere from one to a million or more. You can even have a string that has 0 characters, which is usually called "the empty string."

There are three ways you can declare a string in Python: single quotes (), double quotes (), and triple quotes (). In all cases, you start and end the string with your chosen string declaration. For example:

>>>print('I am a single quoted string')Iamasinglequotedstring>>>print("I am a double quoted string")Iamadoublequotedstring>>>print("""I am a triple quoted string""")Iamatriplequotedstring

You can use quotation marks within strings by placing a backslash directly before them, so that Python knows you want to include the quotation marks in the string, instead of ending the string there. Placing a backslash directly before another symbol like this is known as escaping the symbol. Note that if you want to put a backslash into the string, you also have to escape the backslash, to tell Python that you want to include the backslash, rather than using it as an escape character.

>>>print("So I said, \"You don't know me! You'll never understand me!\"")SoIsaid,"You don't know me! You'll never understand me!">>>print('So I said, "You don\'t know me! You\'ll never understand me!"')SoIsaid,"You don't know me! You'll never understand me!">>>print("This will result in only three backslashes: \\\\\\")Thiswillresultinonlythreebackslashes: \ \ \ >>>print("""The double quotation mark (\") is used to indicate direct quotations.""")Thedoublequotationmark(") is used to indicate direct quotations.

As you can see from the above examples, only the specific character used to quote the string needs to be escaped. This makes for more readable code.

To see how to use strings, let's go back for a moment to an old, familiar program:

>>>print("Hello, world!")Hello,world!

Look at that! You've been using strings since the beginning! You can also add two strings together using the operator: this is called concatenating them.

>>>print("Hello, "+"world!")Hello,world!

Notice that there is a space at the end of the first string. If you don't put that in, the two words will run together, and you'll end up with

You can also repeat strings by using the operator, like so:

>>>print("bouncy, "*10)bouncy,bouncy,bouncy,bouncy,bouncy,bouncy,bouncy,bouncy,bouncy,bouncy,

If you want to find out how long a string is, you use the function, which simply takes a string and counts the number of characters in it. ( stands for "length.") Just put the string that you want to find the length of, inside the parentheses of the function. For example:

>>>print(len("Hello, world!"))13

Strings and Variables[edit]

Now that you've learned about variables and strings separately, let's see how they work together.

Variables can store much more than just numbers. You can also use them to store strings! Here's how:

question="What did you have for lunch?"print(question)

In this program, we are creating a variable called , and storing the string "" in it. Then, we just tell Python to print out whatever is inside the variable. Notice that when we tell Python to print out , there are no quotation marks around the word : this is to signify that we are using a variable, instead of a string. If we put in quotation marks around , Python would treat it as a string, and simply print out instead of .

Let's try something different. Sure, it's all fine and dandy to ask the user what they had for lunch, but it doesn't make much difference if they can't respond! Let's edit this program so that the user can type in what they ate.

question="What did you have for lunch?"print(question)answer=raw_input()#You should use "input()" in python 3.x, because python 3.x doesn't have a function named "raw_input".print("You had "+answer+"! That sounds delicious!")

To ask the user to write something, we used a function called , which waits until the user writes something and presses enter, and then returns what the user wrote. Don't forget the parentheses! Even though there's nothing inside of them, they're still important, and Python will give you an error if you don't put them in. You can also use a different function called , which works in nearly the same way. We will learn the differences between these two functions later.

Note:
In Python 3.x was renamed to . That is, the new function reads a line from and returns it without the trailing newline. It raises if the input is terminated prematurely (e.g. by pressing Ctrl+D). To get the old behavior of , use .

In this program, we created a variable called , and put whatever the user wrote into it. Then, we print out a new string, which contains whatever the user wrote. Notice the extra space at the end of the " " string, and the exclamation mark at the start of the "" string. They help format the output and make it look nice, so that the strings don't all run together.

Combining Numbers and Strings[edit]

Take a look at this program, and see if you can figure out what it's supposed to do.

print("Please give me a number: ")number=raw_input()plusTen=number+10print("If we add 10 to your number, we get "+plusTen)

This program should take a number from the user, add 10 to it, and print out the result. But if you try running it, it won't work! You'll get an error that looks like this:

Traceback (most recent call last): File "test.py", line 7, in <module> print "If we add 10 to your number, we get " + plusTen TypeError: cannot concatenate 'str' and 'int' objects

What's going on here? Python is telling us that there is a , which means there is a problem with the types of information being used. Specifically, Python can't figure out how to reconcile the two types of data that are being used simultaneously: integers and strings. For example, Python thinks that the variable is holding a string, instead of a number. If the user enters , then will contain a string that is two characters long: a , followed by a . So how can we tell Python that should be a number, instead of a string?

Also, when printing out the answer, we are telling Python to concatenate together a string (" ") and a number (). Python doesn't know how to do that -- it can only concatenate strings together. How do we tell Python to treat a number as a string, so that we can print it out with another string?

Luckily, there are two functions that are perfect solutions for these problems. The function will take a string and turn it into an integer, while the function will take an integer and turn it into a string. In both cases, we put what we want to change inside the parentheses. Therefore, our modified program will look like this:

print("Please give me a number:",)response=raw_input()number=int(response)plusTen=number+10print("If we add 10 to your number, we get "+str(plusTen))

Note:
Another way of doing the same is to add a comma after the string part and then the number variable, like this:

print("If we add 10 to your number, we get ",plusTen)

or use special print formatting like this:

print("If we add 10 to your number, we get %s"%plusTen)

which alternative can be written this way, if you have multiple inputs:

plusTwenty=number+20print("If we add 10 and 20 to your number, we get %s and %s"%(plusTen,plusTwenty))

or use format()

print("If we add 10 to your number, we get {0}".format(plusTen))

That's all you need to know about strings and variables! We'll learn more about types later.

List of Learned Functions[edit]

  • : Prints its parameter to the console.
  • or : asks the user for a response, and returns that response. (Note that in version 3.x does not exist and has been replaced by )
  • : returns the length of a string (number of characters)
  • : returns the string representation of an object
  • : given a string or number, returns an integer

Note:

  1. input and raw_input function accept a string as parameter. This string will be displayed on the prompt while waiting for the user input.
  2. The difference between the two is that raw_input accepts the data coming from the input device as a raw string, while input accepts the data and evaluates it into python code. This is why using input as a way to get a user string value returns an error because the user needs to enter strings with quotes.

It is recommended to use raw_input at all times and use the int function to convert the raw string into an integer. This way we do not have to bother with error messages until the error handling chapter and will not make a security vulnerability in your code.

Exercises[edit]

  1. Write a program that asks the user to type in a string, and then tells the user how long that string was.
  2. Ask the user for a string, and then for a number. Print out that string, that many times. (For example, if the string is and the number is you should print out .)
  3. What would happen if a mischievous user typed in a word when you ask for a number? Try it.

Solutions

Quiz

0 Replies to “Parallel Assignment In Python Convert”

Lascia un Commento

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *