We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 10
Chapter 2:
Variables and Simple Data Types
Page + 1 backlink
2.1 What Really Happens When You Run hello.py
When we ran our program hello.py, we saw the following output:
Hello, World!
What happens here is that the terminal runs the file through the Python interpreter,
which reads through the program and determines what each word in the program
means. For example, when the interpreter sees the word print followed by
parentheses, it prints to the screen whatever is inside the parentheses.
‘As we write our programs, the editor highlights different parts of the program in
different ways. This feature is called syntax highlighting and is quite useful as we
write our own programs.
2.2 Variables
Every variable is connected to a value, which is the information associated with that
variable. Let's look at an example where we add a variable named message:
message = “Hello, Python!”
print (message
Run this program and we should see:
Hello, Python!
When the Python interpreter processes the first line in our code, it associates the
variable message with the "Hello, Python!" text. When it reaches the second
line, it prints the value associated with message to the screen.
We can change the value of a variable at any time, and Python will always keep track
of its current value. To demonstrate, let's add two lines to our previous code:
message = "Hello, Python!"
print (messagemessage = "Welcome to Integrative Programming!"
print (message
Run this program and we should see:
Hello, Python!
Welcome to Integrative Programming!
Naming and Using Variables
Here are some rules and guidelines; breaking some of them will cause errors:
1. Variable names can only contain letters, numbers, and underscores.
2. They can start with a letter or an underscore, but not with a number.
3. Spaces are not allowed in variable names, but underscores can be used to.
separate words in variable names.
4. Avoid using Python keywords and function names as variable names.
5. Variable names should be short but descriptive.
6. Be careful when using the lowercase letter 1 and the uppercase letter 0
because they can be confused with the numbers 1 and 0.
Given these rules and guidelines, these variable names are therefore invalid:
student, student+name, student name
Avoiding Name Errors When Using Variables
Let's look at an error that we are likely to make early on and learn how to fix it:
message = "Hello Python!"
print (mesage)
In the above code, we've placed a misspelled word mesage . When an error occurs,
the Python interpreter tries its best to help us figure out where the problem is. The
interpreter provides a traceback when a program cannot run successfully. Here's an
example:
Traceback (most recent call last):
File “hello.py", line 2, in
print(mesage)
NameError: name 'mesage’ is not defined. Did you mean: ‘message’?
The output reports that an error occurs at line 2 of the file hello.py. The interpreter
shows on the third and fourth lines of the output an information that will help us
quickly identify the error, while the fifth line tells us what kind of error the interpreter
found. The error in this case is a name error and reports that the Variable being
printed, mesage , has not been defined. This means that Python can't identify the
name provided.A name error usually means we either forgot to set a variable's value before using it,
or we made a spelling mistake when entering the variable's name. if Python finds a
variable name that's similar to the one it doesn't recognize, it will ask if that's the
name you meant to use, as seen on the last line of the output.
Variables Are Labels
Variables can be regarded as boxes where we can store values in. However, this is
not accurate and not always the case. So, it is better to think of variables as labels,
that you can assign to values or that a variable references certain value.
2.3 Strings
A string is a series of characters. Anything inside quotes is considered a string in
Python, and we can use single or double quotes around our strings like thi
"This is a string."
‘This is also a string.’
This flexibility allows us to use quotes and apostrophes within our strings:
‘I said, "Python is my favorite language!"'
"The language ‘Python’ is named after Monty Python
"One of Python's strengths is its diverse and supportive community."
Changing Case in a String with Methods
One simple task we can do to with a string is to change the case of the words. For
example:
name = "ada lovelace"
print (name.title
name = "Ada Lovelace"
print (name. upper
print (name. lower
In this program, we have the variable name that refers to the lowercase string "ada
lovelace" . On line 2, the method title() appears after the variable inside the
print() call. A method is an action that Python can perform on a piece of data.
The dot . aftername in name.title() tells Python to make the title() method
act on the variable name
Every method is followed by a set of parentheses, because methods often need
additional information to do their work. That information is placed inside the
parentheses. The title() function doesn't need any additional information, so the
parentheses are empty.Save this program as name.py and then run it. We should see:
Ada Lovelace
ADA LOVELACE
ada lovelace
The title() method changes each word to title case, where each word begins
with a capital letter, the uppex() method changes all words to uppercase, while the
lower() method changes all words to lowercase.
Using Variables in Strings
Sometimes, we want to use the value stored in variables into our strings. For
example, we might want to use two variables to represent a first name and a last
name and then combine those values to display a full name:
first_name = "ada
Jast_name = “lovelace"
full_name =£"{first_name} {last_name}"
print (full_name
As seen on line 3, to insert a variable's value into a string, we place the letter £
immediately before the opening quotation marks. Put braces around the variable
name or names we want to use inside the string. Python will replace each variable
with its value when the string is displayed.
These strings are called f-strings. The ¢ is for format, because Python formats the
strings by replacing the name of any variable in braces with its value. We can now
combine all we've learned so far to write the following code:
first_name = ‘ada"
last_name = "lovelace"
full_name =£"{first_name} {last_name}"
message = f"Hello, ifull_name.title()}!"
print (message
The above code should display the following:
Hello, Ada Lovelace!
Adding Whitespace to Strings with Tabs or Newlines
Whitespace refers to any nonprinting characters, such as spaces, tabs, and end-of-
line symbols. We can use whitespace to organize our output so it's easier for users
to read. We can use the character combinations \t to adda tab and \n to adda
newline. For example:>>> print ("Python")
Python
>>> print("\tPython")
Python
>>> print("Languages:\nJavaScript\nPython\nc"
Languages
JavaScript
Python
c
We can also combine tabs and newlines in a single string. For example:
>>> print ("Languages:\n\tJavaScript\n\tPython\n\tC ")
Languages
JavaScript
Python
c
Stripping Whitespace
Extra whitespace can be confusing in our programs. We might see:
‘python’ and ‘python ' the same, but to a program, they are two different
things. Python sees the extra space and considers it significant unless we tell it
otherwise.
Often, we will want to compare two strings to determine if they are the same. Like for
example when checking a person's username when they log in. Extra whitespace
can confuse the program but fortunately, Python makes it easy to eliminate extra
whitespace from a string.
Python can look for extra whitespace on the right or left side of a string and remove
them using the rstrip() and 1strip() methods respectively. For example:
>>> language = ‘python
>>> language. xstrip()
"python!
>>> language = ' python
>>> language. 1strip()
"python!
>>> language = ' python
>>> language strip
"python!
‘As shown on line 8, we can also remove extra whitespaces on both sides at once
using the strip() method. Using these functions will leave the original string
unchanged. So, if we want to permanently change the string, we need to associate
the stripped value with a variable name, either a new variable or the original variable.
For example:>>> language = ' python
>>> language - language. strip()
>>> language
"python!
Experimenting with these stripping functions can help us familiarize with
manipulating strings. In the real word, these stripping functions are used most often
to clean up user input before it's stored in a program.
Removing Prefixes / Suffixes
‘Another common task, when working with strings, is removing a prefix. Consider a
URL with the common prefix https: //. We may want to remove this prefix, so we
can focus on the part of the URL that users need to enter into the address bar of a
browser. Here's how to do that:
>>> fb_url = ‘https: //facebook.com’
>>> fb_url removeprefix('https://')
facebook.com
Here, the method removeprefix() needs additional information, the prefix we
want to remove, which we place inside the parentheses. Like the methods for
removing whitespace, removeprefix() leaves the original string unchanged. So, if
we want to permanently change the string, we need to associate the new value with
a variable name, either a new variable or the original variable. For example:
>>> fb_url = 'https://facebook.com'
>>> fb = £b_url.removeprefix( ‘https: //'
>>> fb
facebook.com
We can also remove a suffix using the removesuffix() method. Just like the
removeprefix() method, we also need to place inside the parentheses the suffix
we want to remove.
Avoiding Syntax Errors with Strings
One kind of error we might see regularly is a syntax error. A syntax error occurs
when Python doesn't recognize a section of the program as valid Python code.
Suppose we add an apostrophe inside a string that uses single quotes. We'll
encounter an error, because Python interprets the code between the first single
quote and the apostrophe as a string and then tries to interpret the rest as Python
code, which are now invalid:
message = 'One of Python's strengths is its diverse community
print (messageIf we save this program as apostrophe.py and run it, we should see:
Traceback (most recent call last):
File “apostrophe.py", Line 1
message = ‘One of Python's strengths is its diverse community. '
SyntaxError: unterminated string literal (detected at line 1)
This syntax error indicates that the interpreter doesn't recognize something in the
code as valid Python code, and it thinks the problem might be a string that's not,
quoted correctly. We might see syntax errors often as we learn to write proper
Python code. Syntax errors are also the least specific kind of error, so they can be
difficult and frustrating to identify and correct.
2.4 Numbers
Numbers are used quite often in programming. Python treats numbers in several
different ways, depending on how they're being used.
Integers
Integers are whole numbers. In Python, you can add +, subtract - , multiply *, and
divide / integers. Exponentiation in Python uses two multiplication symbols %x.. In
a terminal session, the operations simply return their result. For example:
p> 3 +2
>>> 3-2
o> B42
>>> 3/2
1.5
>>> Bee 2
Python supports the order of operations, so we can use multiple operations in one
expression. We can also use parentheses to modify the order of operations so
Python can evaluate the expression in the order we specify. For example:
>o> 2 + Bad.
14
>>> (2 +3) #4
20
The spacing in these examples have no effect on how Python evaluates the
expresions; it simply helps us more quickly spot the operations that have priority
when we're reading through the code.Floats
Any number with a decimal point in Python is called a float. This term refers to the
fact that the decimal point can appear at any position in a number. Like integers, we
can also use the operations +, -, *, /, and x*:
>>> 0.1 + 0.1
0.2
>>> 0.2 + 0.2
0.4
do>2+* 0.1
0.2
>>> 2* 0.2
0.4
Integers and Floats
When we divide any two numbers, even if they are integers that result to a whole
number, we will always get a float. If we mix an integer and a float in any other
operation, we ill get a float as well. Python defaults to a float in any operation that,
uses a float, even if the result is a whole number:
>> 4/2
2.0
>>> 1+ 2.0
3.0
>>> 2 * 3.0
6.0
>>> 3.0 +e 2
9.0
Underscores in Numbers
When writing long numbers, we can group digits using underscores to make large
numbers more readable. If you print a number defined using underscores, Python
only prints the digits.
>>> universe_age = 14_000_000 600
>>> print (universe_age
1499000000
Python ignores the underscores when storing these kinds of values. Even in you
dont't group the digits in threes, the value will stil be unaffected. This feature works
both for integers and floats.
Multiple AssignmentWe can assign values to more thatn one variable using just a line of code. This can
shorten the program and make it easier to read. This is most often used when
initializing a set of numbers. For example:
>>> x,y, Z=1, 2,3
The above code initializes variables x, y, and z with values 1, 2, and 3
respectively. When using mulitple assignments, we need to separate the variable
names with commas, and do the same with the values, and Python will assign each
value to its respective variable. As long as the number of values matches the
number of variables, Python will match them up correctly.
Constants
A constant is a variable whose value stays the same throughout the life of a
program. There is no built-in constant type in Python, but it helps to use all capital
letters to indicate a variable should be treated as a constant and never changed:
MAX_CONNECTIONS = 5000
2.5 Comments
Comments are an extremely useful feature in most programming languages. As our
programs become longer and more complicated, we should add notes within our
programs that describe our overall approach to the problem we are solving. A
comment allows us to write notes within our programs.
How Do You Write Comments?
In Python, the hash mark # indicates a comment. Anything following a hash mark is
ignored by the Python interpreter. For example:
# Say hello to everyone.
print ("Hello everyone!"
Python ignores the first line and executes the second line:
Hello everyone!
What Kinds of Comments Should You Write?
The main reason to write comments is to explain what your code is supposed to do
and how you are making it work. While currently writing our code, we mightunderstand how all of the pieces work together. But when we return to it after some
time away, we might forget some of the details. Writing good comments can save
you time from studying the code all over again!
Professional programmers write meaningful comments. Today, most software is
written collaboratively, so it's best to add descriptive comments to our code. Writing
clear, concise comments is one of the most beneficial habits we can form as anew
programmer.