## Fundamentals of Programming I: Statements and Expressions. # By Chuck Liang, for CSC 15, Hofstra University # Program "source code" in a language such a Python consists of *statements* or # *commands*. A statement/command is a directive for the computer to perform # some action. In order to form statements, however, we also need *expressions* # or *values*. For example: print("hello") # This line is a statement that does something obvious. Here, "hello" is # an expression. The difference between statements and expressions is # analogous to the difference between sentences and nouns in natural # language. In the context of this analogy *print* would be the verb. # The parentheses () are necessary in Python3 (optional in Python2). # Python is case sensitive. x = 3+1 # assigns 4 to memory location associated with x, prints nothing # This is another statement: it instructs the system to calculate the # value 4 and *assign* it to a variable named x; in other words to store # 4 into a certain memory location it will associate with x. In this # statement the expressions are x and 3+1. Note that 3+1 by itself is # not a statement. It does calculate 4, but 4 is also not a statement: # we need to put this *value* into something else in order to make it a # statement. Please note that this statement prints nothing, even in the # interactive interpreter. # we are used to reading the = symbol as "equals", but in fact, the = # symbol in python (and many other languages) does not represent mathematical # equality (which is ==). Rather it represents storing a value in a memory # location. In particular: # 3+1 = x # is NOT a valid statement. The variable (representing a memory location) # that's being written to must be on the left-hand side of the = symbol. x = x+1 # The above statement may cause your math professor to start cursing # computer science for the rest of the day. Please explain to him or her # that it doesn't mean that 4 is "equal" to 5, but rather that the value of # x is increased by 1 and re-written to the same memory location associated # with x. That is, x was assigned to 4 above, but now: print("x is now", x) # x is now 5 # EXERCISE 1: consider the following statements executed in turn: x = 2 y = 4 x = y y = x # At this point, what are the values stored in x and in y? That is, # what would print(x,y) actually print? print(x,y) # guess what will be printed here before running this program # EXERCISE 1b. # If you had guessed that the statements x=y followed by y=x would swap # the values of x and y, you'd be wrong. Devise another sequence of # statements that WOULD always swap the values of x and y (regardless or # their initial values). You may use up to three assignment statements ### Hint: the easiest way is to use a third variable ### Challenge: swap x and y WITHOUT using a third variable. ################# ## Expressions/values come in many different forms or *types*. Understanding # the exact type of an expression is very important. Furthermore, each # type of expression can be divided into primitive and compound expressions. # I list the principal types that you need to know, along with examples: ## 0. Integer expressions: 3, 3+4, 3-2*5, etc. are all integer expressions. # if you assign an integer expression to a variable, such as with x=2, then x # is also an integer expression. * represents multiplication and // represents # integer division. 1//2 is 0, not 0.5. Applying the // operation to two # integers always results in an integer (the quotient, without the remainder). # A particularly important kind of integer expression # is formed with the % operator (called the mod operator). 5%2 returns the # remainder after dividing 5 by 2 (which is 1). The expression 5//2 # returns 2, the quotient without the remainder. The % operator is extremely # important to understand. In Python, x % n, will always give an integer # between 0 and n-1. Say you want to increment a value x, but have it wrap # around back to 0 if it gets to 10, you would write x = (x+1)%10. ## 1. Floating point expressions: 3.14, 2.0, etc.. # The expression 5/2, will give you a "floating point" expression (2.5). # These are numbers with decimal points, and are often called "doubles". # In math, 2.0 and 2 are the same. However, inside a computer, they're # represented very differently. 2.0+3.0 and 2+3 perform different operations. # When you perform an arithmetic operation between two integers, you always # get an integer, and this includes 2//3, which is the integer 0. The # only exception here is division, which always returns a float (4/2 will # return 2.0). When you mix a float with an int, it will also return a # float. For example, to convert an integer x to a float, you can just # write 1.0*x. The expression float(x) will give the same value. # To convert a float into an int, use int(2.0). print( 1//int(2.0) ) # prints 0 print( 1//float(2) ) # prints 0.5 # Here, int(2.0) is an operation that converts a float to an int. int(2.0) # has the same value as the integer 2, and analogously for float(2). print( int(3.9) ) # prints 3 - the decimal part is discarded. print( int(3.9+0.5) ) # prints 4 - always add .5 if you want to round off. # As you can see, int will always return the integer part of the floating # value. So to round off, just add 0.5 first (so 3.5 becomes 4 but 3.4 will # become 3). # EXERCISE 2 (slight challenge): without using any built in operations # other than int, float, +, * and / (along with assignment operator # =), devise an algorithm to round off a floating point number to the # nearest 1/100th. For example, 4.248 should be rounded off to 4.25. pi = 3.141592653589 euler = 2.71828 # Add code here to demonstrate your algorithm so that print(pi) # would print 3.14 print(euler) # would print 2.72 ########################### ## 2. String expressions: "hello world", "12", "fazs3r3**(()", "" # Strings are just sequences of zero or more characters that are taken # as-is. Do not confuse "12" with the integer 12. "12" is just a # sequence of two characters. If you type "12"+3, do not expect 15! # However, there are also operations to convert strings to and from other # types. Try to generalize the operations demonstrated as follows: print( "12"+str(3) ) # what do you expect here? (run to confirm) print( int("12")+3 ) # what do you expect here? # As you can see, when + is used as an operator between two strings, it # *concatenates* them. # One particularly important string is the empty string "". Do not confuse # the empty string with " ", which is a string that consists of one character: # the space character. # In Python, sometimes strings are displayed using single quotes: 'abc'. # What if you want the character " in a string? do this: print( "say \"hello\" to him" ) # OK that was easy, but what if you want to include the \ character as well? print( "who needs \\ in a string anyway" ) # \ is called the "escape character." # Another way to convert a string to a value is to use eval: print(eval("3+2")) # will actually return the integer 5. x,y = eval(input("enter a pair of values separated by , ")) print("you entered a tuple: ",x,y) # Note: The eval operateion is something that can be easily misused and you # will only see me use it to convert input tuples. ### 3. Variables. # Variables are important kinds of expressions. The type of a variable is # the same as the type of value that it's assigned to. x = "abc" # x is now of type string print(x) x = 14 # x is now of type int print(x+1) # x was first assigned to a string, and therefore can be used as a string # expression until it is assigned to something of different type. # Quiz: what will the following print? x = 1 x+1 print(x) # Answer: it will print 1, because x+1 is not the same as x=x+1. # The names of variables can be consists of more than one letter (see pi, euler # above), but the first letter should be a number. ## 4. Boolean Expressions. # This is a fundamentally important type of value in any programming # language, though a little harder to understand than numbers and strings. # A boolean value is either True or False (capitalized T and F). These values # are actually equivalent to 1 (for True) and 0 (for False). So 2+True is actually # equivalent to 3, which can be confusing, so we prefer to use True and False. # All compound boolean expressions eventually evaluate to either True or False. # Here are some sample boolean expressions and what they evaluate to: 3<4 # True 4>4 # False 4>=4 # True: >= means greater than or equal to, <= is less than or equal to 3+1 == 4 # True: note that "==" means "boolean equality", which is not # the same as "=", which is used to form an assignment statement. 13%2==1 # True because 13 is an odd number "abc" != "ABC" # True: Python is case sensitive, and != means "not equal" # Compound boolean expressions are formed as follows 3<4 and 3>0 # True because both are true 3<4 or 3>4 # True or means either or BOTH is true. 1<2 or 2<3 # True not(1<2) # False: because 1<2 is True. not inverts the boolean value. # As another example, assume that x and y are two integer variables, then # the boolean expression x != y is equivalent to not(x==y), which is also # equivalent to (x0 and x<=10). ## EXERCISE 3: let h be a value representing a time in hour of the day: # for example h==9 represents 9am, h==14 represents 2pm. Devise # a boolean expression to express the time constraint: # "h is between 10am and 1pm or between 4pm and 6pm" ## EXERCISE 3b: (slight challenge): a year is a leap year if it is evenly # divisible by four "except for centennial years not divisible by 400." # A centennial year is a year that's divisible by 100. For example, year # 2000 is a leap year but year 2100 is not a leap year. Given an integer # year value y, y%4==0 if y is divisible by 4. Write statements to assign # True to a variable named ly if y is a leap year, and assign False to ly if # y is not a leap year. For those with programming experience, you're NOT # allowed to use if-statements. y = int(input("enter year: ")) leapyear = (y%4==0) # but this is not enough... ############ ### When do you need spaces? Expressions such as x<=0 and x <= 0 are the # same. But do not use x < = 0 because <= is ONE symbol. Usually, symbols are # divided into "alphanumeric" and non-alphanumeric. An alphanumeric word # consists of one or more alphabetical (upper or lower case) characters and # numerical digits. For example, x2ab3d is alphanumeric, and can # be used as the name of a variable. Non-alphanumeric symbols include # ==, =, <=, %, etc. In general, use spaces between different # alphanumeric symbols. For example, what's wrong with 010 ? Spaces # are needed to separate the alphanumeric symbols 'x', 'or', and 'y'. So # this should be written as 010. However, there does not need to # be spaces between alphanumeric and non-alphanumeric symbols: 0