Variables in Python
Variables in Python
Hi, and welcome back to Python 101. In the second chapter of this course, we will have a look at variables, operators and simple I/O.
- Programs you'll be able to compose by the end of this chapter: Fill the form, Odd or even, Leap year or not.
- Variables: String, number, floating point, Boolean, assignment statements, identifiers, guidelines for naming variables.
- All about strings: Using quotes inside strings, verbatim strings, escape sequences, concatenating and repeating strings, line continuation, immutability, nesting quotes, string methods, calculating the length of a string.
- More about print: Printing multiple values, ending print statement with a desired character.
- Numeric data types: int, float, complex, arithmetic operators.
- Boolean data type: boolean operators.
- A Few General Things: getting user input with input(), casting: type conversions(string to int, int to string, string to float), comparison operators.
- Controlling the flow of the program: Introduction to how to control the flow of the program, branching: if construct.
- On the agenda in next chapter
What you'll be able to make by the end of this chapter§
Let's have a look at the programs you will be able to materialize by the end of this chapter...
#1 Fill the form
## Fill the form ## THOUGHT PROCESS: Prompt the user for a few questions -> Place the answers in variables, convert the data types wherever needed -> print the variables in a neat layout. name = input("Enter your name: ") age = input("Enter your age: ") age = int(age) email = input("Enter your email address: ") print("Name\t\t:\t", name.upper()) print("Age\t\t:\t", age) print("Email\t\t:\t", email.upper())
#2 Odd or even number?
## Determine whether the given integer is even or odd. Even numbers are multiples of 2, whereas odd numbers are not. ## THOUGHT PROCESS: Prompt the user for a number -> place the answer in a variable, convert the data type -> operate on number turn by turn using if statement, print even if even, else print odd. # Input from user number = int(input("Enter a number to be tested: ")) # Logic: determining odd/even status using the modulus arithmetic operator if number % 2 == 0: print(number, "is even.") else: print(number, "is odd.")
#3 Leap Year or not?
## Program to determine whether a given year is a leap year or not. A leap year is one with 29 days in the month of February, and mathematically, it is a multiple of 400 or 100 or 4. ## THOUGHT PROCESS: Prompt the user for an year -> cast the input into an integer -> set a default flag for later use -> operate on number turn by turn using if statement, set flag accordingly -> use the flag to print the correct conclusion. # Take the input from the user year = int(input("Enter an year: ")) isAleapYear = False # this variable serves as a flag in the program i.e. its value will be either true or false based on conditions, and at some point in the program, this flag will decide the flow of the program i.e. which statements to execute and which ones to skip according to its value. Since Python is an interpreted language, any variable we use inside the program needs to be declared beforehand so that the interpreter knows that there is a variable by this name. We can initialize it with the wrong value, it just needs to be in the memory so that the interpreter can recognize it. We can declare this variable anywhere before its use, but the convention is to declare variables at the top, before the actual logic, for easy code walkthrough. # Determine whether the supplied year is a leap year or not if year % 400 == 0: isAleapYear = True elif year % 100 == 0: isAleapYear = True elif year % 4 == 0: isAleapYear = True else: isALeapYear = False # Printing the result if isAleapYear: print(year, "is a leap year.") else: print(year, "is not a leap year.")
- A variable is a container (say, a glass), that holds a value(say, water) that may change (say, coffee).
- Once a variable is assigned a value, the variable can be used in place of that value.
- Variables are stored in the memory of your computer. This memory space is vacated as soon as the program runs it full course (google 'Python Garbage Collection' for further study). To vacate this space while the program is still running, you may use the del keyword e.g. >>> del variable_name
- Python supports 4 primitive types of variables: string, integer, floating point, Boolean (complex numbers are also supported, but are not considered primitive). Apart from these, variables can also hold more complex data types like lists, sets, tuples and dictionaries, these are known as data structures. We will get to them in due time. For now, let's grapple with the fundamental ones: string, integer, floating point and Boolean.
- Declaring a variable is easy. Simply give your variable a name, followed by an equality sign(also called assignment operator), followed by the value you want your variable to hold.
>>> my_variable_1 = 'Hello' # a string variable >>> my_variable_2 = "Hellooooo" # another string variable >>> my_variable_3 = 23 # an integer variable >>> my_variable_4 = 23.0 # a floating point variable >>> my_variable_5 = True # a Boolean variable
All of the above are assignment statements, with variables on the left and values on the right
- As you can see, we do not specify any additional keyword to specify what kind of data is the variable going to hold. Python is smart, it deduces the data type based on the value we are assigning to the variable. You can check it yourself by using the builtin type function.
>>> type(my_variable_1) <class 'str'> >>> type(my_variable_2) <class 'str'> >>> type(my_variable_3) <class 'int'> >>> type(my_variable_4) <class 'float'> >>> type(my_variable_5) <class 'bool'>
- Each variable type i.e. str, int, float, bool, dict, tuple, list, set has a finite set of associated functions and attributes (properties) that can be called only on a particular type of variable e.g. a string variable is open to methods like upper(), lower(), title() etc. which are not applicable to an integer variable. Likewise, an integer variable has attributes like numerator and denominator that are not applicable to strings, so on and so forth.
- You can replace the existing value in a variable.
>>> variable_1 = "hi" >>> variable_1 = "hello" >>> print(variable_1) hello
- Variables need to be declared before they are referenced in the code, or else the interpreter raises a NameError exception. We will cover exceptions later.
Guidelines for naming a variable
There are two synonyms for variables: attributes & identifiers. From lexical point of view of the Python programming language(for that matter, any programming language), identifier is the name given to entities like class, functions, variables etc. It helps differentiating one entity from another and to refer them.
Following are the rules to make a valid identifier:
- it can be a combination of lowercase alphabet (a-z), uppercase alphabet (A-Z), digits (0-9) and underscore(_) e.g. my_variable, myVariable, myVar.
- it cannot begin with a digit i.e. myVar1 is fine but 1myVar is not.
- special symbols like $, #, !, % etc. are not allowed since they have special meanings in the language.
- there is no limit on the length of identifiers, but try to make them as readable as you can, keeping readability in mind.
- identifiers are case sensitive. so myVar and myvar are two different variables.
- identifiers should not be keywords i.e. you should not make a variable named print or True etc., as it will create problems when you want to the keyword True.
All about strings§
- A string is a sequence of characters, and a character is, well, you know what a character is. In literal terms, character is anything you can put on to the screen using your keyboard, like a letter, a number, a space, special symbols such as hash, percent etc. "Hello there!" is a string. It consists of 12 characters(5 + 1 + 5 + 1).
- Strings can be declared using an apostrophe/single quote('), double quotes("), 3 apostrophes(''') or 3 double quotes("""). You can use all these interchangeably, as long as you wrap your string with the same set of symbols i.e. if you cannot begin a string with a single quote and end with a double quote.
>>> stringOne = 'Hi there!' >>> stringOne 'Hi there!' >>> stringTwo = "Hello there!' >>> stringTwo 'Hello there!' >>> stringThree = '''Hi there from triple apostrophe strings!''' >>> stringThree 'Hi there from triple apostrophe strings!' >>> stringFour = """Hello from triple double quoted strings!""" >>> stringFour 'Hello from triple double quoted strings'
- As I said, you could either of these 4 ways to denote a string. The last two, the triple quoted strings may span multiple lines and Python won't generate any error, while in the first two cases, it will generate an error if you try to span them over multiple lines.
>>> stringFive = "Hello # Press enter to make it span to the next line SyntaxError: EOL while scanning string literal >>> stringSix = '''Hello from a verbatim string... ...''' >>> stringSix 'Hello from a verbatim string...\n\n...'
Triple quoted strings are really helpful when you want to output ascii art on to the screen, as they preserve the whitespace you specify in the variable. Ascii art is combination of special symbols(including alphabet and numbers) that depict a picture or a logo. These come in handy while trying to output a graphic when some event occurs in the program. One example is outputting different pictures in a game of hangman, depending how many tries has a player had.
stringSeven = ''' _______ |/ | | (-) | \|/ | | | / \ | |___ '''If you simply enter this variable name in the interpreter and press enter, you will see a combination of sequences such as \n, \xa0. These are escape sequences, you will learn about them in the next section. For now, suffice it to know that to output this graphic as it is depicted here, you have to wrap the variable in a print() function i.e. >>> print(stringSeven)
Triple quoted strings are also used as docstrings in functions, we will get to that later.
- You may use normal strings to span multiple lines by using the line continuation character i.e. backslash (\).
>>> stringEight = 'This string is most likely to violate the Python guideline which says you \ should try to limit your statements to 79 characters and no further.' >>> stringEight 'This string is most likely to violate the Python guideline which says you should try to limit your statements to 79 characters and no further.'
However, PEP, the Python Enhancement Proposal prefers that if you want your strings to span multiple lines, you may use the brackets, like below.
>>> stringNine = ("This string is also likely to violate the Python guideline which says you " "should try to limit your statements to 79 characters and no further.") >>> stringNine 'This string is also likely to violate the Python guideline which says you should try to limit your statements to 79 characters and no further.'
Unpacking a string
Strings are sequences of characters, and they can be unpacked into individual variables. Unpacking procedure can be performed on lists, dictionaries, sets and tuples, but we'll look at that later. Here's how you unpack a string:
>>> stringTen = "Hello" >>> a,b,c,d,e = stringTen >>> a 'H' >>> b 'e' >>> c 'l' >>> d 'l' >>> e 'o'
Referring individual characters in a string with indexes
You can extract a particular string out of a string using a number in square brackets, as below:
>>> stringEleven = "Ethan" >>> stringEleven 'h'
What you specified in the brackets is what is called an index. Indexes are a programming language's way of storing your data sequentially in the memory. Indexes are zero based, that is the first character will be given an index of 0. Here's how the string 'Hello there!' will be stored in the memory:
>>> arrayRepresentation = ''' _ _ _ _ _ _ _ _ _ _ _ _ | | | | | | | | | | | | | | H | e | l | l | o | | t | h | e | r | e | ! | | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | 0 1 2 3 4 5 6 7 8 9 10 11 ''' >>> arrayRepresentation 'e' >>> arrayRepresentation 't'
You can access the characters from the end as well, using negative indexes. In this case, the first character from the end will be represented by -1. Give that a try.
>>> stringTwelve = "Hello" >>> stringTwelve = 'G' # Can't alter a string using indexes TypeError: 'str' object does not support item assignment >>> stringTwelve = "Hi" # Can assign a different value to the variable >>> stringTwelve 'Hi'
FYI: Among the sequence data types, dictionaries and lists are mutable, whereas sets, strings, tuples are immutable.
Repeating a string
You can repeat a string multiple times by using the asterisk symbol (*), like this:
>>> stringThirteen = "Hi " >>> stringThirteen * 5 'Hi Hi Hi Hi Hi '
Concatenating two or more strings
You can join two strings by using the addition symbol (+), or by giving each string as an argument to the print function, or by placing the strings to be joined adjacent to each other wrapped in their own quotes. See below for example.
>>> stringFourteen = "Hi" >>> stringFifteen = " there!" >>> stringFourteen + stringFifteen 'Hi there!' >>> print(stringFourteen,stringFifteen) # note how print adds a space between the strings in the result. 'Hi there!' >>> stringFourteenTwo = 'hel' 'lo''...there' # haven't used this much myself, but it is supported by Python. >>> stringFourteenTwo 'hello...there'
Be wary of the fact for string concatenation, all the participants should be of the type string, or you will see a TypeError. Refer to type casting below to make the required conversion.
Escape Sequences: how to print special characters inside strings
There are many characters you might want to include in your string, but inserting them normally will generate errors or unexpected results e.g. say you wanted to quote a great author or wanted to include a dialogue from a character in direct speech, or wanted to use the sarcastic quotation marks, or further more, wanted to emphasize a particular word using single quotes, here's how you would do it:
>>> stringSixteen = "Albert Einstein once said, \"Any fool can know. The point is to understand.\"" # The double quotes have special meaning in Python i.e. they are used to denote a string, that doesn't mean you can't use them in the English language constructs. You may do so by prefixing your character by a backslash character. >>> print(stringSixteen) Albert Einstein once said, "Any fool can know. The point is to understand." >>> stringSeventeen = 'I am here to print "Game Over" on the screen.' >>> print(stringSeventeen) I am here to print "Game Over" on the screen. >>>
Actually, you can use nested quotes as well, to achieve the above purpose like this:
>>> stringSixteen = 'Albert Einstein once said, "Any fool can know. The point is to understand."' # Nesting quotes inside the other kind of quotes. >>> print(stringSixteen) Albert Einstein once said, "Any fool can know. The point is to understand."
Python is okay with above as long as you place the closing quotes in the right place i.e. the quotes you begin later should be closed first.
What you cannot do is this:
>>> stringEighteen = 'I am here to print 'Game Over' on the screen.' SyntaxError: invalid syntax
because Python cannot make sense of the above, you need to escape the single quotes in the middle by prefixing them with a backslash (\).
>>> stringEighteen = 'I am here to print \'Game Over\' on the screen.' >>> print(stringEighteen) I am here to print 'Game Over' on the screen.
Following are the prominent escape sequences used in Python:
>>> print("Backslash: \\ ") Backslash: \ >>> print("Single quote: \' ") Single quote: ' >>> print("Double quote: \" ") Double quote: " >>> print("New line: \n some text") New line: some text >>> print("Tab: \t some text") Tab: some text
For further reading, visit this link.
>>> some_variable = "Hi\nthere!" >>> some_variable 'Hi\nthere!' >>> print(some_variable) Hi there!
System bell with the \a sequence doesn't work in interpreters, you will have to save a .py file with a print("\a") statement and run it from the command prompt to hear it.
Slicing a string
Slicing means getting a substring of a given string i.e. getting a portion of the original string. Here's how we achieve slicing in Python.
>>> originalString = "magnanimous" >>> arrayRepresentationOfOriginalString = ''' # for understanding indexes used later 0 1 2 3 4 5 6 7 8 9 10 _ _ _ _ _ _ _ _ _ _ _ | | | | | | | | | | | | | m | a | g | n | a | n | i | m | o | u | s | | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 ''' >>> st = originalString # for easy reference >>> st[1:5] # st[x:y] gives us a string starting with st[x] and ending with st[y-1] 'agna' >>> st[-5:-1] # -5 is actually 6 and -1 is actually 10, so this becomes st[6:10] 'imou' >>> st[1:5:1] # st[x:y:z] gives us a string starting with st[x], with a step over size of 1, ending with st[y-1] 'agna' >>> st[1:5:2] # starting at index 1, ending with index 5-1, with a difference of 2 between the indexes of characters 'an' >>> st[5:1:-1] # FOR NEGATIVE STEP SIZE: begin at index 5, move in the opposite direction i.e. left, finish at index 1 + 1. 'nang' >>> st[-5:-8:-1] 'ina' >>> st[:5] # select everything from index 0 to 5-1 'magna' >>> st[5:] # select everything from index 5 till the end of the originalString 'nimous' >>> st[:] # gives the originalString itself 'magnanimous'
- Python provides numerous methods for tweaking strings, each of which is handy. You can see all these by entering a string in the Python interpreter with single/double quotes, typing in a period (.), then pressing tab or Ctrl/Cmd + Space.
- To bring these into action, select one of these using arrow keys, double press Tab, type in two round brackets i.e. () and hit enter e.g. "Sample".upper()
- To get help on these methods, say title method you may do something like this: >>> help("Sample".title)
I'll list a few prominent ones here, you can explore the rest.
>>> stringNineteen = "lab rat for testing string methods" >>> s1 = stringNineteen.upper() # 'LAB RAT FOR TESTING STRING METHODS' # converts all string characters to upper case >>> s2 = stringNineteen.lower() # 'lab rat for testing string methods' # converts all string characters to lower case >>> s3 = stringNineteen.capitalize() # 'Lab rat for testing string methods' # converts first character of the string to upper case >>> s4 = stringNineteen.count('t') # 5 # gives the number of occurrences of the provided character or sequence in the originalString >>> s5 = stringNineteen.title() # 'Lab Rat For Testing String Methods' # capitalizes the first letter of every word, just like in a headline title >>> s6 = stringNineteen.replace('t', 'w') # replaces occurrences of first argument with the second one. Arguments could be a sequence as well. >>> s7 = stringNineteen.split() # ['lab', 'rat', 'for', 'testing', 'string', 'methods'] # gives a list of words separated by space in the originalString. Could achieve the same purpose by .split(" "). You could specify any other delimiter, like a comma i.e. .split(","). >>> s8 = "_".join(stringNineteen) # 'l_a_b_ _r_a_t_ _f_o_r_ _t_e_s_t_i_n_g_ _s_t_r_i_n_g_ _m_e_t_h_o_d_s' # joins together originalString with the given string as separator ## COMMON BUILTIN FUNCTIONS APPLICABLE ON STRINGS >>> ord('a') # 97 # ord() function takes a single character(special ones too) and returns its Unicode value. Unicode is a collection of codes for more than 1,20,000 characters covering letters, numbers in a variety of languages, including symbols. Unicode values for letters a through z are 97 to 122 & A through Z are 65 to 90. It is inverse of the builtin chr() function. >>> chr(97) # 'a' # chr() function takes a Unicode value and returns the symbol or letter represented by the provided code in the Unicode dictionary. It is inverse of the builtin ord() function.
Calculating the length of a string
We can use the inbuilt len() function to calculate the length of a string. The len() is a generic method, meaning it can be used to calculate the length of lists, tuples, dictionaries etc.
>>> len("Hello") 5 >>> string1 = "merry merry" >>> len(string1) 11
More about print§
So far, we have seen how the print() function is arguably the most used builtin function. Let's discuss a couple more functionalities provided by the print() function.
Ending a statement with a desired character
The default behavior of the print() is to print a new line after whatever we ask it to print. Now that you know about escape sequences, you would have probably guessed that it ends with a \n.
We can tweak this to suit our needs, using the end argument. Let's see this in action:
## Put the following code in a script and execute it on the command line. print("hunky", end = "-") print("dory") ## The output on the command line will be: hunky-dory
Printing multiple values
We have actually touched upon this in the string concatenation bit, for the sake of completeness, let's see it once again. We can print multiple values using the same print() function, like this:
>>> a = "apple" >>> b = "ball" >>> c = "cat" >>> print(a, b, c) apple ball cat # The spaces in the print statement after commas bear no effect on the output, that's just the default behavior of print function, it puts a space between the arguments supplied to it.
Number data types§
Python 2 supports int, float, complex and long data types. However, long was dropped in Python 3. Integers are numbers without any fractional component e.g. 2, -2, 0. Floating point numbers have a fractional component e.g. 2.3, 3.14. Complex numbers have an imaginary bit along with them, represented by the letter j.
>>> myInt = 2 >>> type(myInt) # <class 'int'> >>> myFloat = 3.14 >>> type(myFloat) # <class 'float'> >>> myComp = 2 + 3j >>> type(myComp) # <class 'complex'>
Python supports mixed arithmetic: when an arithmetic operator has operands of different numeric types, the operand with less precision is widened to that of the other, where integer is narrower than floating point, which is narrower than complex.
Mathematical operators work more or less the same way on all integer types, except for a couple of exceptions.
>>> a = 6 >>> b = 4 >>> a + b # 10 # addition >>> a - b # 2 # difference >>> a * b # 24 # product >>> a / b # 1.5 # quotient >>> a // b # 1 # floored quotient i.e. the largest integer less than the quotient(1.5) # not applicable on complex numbers >>> a % b # 2 # remainder of the division a / b i.e. 6 / 4 # not applicable on complex numbers >>> a ** b # 1296 # a raised to the power b i.e. 6 * 6 * 6 * 6 >>> -a # -6 # negation of a c = 6 + 4j f = 2.8 ## Builtin functions designed for the integer data types >>> abs(-a) # 6 # absolute value or magnitude of a >>> int(f) # 2 # f converted to an integer # Result is floored >>> float(a) # 6.0 # a converted to a floating point >>> complex(a, b) # (6+4j) # a complex number with real part a and imaginary part b >>> c.conjugate() # (6-4j) # Conjugate of the complex number c >>> divmod(a, b) # (1, 2) # the pair (a // b, a % b) >>> pow(a, b) # 1296 # a raised to the power b i.e. 6 * 6 * 6 * 6 >>> max(a, b) # 6 # returns the larger of the two # not applicable on complex numbers >>> min(a, b) # 4 # returns the smaller of the two # not applicable on complex numbers
Boolean Data Type§
Boolean is the simplest data type you will ever see. It only has two valid values: True and False. It was added to Python in version 2.3. Since then, many builtin functions and standard library functions were changed to return either True or False e.g. the isinstance(x, y) which tells us whether x is of the type y.
Boolean data type was added with the primary goal of making code clearer. For example, if you're reading a function and encounter the statement return 1, you might wonder whether the 1 represents a Boolean truth value, an index, or just a number to be used elsewhere. If the statement is return True, however, the meaning of the return value is crystal clear.
In all actuality, True and False are string versions of integers 0 and 1, and Boolean data type is a subclass of the 'int' type. Hence, it supports arithmetic, like this:
>>> True + 1 2 >>> True * 20 20 >>> False + 1 1 >>> False * 20 0 >>> int(True) 1 >>> int(False) 0
Following are the three boolean operators: or, and and not.
# a or b: if a is false, then b, else a # WHEN BOTH VALUES DENOTE FALSE: returns the second value. # WHEN ONLY ONE VALUE DENOTES TRUE: returns the value denoting true. # WHEN BOTH VALUES DENOTE TRUE: returns the first value # As soon as it encounters a true value, it stops evaluating further. >>> 0 or 2 2 >>> 2 or 0 2 >>> 2 or 5 2 >>> False or True True >>> True or False True >>> 0 or False False # a and b: if a is false, then a, else b # WHEN BOTH VALUES DENOTE FALSE: returns the first value. # WHEN ONLY ONE VALUE DENOTES FALSE: Returns the value denoting false. # WHEN BOTH VALUES DENOTE TRUE: returns the second value. # As soon as it encounters a false value, it stops evaluating further. >>> 0 and 2 0 >>> 2 and 0 0 >>> 2 and 5 5 >>> True and False False >>> False and True False >>> 0 and False 0 # not a: if x is false, then True, else False >>> not True False >>> not False True >>> not 5 False >>> not 0 True
A Few General Things§
Here are a few handy things you should take note of.
Getting user input: input()
The builtin input() function is used for receiving input from the user. The input function takes an argument, which is what will be flashed on the screen before the user enters a value. We can assign the value entered to a variable that we can use later in the program.
>>> input("Tell me your name. \n") Tell me your name. Tyrion Lannister # User types this and presses enter 'Tyrion Lannister' >>> name = input("Tell me your name. \n") Tell me your name. Tyrion Lannister >>> print("Did you just say " + name + "?") Did you just say Tyrion Lannister?
Casting: Type Conversions
There will be times when you need to convert a string to a numeric form, or vice versa. For example, try executing
>>> a = 21 >>> print("I am " + a + " years old.")
You should see something like this:
Traceback (most recent call last): File "python", line 1, in <module> TypeError: Can't convert 'int' object to str implicitly
To get around situations like this, we can use the builtin str(), int(), float() functions.
## Converting an integer to a string >>> a = 21 >>> print("I am " + str(a) + " years old.") I am 21 years old. ## Converting a string to an integer >>> age = input("How old are you? \n") # input() returns a string, so age is a string right now. How old are you? 22 >>> age = int(age) # converting a string(age on the right) to an int(age on the left) >>> age_in_days = age * 365 >>> print("You have lived for more than" + str(age_in_days) + " days.") You have lived for more than 5830 days. ## Converting a string to a floating point >>> temp = float(input("Pop Quiz: What is the normal body temperature(in Celsius units) of humans?\n")) Pop Quiz: What is the normal body temperature(in Celsius units) of humans? 38.6 >>> print("You entered: " + str(temp)) You entered: 38.600000000000001
At some point in your program, you will the need to compare two values, and then proceed on the basis of the result of the comparison. For example, you have to compare the entered string with the stored password of the safe, and grant or revoke access to the safe on the same basis, or you have to monitor the temperature of a furnace and throw off an alarm as soon as it surpasses the maximum allowed value of temperature. Okay, a little too intricate for an example, but you get the point, don't you?
Python supports 8 comparison operations, here they are with examples:
## COMPARISON OPERTORS # < ## strictly less than # <= ## less than or equal to # > ## strictly greater than # >= ## greater than or equal to # == ## equal to # != ## not equal to # is ## object identity tester: checks if the variables on either side of 'is' point to the same object in the memory # is not ## negated object identity tester ## VARIABLES FOR EXAMPLES BELOW >>> a = 360 >>> b = 500 >>> c = 360 >>> d = a >>> password = "letmein" ## EXAMPLES ####################### < >>> a < b # 360 < 500 True >>> a < c # 360 < 360 False ####################### <= >>> a <= b # 360 <= 500 True >>> a <= c # 360 <= 360 True ####################### > >>> a > b # 360 > 500 False >>> a > c # 360 > 360 False ####################### >= >>> a >= b # 360 >= 500 False >>> a >= c # 360 >= 360 True ####################### == ## returns True if the objects referred to by the variables are equal. >>> a == b # 360 == 500 False >>> a == c # 360 == 360 True >>> password == "letmein" # "letmein" == "letmein" True ###################### != >>> a != b # 360 != 500 True >>> a != c # 360 != 500 False >>> password != "letmein" # "letmein" != "letmein" False ###################### is ## is will return True if two variables point to the same object >>> a is d # we assigned a to d by d = a, so d points to the same object as a True >>> d is a True >>> a is c # we assigned the value 360 to both a and c, so only the a == b returns True False >>> a is b False ## the way the is operator works is that it compares the unique numbers of the two operands given to them by Python for the current session. These unique numbers are the identity ###################### is not >>> a is not b True >>> a is not c True >>> a is not d False
>>> a = 360 >>> b = 500 >>> c = 360 >>> d = a >>> id(a) 23543243 # yours will be different >>> id(b) 23423423 >>> id(d) 23543243 # same as a, since we made d refer to a by executing d = a
PYTHON CACHES SMALL INTEGER OBJECTS: Python usually caches(places them in cache memory for quick retrieval, to save time) the id of numbers from -5 to 256(this range many vary on different implementations of the language), so if you assign any number within -5 - 256 to two or more variables, their id will be same i.e.
>>> a = 100 >>> b = 100 >>> id(a) # some random number >>> id(b) # the same number as returned by id(a)
Controlling The Flow Of The Program§
Python is an imperative language, as opposed to being a declarative language. Imperative paradigm suggests that the language uses its statements to jump around the program and control the way a program operates. In other words, the control shifts from one block of code to the other. Declarative languages emphasizes on what the statements would accomplish, and not on how they would do it. You specify what you want done, it is left on the machine (more specifically, compiler) to figure that out. Examples of declarative languages are SQL and Prolog.
There are three methods of controlling the flow in Python:
- Function calls
We'll cover branching for now. Branching, as the word suggests, implies that if a given condition(also known as predicate) is true, execute the following indented(four spaces or a tab) code block. Else, execute another code block. There is only one statement in Python that implements branching i.e. the if statement.
The simplest form of an if statement is: if a given condition is true, execute this piece of code. If it is false, proceed by skipping the code block.
if(True): print("Yay!") # prints if True: print("Yay!") # prints flag = True if flag: print("Yay!") # prints flag = False if flag: print("uh oh....") # doesn't print someTrueValue = 2 if someTrueValue: print("Yeah!") # prints if not someTrueValue: # evaluates to false print(" :O ") # doesn't print someFalseValue = 0 if someFalseValue: print("No;.") # doesn't print if not someFalseValue: # evaluates to true print("Bwahahaha") # prints if(2 < 5): print("You are right, 2 IS less than 5.") # prints if( len("Hello") == 5 ): print("Hello is a five letter word.") # prints if(False): print("Anything, it is not going to be printed anyway.") print("The condition was wrong.") if False: print("Anything, it is not going to be printed anyway.") print("The condition was wrong.") if( 2 > 5 ): print("Bleh") print("The condition was wrong.")
The elif and else clauses give you more ways to cover the domain of your problem. They are optional to specify.
Elif: If the predicate in the "if" is false, it will test the predicate on the first elif, and run that code block if it’s true. If the first elif is false, it tries the second one, and so on. As soon as it finds a true predicate, it will stop checking branches, and skip the rest of the if statement.
Else: The else clause is placed at the bottom of the entire if statement. If none of the other branches are executed, then Python will run this branch. It doesn't take any predicate.
if (2 > 10 ): print("Your maths is all wrong!") else: print("Executing the else block.") if ( 2 > 10 ): print("Oh dear....") elif ( 2 > 3 ): print("...") elif ( 2 > 1 ): print("Finally!") if ( 2 > 10 ): print("Oh dear....") elif ( 2 > 3 ): print("...") elif ( 2 > 2 ): print(".........") else: print("Enrolling you for Mathematics for Dummies....")
On the agenda in the next chapter§
Strings, Numbers, Operators, Controlling the flow, we have covered significant ground in this chapter, kudos to you! Try the 3 programs yourself. You will be able to make sense of them now, and in case you don't, then place a comment down below.
In the next chapter, we will cover 2 the looping constructs, namely, for and while. Till then, cheerio!
- Write a program to convert height units. Your program should take two inputs: feet and inches. Convert these into centimetres using the fact that 1 inch = 2.54 cm & 1 foot = 12 inches. [ Solution ]
- Write a program to calculate Body Mass Index (BMI). Body Mass Index (BMI) is a value obtained from height and weight of an individual. It is used as a metric to classify a person as underweight, normal weight, overweight or obese based on the computed value. BMI for underweight: < 22.5. BMI for normal-weight: 22.5–25, BMI for overweight: 25–29.9. BMI = ( weight / height * height ) * 703 when weight is in pounds (lbs) and height is in inches. BMI = ( weight / height * height ) when weight is in kilograms and height is in meters. You can use either of these formulas to compute BMI. Ask the user for his height and weight and tell him his BMI. [ Solution ]
- Write a script to convert Celsius temperature to Fahrenheit temperature. Formula: F = 32 + 9/5 * C. Ask the user for a Celsius temperature and output the equivalent Fahrenheit temperature. [ Solution ]
- Write a script to determine whether the entered letter is a vowel or a consonant. [ Solution ]
- Object Oriented Python
- Design Patterns in Python
- 50+ Handy Standard Library Modules
- 60+ Handy Third Library Modules
- 50+ Tips & Tricks for Python Developers
- 50+ Know-How(s) Every Pythonista Must Know