Python Tech Series… Day 2: Introduction To Python Programming. Python's Building Blocks wrt to CS* - Part 1

Hello Reader! Welcome to Day 2. I hope Day 1 is good and laid a great start for the series. Today we will look at the Building blocks of the Python language such as input, output, Variables, Comments, Keywords, Data Types, etc.

image.png

Topic 1: Comments: Comments help to document the program without impacting the execution flow. # used for single-line comments and ''' three single/double quotes for multi-line comments. '''. Same multiline comments can be used for documenting the function, class, and method and we can print using doc. suppose if you want to comment on multiple lines in one-click select the code you want to comment on and press Cntrl + / In windows or cmd + / in mac.

example:
# seperator method separate using '-'
    '''multi line 
                  comments'''

Topic 2: Display Output: Print() is a function that helps us to print information into the user's console. In the previous example, the print("hello world") statement hello world is printed into the terminal. The print function takes the values given inside the brackets and prints them into the terminal screen.

There are 2 important parameters and 1 method for the print function.

1. Sep - How to separate each value inside the print function. default is ' '. for example. print(1,2,sep= '-'), and the result will be 1–2 in the output terminal. based on the value given inside the sep method, the output will be different.

2. End - To specify what needs to print at the end. By default, the end will be \n (newline character).

3. Format: Not a default method of print, but combining print with the format will give a lot of coding freedom. we use {} to define our data. Format function can be used to limit the decimal points in the output screen also.

example:
# seperator method seperate using '-'
print(1, 2, sep='-')
# end - default is '-' #output gets end with -
print(1, 2, end='-')
print('\neach char in list in new list')
print(*lstr, sep='\n')
# lets say you need to print decimal points upto 6  {:.6f} or decimal points upto n value {:.nf}
print("value of c is {:.6f}".format(c))
# format using {key:value too}
print("My name is {a}, {b}".format(a='sai', b='murali'))

Topic 3 Variables: Variables are containers of the data. While performing a task, we generally store the values, give names to them & refer to them later. The name is called Variables. Variables are nothing but Labels for the data. The process of storing a value inside a variable is called Assignment and it will be done using Assignment Operator(=). when we create a variable, the System will reserve some chunks of memory to store the information such as Variable id, Variable type, and Variable value. we can print the value inside a variable using print() function, and its Type using type() function #we will discuss in next topic).Variables are highly Case sensitive. Variable names are case sensitive - name, Name, NAME, and namE all are the unique name to python and all are valid.

Rules of defining Variable Name(Must):

  1. Variable name cannot start with a number, but a number can be used anywhere in the name except at the start. Example: sai = 2, sai2 = 2 are valid where 2sai = 2 is not valid.

  2. Variable name must start with Either Letter or Underscore(_). [a-z,A-Z,a-Z] Example: sai= 2, sai=2, var, lit _ are valid.

  3. Variable name must contain only Letters, Numbers, and Underscores No special characters are allowed. [a-z,A-Z,a-Z]. Example: sai_murali_2, sai_2_murali, s2_ai are valid, sai@1 is not valid.

  4. Keywords cannot be used as Variable names. Keywords are reserved words that have some meaning and effect and are used to construct the program. we have 36 keywords in python. we can see if a name is a keyword or not using its iskeyword function in the keyword module. if iskeyword return True means the name you gave is a keyword else it is not a keyword. Example:if = 2, while = 100 are not allowed.

import keyword as key
print(key.kwlist) #print all keywords
print(len(key.kwlist)) #print total no of keywords in python
print(key.iskeyword('if')) #checks if "if" is keyword or not.
  1. Spaces are not allowed in the variable name. we can use underscores to join multiple words to create a single name. Example: sai_murali = 2 is valid, where sai murali = 2 is not valid.

  2. Be careful when using the lowercase letter l and the uppercase letter O because they could be confused with the numbers 1 and 0.

length = 2; #variable length with value 2
width = 2; #variable width with value 2
area_of_rectangle  = length * width;  #variable area_of_rectangle gets data from an expression length * width;
print(area_of_rectangle) #print value in area_of_rectangle variable.

Expression: is a combination of numbers, symbols, or other variables that evaluates and produces a result.

Python will raise a Syntax Error if any name is declared without following the above rules and The interpreter provides a traceback when a program cannot run successfully. A traceback is a record of where the interpreter ran into trouble when trying to execute your code. Trace will have information such as file name, the line at which the error occurred error type, and Error description.

The same rules will be applied when we declare a class, function, methods, etc.

Identifier Name Conventions:

  1. if we have a single Underscore at the front of your identifier. ex: _my_var : indicates this is an internal or Private Object. Everything in the Python is public, To differentiate we use a single underscore to tell this is a Private object.

