Variables, Strings & Numbers In Python
1. VARIABLES
Every variable holds a value, which is the information associated with that variable.
In the above example, the variable is named message and it holds the value Hello World. You can change the value of a variable in your program at any time, and Python will always keep track of its current value.
1.1. Variable naming rules
Variable names can contain only letters, numbers, and underscores
Variable can start with a letter or an underscore, but not with a number
Spaces are not allowed in variable names, but underscores can be used
Avoid using Python keywords and function names as variable names (for example, don’t use the word print to assign a variable)
Variable names should be short but descriptive. For example, if you are saving the car names in the list, then
car_names
is better thanjojo
Be careful when using the lowercase letter l and the uppercase letter *O * because they could be confused with the numbers 1 and 0
1.2. Traceback
A traceback (error) is a digital record of where the interpreter ran into trouble when trying to execute your code For example, if we try to print variable
messages
when in real we set the variable namedmessage
, we get the following traceback
NameError: 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.
2. STRINGS
String is a data type that is used to represent text rather numbers. The string literal can contain alphabets, numbers, spaces and special characters. We can use “ ”
or ‘ ‘
to store the string value
2.1. Changing Case in a String with Methods
What is Methods? A method is an action that Python performs on a piece of data. Every method is followed by a set of parentheses ( )
, because methods often need additional information which is provided inside the parentheses.
Examples
title() title()
displays each word in titlecase, where each word begins with a capital letter.
In this example, the lowercase string “dexter morgan” is stored in the variable name
. The method title()
appears after the variable name.title()
. This method doesn’t need any additional information, so its parentheses are empty. upper() upper()
changes a string to all uppercase letters lower() lower()
changes a string to all lowercase letters
There are 10’s of string methods, to get the complete list and their function, follow this official doc
2.2. Combining or Concatenating Strings
The following methods are used to combine strings
a. Method 1 (plus sign)
You might want to store a first name and a last name in separate variables, and then combine them when you want to display someone’s full name
Python uses the plus symbol (+) to combine (concatenate) strings.
b. Method 2 (f string)
Since the introduction of Python 3.6, we can use f string, to concatenate the strings, variables etc. Here is an example of using f string
To use f string method, all we need to do is to add f
before " "
Then we can write any text inside double quotes and use the { }
to provide the values of variables. Among two methods, I personally prefer using f string because it is simple and produce clean code.
2.3. Adding Whitespace to Strings
a. Adding Tab
To add a tab in your string, use the character combination
b. Adding Newlines
To add a newline in your text, use the character combination
c. Combining Tabs and Newlines
d. Stripping Whitespace
White spaces is a piece of data and to ignore/strip them from the string, you need to tell Python to remove them:
To remove whitespaces from the right end of a string, use the
rstrip()
method
To remove whitespaces from the left end of a string, use the
lstrip()
method
To remove whitespaces from the both ends of a string, use the
strip()
method
3. NUMBERS
3.1. Integers
Integer is whole number without any fraction. It can be positive or negative but always a whole number. For example, -1, 0, 10 We can perform various arithmetic operations on the integers.
For example, one can add +
, subtract -
, multiply *
, and divide/
integers in Python as follows:
You can use two multiplication symbols **
to do powers
Python supports the order of operations (Parenthesis Exponent Multiplication Division Addition Subtraction)
Python will first solve the Exponent (4 ** 2
= 16) then Multiplication (16 * 4
=64) then Addition (64 + 2
=66) and lastly subtraction (66 - 6
=60) Note: The spacing has no effect on how Python evaluates the mathematical expressions
3.2. Floats
You can read about the anatomy of float number on wikipedia or Quora but in simple terms, any number with decimal point is considered as float in Python. It can be positive or negative, but always contains a decimal point. For example -1.0, 9.5 etc. For the most part, you can use decimals without worrying about how they behave
Sometimes get an arbitrary number of decimal places in your answer. Python tries to find a way to represent the result as precisely as possible. This is how Python find the answer to this operation internally.
3.3. Avoiding Type Errors with the str() Function
What will happen when you try to combine a string with number, using +
operator
TypeError: It means Python can’t recognize the kind of information you’re using. **str() function: ** To avoid TypeError
in above example, we will convert the number into string using str() function
However, as covered earlier, we can easily use the f string
method to avoid the need to convert integer to string. Here is an example:
4. COMMENTS
A comment allows you to write notes within your programs that is ignored by compilers and interpreters.
4.1 How Do You Write Comments?
In Python, the hash mark #
indicates a comment. Anything following a hash mark in your code is ignored by the Python interpreter.
4.2. What Kind of Comments Should You Write?
Purpose of writing comment is to let readers of your code understand what you are doing in your program
Writing meaningful comment is even more important when we collaborate with others (Think of Open source)
For someone new in programming, writing clear, concise and helpful comments in your code is one of the most beneficial habits you can form
5. OTHERS
5.1. Boolean Data Type
Boolean is a binary data type whose value is either True
or False
As you will learn more about Python and its data science libraries, you witness its powerful ability for data manipulation and masking
5.2. Finding Data Type
We have covered some basic data types in this article. In order to find the data type, we will use Python type()
function. Here are few examples:
5.3. Zen Of Python
Experienced Python programmers encourage to avoid complexity and aim for simplicity whenever possible. The Python community’s philosophy is contained in The Zen of Python by Tim Peters. To import it, execute following command in your Python program:
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than right now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
Last updated
Was this helpful?