Python - Coding Basics - Variables and Data Types

Coding basics in Python

This page will be updated time to time

In this page we will see various aspects related to coding in Python like Variables, Datatypes etc.

Below are some Symbols and their respective operations

  • # If a line in the code begins with #, it will be considered as comment and will not be executed. We will use these to give a description of the code
  • print() - a function to generate output from the script
  • For example, to print a value of a variable with name "var", we will use print(f'var = {var}')

Below are the arithmetic operators used in Python

  1. + to perform addition. E.g.: 6+3 is 9
  2. - to perform subtract. E.g.: 6-3 is 3
  3. * to perform multiplication. E.g.: 3*3 is 9
  4. / to perform division and this returns quotient. E.g.: 27/3 is 9.0 
    • Division returns Float
  5. // to perform floor/integer division and rounds the result to whole number. E.g.: 22//3 is 7
    • Floor division returns Int
  6. % to perform modulo and this returns remainder. E.g.: 27%3 is 0
  7. ** to perform exponentiation or power. E.g.: 3**3 is 27

Below is how variables and datatypes are used in Python

A variable is used to store a value and can be referred/called later.
Variable is specific case-sensitive name.
  • <variable_name>=<variable_value>
  • person_age=25 --> here "person_age" is variable with value 25 assigned to it
  • person_name=rachel --> here "person_name" is variable with value "rachel" assigned to it
Data types are used to tell the type of data a variable is used to store. Data type of a variable value can be known using type function like this --> type(variable_name)
e.g. type(person_age)  which will return <class 'int'>
  • Int or Integer (whole numbers) - a number without fraction part
  • Float or Floating Point(decimal values) - a number with both an Integer and fraction part
  • Str or String - text enclosed in quotes. Could be either single or double quotes
  • Bool or Boolean - True or False (With upper case T in True and F in False). It is kind of Yes or No and are used to check conditions
Python makes our life easier by inferring the type of data we are working with, avoiding the need for us to explicitly declare the data type! 

Variable naming standards
  • should be with underscore(_) if variable name is like two letters
  • shouldn't start with number
  • also we can follow either
    • snake case - person_age - separate each word by underscore
    • camel case - PersonAge - capitalize 1st letter in each word
  • print() - a function to generate output from the script
  • For e.g., to print value of  variable with name "var_name", we will use print(f'aa = {var_name}')

Working with strings

Strings can be created using single or double quotes.
Method - A function that is only available to a specific data type.
Usage of method will be like variable.method()
For e.g., if person_name is variable, and replace is the method, we can use methods like this --> person_name.replace("John", "Mary")

Some commonly used methods with strings are 
  1. replace() - to replace a letter/word with different letter/word
  2. lower() - to convert to lower
  3. upper() - to convert to upper
  4. print() - to print a string
  5. print("Welcome"[0]) - to print only 1st letter of the word "Welcome" which is W. This is called subscript.
Multi-line strings - if a string is long enough to spread across multiple lines, then we will enclose in between 3 double quotes

"""Hello 
World"""

All the datatypes (int, float, string, Boolean) discussed so far can store only one value in a variable.
What if we want to store more values.  For this we have more advance data types and let's look at them.

More datatypes - Lists, Dictionaries, Sets and Tuples

Lists - to store more values in a variable and these values can be a mix of any data types seen so far. 
We use [ ] (square brackets) to store values separated by comma (,) in the List datatype variables.
numbers = [10, 20, 30, 40]. 
Lists are ordered.

Accessing elements a List
Elements of a list can be accessed by subsetting or indexing. Python allocates an index number to each value in the list starting from 0. 
Accessing via Subsetting/Indexing is like say from our example list of numbers
numbers[0] to access 1st element in list
numbers[6] to access 7th element in list
numbers[-1] to access the last element in list

Accessing multiple elements in List
numbers[1:3] will return 20 and 30 from our example list numbers defined  and these are 2nd and (2nd+1) elements in the list
numbers[1:3] here returned 2nd element and up to
list[n:m] --> this will return the values of (n+1)th in index and upto (m-1)th in index
In this case, subsetting syntax will be like <list_name>[starting_element:last_element + 1] as Python doesn't count index of the last element and counts only up to the index of the last element

numbers[n:] will return from index (n+1)th element to last element
numbers[:n] is same as numbers[0:n] to  return from 1st element to index (n-1) element
numbers[::n] will return every 1st element and then every nth element 
numbers[1::n] will return 2nd element and then every (n+1)th element from there


Dictionary to store more values in a variable and these values can be a mix of any data types. discussed so far. However, if there has to be relationship among the values stored, then Lists will not be helpful. Dictionary datatype comes in handy in this scenarios where related information needs to be stored and we will have key value pairs in Dictionary. We use {} (curly bracketsto store values in the Dictionary datatype variables.

county_captial = {"India":"New Delhi", "France":"Parsis", "USA":"Washington DC"}

Dictionaries are ordered and can be accessed like Lists but by providing the key.
Dictionaries do not accept duplicate keys.

dictionaryname.values() - to access all values in the Dictionary
dictionaryname.keys() - to access all keys in the Dictionary
print(dictionaryname) - to print entire Dictionary
dictionaryname.items() - to print entire Dictionary. However, this will print each value/key value pair of dictionary as comma separated values in parathesis (). These values in parenthesis are known as Tuple. 

We can update the values of Dictionary items. 
dictionaryname[value]=new value
dictionaryname[key]=new key

Sets to store unique(non duplicates) data and immutable(unchangeable) of existing values. However, values can either be added or removed. Sets can be searched quickly.
We use {} (curly bracketsto store values in the Set datatype variables.
Sets are unordered and no duplicates.

Tuples to store unique(non duplicates), immutable and related data . No add/removal/change after creation. 
We use () (parenthesisto store values in the Set datatype variables.
numbers = (10, 20, 30, 40). 
Tuples are ordered.



No comments:

Post a Comment