Operators and expressions
From Wikiversity
[edit] Assignment and TypingAssignment is setting a variable to a value. Like common mathematics, most languages use a simple equal sign (there are exceptions, e.g. in Pascal, the ":=" operator is used for assignment) a = 5 blah = "A string" Note that, in statically typed languages, you cannot change the type of a declared variable at run-time, e.g. : int a = 5 // We declare a variable "a" of type integer a = "Blah" // ERROR ! "a" type can't be changed to a String ! is invalid in C, C++, Java. Dynamically typed languages, such as Python, Ruby, and most scripting languages (e.g. Lua) don't have this limitation. "Traditional" programmers sometimes think that dynamically typed languages leads to a worse design, but in the end which language you should use is a matter of personal tastes and the requirements for your project. |
[edit] Arithmetic OperationsThe simple operations like additions and subtraction are exactly the same as in common math. a = 2 + 5 (a equals 7) b = 4 - 3 (b equals 1) For operations like multiplication and division, the operators are slightly different than standard mathematics, to avoid confusion with other symbols. Multiplication is denoted by an asterisk (*), and division by a slash (/). m = 3 * 5 (m equals 15) d = 20 / 5 (d equals 4) |
[edit] Boolean ExpressionsBoolean refers to expressions that can take either a "true" or a "false" value. Since computers are electrical in nature, true usually takes on the value of flowing current, or the numeric value 1, while false is the absence of current, denoted as a 0. The following table illustrates how the values can be combined to achieve results. In an AND expression, both expressions must be true for the evaluation to be true, while in an OR expression either or both values being true will cause the evaluation to be true. XOR means "exclusive OR", it will be true only if one OR the other, but NOT both are true.
NOT is the inversion, or opposite, of the input value. This makes a true value false, and a false value true. Common operators for NOT in programming languages are "!" and "~". !0 == 1 !1 == 0 By combining these elements in various ways, we are able to make fairly complex decisions break down to true or false values. |