Categories
Python

Part 1: VARIABLES, STRINGS & NUMBERS

Learn the basics of Python data structure including strings, variables, boolean and commenting in Python

1. VARIABLES

Every variable holds a value, which is the information associated with that variable.

message ="Hello World"
print(message)
Hello World
Hello World

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 than jojo
  • 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 named message, we get the following traceback

Traceback (most recent call last):
  File "/Users/Exercise Files/Variable.py", line 2, in <module>
    print(messages)
NameError: name 'messages' is not defined

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

"This is a string." 
'This is also a string.'

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.

name = "dexter morgan" 
print(name.title())
Dexter Morgan

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

first_name="Dexter"
last_name="Morgan"
full_name=first_name + ' ' + last_name
print(full_name)
Dexter Morgan

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

first_name="Dexter"
last_name="Morgan"
full_name= f"Full name: {first_name} {last_name}"
print(full_name)
Full name: Dexter Morgan

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 \t

print("\tPython")
	Python

b. Adding Newlines

To add a newline in your text, use the character combination \n

print("Platforms:\nIOS\nAndroid")
Platforms:
IOS
Android

c. Combining Tabs and Newlines

print("Platforms:\n\tIOS\n\tAndroid")
Platforms:
	IOS
	Android

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
whitespaced_string="   Left and Right   "
print(whitespaced_string.rstrip()) 
  Left and Right
  Left and Right
  • To remove whitespaces from the left end of a string, use the lstrip() method
whitespaced_string="   Left and Right   "
print(whitespaced_string.lstrip())
Left and Right   
Left and Right   
  • To remove whitespaces from the both ends of a string, use the strip() method
whitespaced_string="   Left and Right   "
print(whitespaced_string.strip())
Left and Right
Left and Right

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:

print(f"5 plus five is {5+5}")
print(f"5 subtracted from 10 is {10-5}")
print(f"5 multipled by 5 is {5*5}")
print(f"10 divided by 2 is {10/2}")
5 plus five is 10
5 subtracted from 10 is 5
5 multipled by 5 is 25
10 divided by 2 is 5.0

You can use two multiplication symbols ** to do powers

print (f"5 power 2 is {5**2}")
print (f"10 power 5 is {10**5}")
print (f"Sqaure root of 25 is {25**0.5}")
5 power 2 is 25
10 power 5 is 100000
Sqaure root of 25 is 5.0

Python supports the order of operations (Parenthesis Exponent Multiplication Division Addition Subtraction)

print(2 + 4 ** 2 * 4 - 6)
60

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

print(0.2+0.3)
0.5

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.

print(0.2+0.1)
0.30000000000000004

3.3. Avoiding Type Errors with the str() Function

What will happen when you try to combine a string with number, using + operator

age=20
print("Happy " + age + "th birthday")
TypeError: can only concatenate str (not "int") to str

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

age=20
print("Happy " + str(age) + "th birthday")
Happy 20th birthday

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:

age=20
print(f"Happy {age}th birthday")
Happy 20th birthday

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.

# print the result of 10**10
print(10**10)
10000000000

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

name = 'dexter'
is_smoker = False
is_drinker = True
print(f"{name.title()} smoking status is {is_smoker} and drinking status is {is_drinker}") 
Dexter smoking status is False and drinking status is True

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:

print(f"Data type of 'Hello World' is :{type('Hello World')}")
print(f"Data type of 100 is :{type(100)}") 
print(f"Data type of 10.50 is :{type(10.50)}") 
print(f"Data type of True is :{type(True)}") 
Data type of 'Hello World' is :<class 'str'>
Data type of 100 is :<class 'int'>
Data type of 10.50 is :<class 'float'>
Data type of True is :<class 'bool'>

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:

import this

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!

Leave a Reply