Suppose in a module, if we have an object with a single underscore, and when we are trying to import the module, the private object will not get imported. we can access them using different techniques which can discuss during OOPS concepts.

  1. if we have double Underscore at the front of your identifier. ex: __my_var: indicates mangle attributes. uses for inheritance classes. if a Variable name in the parent class is also being used in the child class, we make the parent class variable a mangle and it helps to differentiate via 'name mangling'. More on this we can discuss during OOPS concepts.

  2. if we have double Underscore at both front and end of your identifier. ex: my_var: These have special meaning and special purpose and system defined. ex: init use to initiate a class. It is always suggested not to create an identifier with a double underscore on both sides because there might be a special understanding for interpreters which can cause issues. ex: x < y → as per interpreter : x.lt(y) # this method gets executed when x < y is given in the Python.

PEP8:Python Enhancement Proposal, A template tells about the good coding practices which writing a code in python.

  1. Packages: Names must be short, NO Underscores, All Lower cases.
  2. Modules: Names must be short, Can have Upper case, and No underscores.
  3. Class: CamelCase. ex: CapWords.
  4. Function: Must be Lower case, Can have underscores.
  5. Variables: Can contains Numbers, underscores, and Letters but should not start with numbers and can have both lower and upper case.

Input function: Py provides an input function to get the information from the user. #caution: any value you enter as input, the input function will return that data in a String format only. The reason is we input the from the Keyboard and keyboard words on ASCII char organization which is by default char/str type. that is the reason we will get data in STR Format. if you want to use the data, we have to use the Type conversion function to convert from one data to another.

a = input('Enter the number:-')
print(a, type(a))

Ideally, Computer doesn't know how to mix different data types, ex: print(7+8) #adding 2 ints is valid or print("hello " + "world") #adding 2 str's is valid but print( 7 + "hello ") # computer don't know how to add an integer to a string and raise a TypeError says we can't use + between int and str., in short, we can't add different types. This opens up a new concept called, Type conversions.

print(7 + 8.5) # adding float with int, Python will not push TypeError here instead, when both belong to number systems, and float is more priority than int, Python will convert the int 7 to float 7.0 and add up with 8.5 and prints the results 15.5. This concept is called IMPLICIT Conversion. The Interpreter automatically converts the data from one data type to another.

Going back to the input() function, anything you entered in an input function will be returned in str format. suppose you entered the age of the number and the age must be in int format, in such situations we have to convert the age from string to int, here Explicit conversion helps us, and Python provides functions that convert data from one type to another. ex: int() to convert data into int format, list() data into list format, float() data into float format, str() data into string format, etc.

age = input('Enter the age:- ')
print(age, type(age))  # enter 2, str type
age = int(input('Enter the age:- '))
print(age, type(age)) #enter 2, int type.
Enter the age:- 2
2 <class 'str'>
Enter the age:- 2
2 <class 'int'>

Type: In every day, we process/use a lot of data. For example, if you want to store a contact in your phone, you have to enter a name - a series of characters represents some text, phone number - a series of numbers represent some whole number. likewise, most programs need to manipulate lots of data and the data will come in any format. example: name of the person - String format, Age of the person - integer (whole number), Height of the person - float or real numbers, etc.

Python offers the below type hierarchy and will discuss in detail in the future.

Numbers: We can divide numbers into 2 different sections. 1. Integral: Numbers like 1,2,3…, (whole numbers) or Booleans (actually Int, 1(True), 0(False)). 2. Non-Integral: Float (c doubles) ex: 3.14, Complex numbers (both real and imaginary part), Decimals (kind of floats) represents real numbers but decimals have more control on precision over floats, Fractions(1/3) Fractions will be very helpful when we deal the real numbers with infinity precision.

Collections: Collection of different data under one roof.

  1. Sequences: Sequences can be sub-divided into Mutable(list) and immutable(tuple - an immutable variant of the list), Strings(str).
  2. Sets: Sets can be sub-divided into mutable (sets) and immutable(frozen sets).
  3. Mappings: Dictionaries. Dict and Sets are actually related. implemented very similarly. Both are Basically Hash maps. The only diff is sets are not key valued, whereas Dict is a key-value pair type.

Callables: A function which can be called and perform an unit of work. we have user defined functions, generators, Classes, Instance methods(inside classes), Class Instances.Built in functions (len(),print(), input() etc), Built in Methods (ex: list has append() method to add element at end).

Singletons: Design a pattern that allows you to create just one instance of a class, throughout the lifetime of a program. ex: None, NotImplemented, Ellipis {..}. All objects created with None will point to the same memory location.

Type function: type(variable name or value) will tells the type of the function. ex: type(10) returns its type as Int, type(10.0) return its type as Float.

Here, The stage is set for the next set of topics, But we have to work on how variables are behaving at the memory level, Mutability, Equality, Assignment, Reference counting, Dynamic and Static Typing, etc. This helps us to solid understanding of data. Detailed discussion in next Up URL Below.

Day2: Part2: saimuralipavanrayavarapu.hashnode.dev/pytho..

References or Copyrights: CS*: Computer Science.

Thanks for reading!. Keep Upskilling.