❌

Reading view

There are new articles available, click to refresh the page.

Git

Git is a powerful version control system which used to manage the code across multiple users and track changes across different versions.

Installation:

Download and install GIT from the below path

https://git-scm.com/download/win

Once installed, Git can be used as a version control system through various commands.
You can configure Git for a specific folder on your computer, allowing you to manage all changes to existing files and the addition of new files within that folder

Basic commands:

1. git init:

This will initialize new repository in the current directory. This also creates .git directory and store all version control information.

2. git config:
git config --global user.name "Ranjith "
git config --global user.mail "ranjith201099@gmail.com"
3. git status

Shows the current status of working area like staged, untracked and unstaged.

4. git add

add changes from working directory to the staging area, preparing them to commit.

To add specific file: git add "filename.py"
To add all changes git add .
5. git commit
git commit -m "<message>"

Commits the staged changes with descriptive mesage

6. git log

Displays the list of commit history for the repository.
It will show commit id, author, dates and commit changes
Creating a branch

git branch <branch_name> - to create branch
git checkout <branch_name> - to switch to the new branch
git branch -b <branch_name> 

to create and switch to branch
git branch - to view all the branches (current branch will be highlighted with asterisk)

Merge a branch:

Once completed work on a branch and want to integrate it into another branch (like master), merging comes to place.

It means all the changes we have made in <branch_name> will be merged with master branch.
First, switch to the branch you want to merge into: git checkout master
Then, use git merge <branch_name> to merge your branch.
Deleting branch
Once the code changes in <branch_name> merged into <master> branch, we might need to delete branch.
use git branch -d <branch_name> to delete branch

Image description

Image description

js | Functions |

Functions

Functions are pieces of code that we can reuse again and again in our code

Function Declaration - JavaScript Hoisting

syntax:
function functionName( ){

// code block

}

functionName()  //calling function
Example:
function msg( ){

console.log("Hii...Hello");

}

msg()  //calling function
//msg()
output:

Hii...Hello
//Hii...Hello

A function declaration defines a named function.It's hoisted,
meaning you can call it before it's defined.

Calling the function:
HOSTING
msg()  // valid  HOSTING
function msg( ){

console.log("Hii...Hello");


}
output:

Hii...Hello

Function Parameters and Arguments

syntax:

                        //input 
function functionName( parameter ){

// code block   //output

}

functionName( arguments)  //calling function

Functions can take parameters, which act as placeholders for the values
that will be passed to the function.The passing value is called an argument.

function msg( name ){

console.log("Hii...Hello" + name);

}

msg( "ranjith") ;
msg( "kumar") ;


output:

Hii...Hello ranjith
multiple parameters
function msg( name ,age){

console.log("Hii", + name +" my age"+age);

}

msg( "ranjith",25) ;
msg( "kumar",20) ;

Default Parameter

function printer(color){

console.log("print document in ${color} color");

}

//printer("blue") 
printer("blue") 
output:

document coloe blue color
//red override
function printer(color="black"){

console.log("print document in ${color} color");

}

//printer("red") 
printer( ) 
output:

//document coloe red color

document coloe black color

 Function with Return Type
function add( a,b){
     return a+b;

}

 let sum = add(10,20); //variable vechu assign panni print pannrom
 console.log(sum);  //30

 //console.log(add(10,20);   check pls
 Function Expression
A function expression defines a function inside an expression.
It's not hoisted, so you can't call it before it's defined.
syntax:

    variable      keyword
let functionName=function ( ){

   //code block

}

functionName()   // calling function

Ex:

           //don't change 
 let msg = function( ){   // function() indha typelaa kandippa irukkanum

 console.log("good morning");

}

msg( ) ;  //good morning 
With Argument
//msg( "ranjith") ;   // exp not hositing

let msg = function( name ){

console.log("good morning ${name}");

}

msg( "ranjith") ;  //good morning ranjith
Function Expression with Return Type
let mul = function (a,b){
   return a*b;

};

let result = mul( 5,2 ){
console.log(result); //10

 //console.log(mul(4,7));
 Arrow Function
 Arrow functions provide a concise syntax and do not bind their own 'this'. They are not hoisted.
 syntax:


    variable      keyword
let functionName=( ) =>{

   //code block

}

functionName()   // calling function

Example:
let evening = ( ) =>{

 console.log("good evening everyone");

}

evening ()   // good evening everyone 
With Argument
//not hoisting
let evening = ( name ) =>{

 console.log("good evening " + name);

}

evening ("ajith")   // good evening ajith
 Arrow Function with Return Type


 let sub =( a,b ) =>{
    return a - b ;
 };

  console.log( sub(10,6); // 4
Shorter Way
let sub =(a,b) => a-b;

console.log(sub(10,6)); //4
Function Calling Other Function
                       //ranjith
 function welcomeShopper(name){

 console.log(" welcome ${name} ! enjoy yoyr shopping experience")

}              //ranjith
    function main(name){

   // welcomeShopper(name); // direct calling
                   //ranjith
   let ShopperName-name;  // variableassign and after calling
                   //ranjith
   welcomeShopper(ShopperName); // calling top welcomeshopper

  };

  main("ranjith")  // welcome ranjith ! enjoy your.....
Anonymous Functions: Later on Course on Arrays
serTimeout(() => {

   console.log(" anonymous function executed");

 },2000 // 2sec delay  

 output: anonymous function executed
Scope of variables will on functions and loops
var: Function scoped.
Ex:
function demo(){
    var a =20;
    console.log(a); 

  }
demo();
console.log(a)  //error function outside calling
let: Block scoped.
const: Block scoped.
 Ex:

 function demo(){
     var a =20;
     console.log(a); 

   if (true){

   var x = "var";
   let y = "let";
   const z = ""const;     /// block scop

   console.log(x);
   console.log(y);    // all working good ...if block
   console.log(z);

  }
   console.log(x); // outer block code run successfully  (var)   
   console.log(y);   // error  (let)
   console.log(z);   // error not defienfd  (const)

 demo();

console.log(a)

Js | Truthy & Falsy |

Truthy and Falsy Values:

in Javascript, truthy and falsy values are used to determine whether a value evaluate to true or false in a boolean
context.this concept is crucial for controlling the flow of your program using conditions like if statement.

Falsy Values: 0," ",null,NaN,false,undefined 
console.log(Boolean(0)); //false
console.log(Boolean(undefined)); //false

console.log(Boolean(' '));  //empty false

console.log(Boolean(null)); //false

console.log(Boolean(NaN)); //false not a number

console.log(Boolean(false)); //false

Truthy Values: any value that is not Falsy :

console.log(Boolean(1)); //true
console.log(Boolean(1833933)); //true
console.log(Boolean(-1)); //true
console.log(Boolean("hello")); //true
console.log(Boolean(1)); //true
console.log(Boolean([])); //true empty array
console.log(Boolean({})); //true empty object
console.log(function (){}); //true
Example:
           t     f
let cash =255  //0 ; 
    //conditions false  statement block not run
if (cash){
  console.log("you can buy burger with drink"); 
}else{
   console.log("you can buy burger"); 
}else{
   console.log("you don't have money"); 
}
let a;
console.log(a); //false
output:
undefined 
let a = 10;
console.log(a); //true
let a = null;
console.log(a); //false

Js | Decision Making: | if | if Else | Else if |

Decision Making: if, if...else, else if


Decision making or control flow in programmming is the way we coontrol the execution
of code based on certain conditions.this allows the program to make choicces and execute diff code paths.

Example 1: if statement
syntax:
if (condition){

  //code block 

}

Example:

             f    f   t
let temp =  #24  #25  25;


if (temp>=25);
{

console.log("it is hot outside");

} 

Example 2: if...else statement

syntax:

if (condition){

  //code block 

}
else{

   //code block 

}
Example 1:
if (temp>=25);

{

console.log("it is hot outside");

}
else{

console.log("it is cold outside");

}
Example 2:
let isRaining= #true false;

if (isRaning);
{

console.log("take an umbrella");

}
else{

console.log(" you don't need an umbrella");

}
Example 3: else if statement
syntax:
if (condition){

  //code block 

}
else if(condition){

   //code block 

}
else{

   //code block 

}
Example:
let time=14;

if (time<12){

console.log("good morning"); 

}
else if(time<18){

 console.log("good afternoon");  

}
else{

 console.log("good evening");  

}
Example 4: Nested if statements
Variables
let age= 16;
let iswithparents=true;
let idproof=true;
Decision logic

if (age>=18);{

  if(idproof);
    console.log("you can visit the mall and can able to watch the movie"); 
  } else{
     console.log("you can visit te mall"); 
  }
}else{
     if(iswithparents);
        console.log("you can visit the play area"); 
  } else{
     console.log("you are not allowed in the play are"); 
  }

}
Example:
let day=1;

if(day===1){
  console.log("monday"); 
}
else if(day===2){
  console.log("thuesday"); 
}
else if(day===3){
  console.log("wenday"); 
}
else if(day===4){
  console.log("thuesday"); 
}
else if(day===5){
  console.log("friday"); 
}
else{
console.log("in valid"); 
}
Switch Statement
syntax:
switch(vale){
  case 1:
     //code block  
      break;
  case 2:    
    //code block  
       break;
  case 3:
      //code block  
       break;
  Default:
      //code block  
       break;
}
Exmple1:
let day=3;

switch(day){

  case 1:
      console.log("monday"); 
      break;
  case 2:
      console.log("thuesday"); 
      break;
  case 3:
      console.log("wensday"); 
      break;
  case 4:
      console.log("thresday"); 
      break;
  case 5:
      console.log("friday"); 
      break;
   default:
      console.log("invalid"); 
}

output:

wensday
Exmple2:
let choice='tea';

switch(choice){

   case 'coffee':
      console.log("you choose coffee monday"); 
      break;
   case 'tea':
      console.log(" you choose tea thuesday"); 
      break;
    case 'water':
      console.log(" you choose water thuesday"); 
      break;
    default:
      console.log("invalid"); 
}

output:

you choose tea 
Ternary Operator
short hand if else
let isadmin =true;

/*if(isadmin){
  console.log("am  admin");
}
else{
   console.log("am  user");
} */
                 true        .
let userrole = isadmin ? " am admin ":" am user ";
console.log(userrole);

let mark=60;
     var        cond      if       else
let result = mark>=30 ? " pass ":" fail ";
              //true
//let result = 25>=30 ? " pass ":" fail ";

console.log(result); 

output:

pass

Js | DataTypes |

Datatypes

  • Javascript is Dynamic Typing

  • Primitive and Object Type

Primitive Data Types:

1.Number - Represents both integer and floating-point numbers.

let age=10;  #equal two apram enna num,str,bool ex...automatic convert pannikum enna datatype nu.
console.log(age);
console.log(typeof age); 

output:
10
number
age="25";
console.log(age);
console.log(typeof age); 

output:
string

float number:

let price=19.99;
console.log(price);
console.log(typeof price); 

output:
19.999
number

2.String - Represents a sequence of characters.

let greeting="Hello World.!"
console.log(greeting);
console.log(typeof greeting); 

output:
string

3.Boolean - Represents a logical entity and can have two values: true or false.

let isActive=true;
console.log( isActive);
console.log(typeof  isActive);
let isActive=false;
console.log( isActive);
console.log(typeof  isActive); 

4.Undefined - A variable that has been declared but not assigned a value.

let name;  #Error undefined
console.log( a);
console.log(typeof a); 

5.Null - Represents the intentional absence of any object value.

let name-null:
console.log(name);
console.log(typeof name); 

6.Symbol - Represents a unique and immutable value, often used as object property keys.

let unique=symbol("key"); #custom symbol
console.log(unique);
console.log(typeof unique); 

output:
symbol("key")

7.BigInt - Represents whole numbers larger than 2^53 - 1 (the largest number JavaScript can reliably represent with the Number type).


let largeNumber=BigInt(68690356789000833);
let largeNumber=68690356789000833n; #using the n notation

console.log( largeNumber);
console.log(typeof largeNumber); 

output:
68690356789000833n

Non-Primitive Data Types

1.Object

Represents a collection of properties, each consisting of a key (usually a string)
and a value (which can be any data type, including another object.

let person={

  name-'ranjith'.
  age=25,
  isEmployed=true;
}

console.log( person); //total laa print agum
console.log( person .name);  // name only
console.log( person .age);  // age only
console.log( person .isEmployed);

console.log(typeof  person); 

2.Array

A special type of object used for storing ordered collections of values.

let number=[1,2,5,4,8];
console.log( number);

let mixdata=[1,'2',true,false,null,[1,2,'5',"str"] ,undefined ];
console.log( mixdata);

3.Function

A special type of object that is callable and can perform an action.

function invite( ){
   console.log( "you are invitd");
}
invite()
**4.Date - A built-in object for handling dates and times.**

let now- new Date;
console.log( now);

outut:
date wed jul 24 2024 09.00:51 Gmt( indian stamdard)

Js | Variable & Values |

Jscript print :

console.log("Hello World ");

Variables & Values

Image description

Image description

  • The var keyword was used in all JavaScript code from 1995 to 2015.

  • The let and const keywords were added to JavaScript in 2015.

  • The var keyword should only be used in code written for older browsers.

Java script identifiers :

  • All JavaScript variables must be identified with unique names.

  • These unique names are called identifiers.

  • Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

  • The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.

Names must begin with a letter.

Names can also begin with $ and (but we will not use it in this tutorial).

Names are case sensitive (y and Y are different variables).

Reserved words (like JavaScript keywords) cannot be used as names.

What is Good?

- let and const have block scope.

- let and const can not be redeclared.

- let and const must be declared before use.

- let and const does not bind to this.

- let and const are not hoisted.

What is Not Good?

- var does not have to be declared.

- var is hoisted.

- var binds to this.

Declare var variable :

var a; #Error undefined 

Initialize the variable :

var a = 10;

Redeclaration allowed :

var a = 100;
console.log(a);

Output :
100

Declare let variable :

let b;

Initialize the variable :

let b = 10;

Redeclaration is not allowed :

let b =100; 

Reassignment is allowed :

b = 200;
console.log(b);

cons must Declare & initialize 1st line :

const PI=31415 ;
//fixed Value Called Constant
console.log (PI);

Reassignment is not allowed :

const c = 1;
c = 2;
console.log(c);

Naming conventions :

correct way :

Correct camel Case convention :
let userName = 'John'; 
Underscore is not recommended but valid :

let user_Name ='Max'; 
start from Underscore :

let _userName ='Doe'; 

start from dollar symbol :

let $userName='Evo' ; 

string concatenate :

console.log('Welcome + userName);
console.log("Hi + userName);
console.log('Bye + userName);

Incorrect variable names :

Invalid: variable names cannot start with a number

let 5date= 5;

Resrved keywords (Functions):

let new = "data";
let function = 20;

Symbols in variable names :

let #function = 'data'; 
let @function = 'data';
let John&Jane = 'Friends'; 

let $function = 'data';  
#this one is correct

Scope of variables will on functions & loops :

var: Function scoped.
let: Block scoped.
const: Block scoped 

Python - List Methods & Tasks II

Even though I had done the tasks beforehand, watching them being done in class today taught me new things.

I learned that I could use Python's in-built list methods more, instead of falling back to for loop all the time.

For example, I could use the extend method (rather than for loop and append method) to expand a list with the contents of another list. Likewise, I could use the clear method (rather than for loop and remove method) to empty a list.

Unless there is a specific need for using the for loop, like I need to check a condition on individual elements before adding them to or removing them from the list, the code looks much cleaner this way.

Python: print() methods

Hi all,
Today, I learned about the Python print statement. It is fascinating to know that Python has so much functionality.I will share some of the thing i learned today

  1. sep, the sep parameter is used with the print() function to specify the separator between multiple arguments when they are printed.
  2. escape sequence like \n (new line), \t(adds space), \b(removes previous character).
  3. concatenation which adds two different strings.
  4. concatenating str and int which combine string and integer by converting integer into string by typecasting.
  5. Raw string A raw string in Python is defined by prefixing the string literal with an 'r' or 'R'.Raw strings are often used when working with regular expressions or when dealing with paths in file systems to avoid unintended interpretation of escape sequences.
  6. Format the format() method is used to format strings by replacing placeholders {} in the string with values passed as arguments.
  7. string multiplication here you can multiply strings by using the *operator. This operation allows you to multiply string a specified number of times.

Python - Indexing and Slicing

Indexing & Slicing is an important concept in Python, especially when we use strings.

Indexing :

WKT, string is nothing but a sequence of characters.
So, each character has a position namely index and accessing their position in that particular string is known as indexing.

In Python, we have zero based indexing i.e., the first character of a string has an index(position) of 0 rather than having one, then the second character has an index(position) of 1 and so on.

For example,

>     H E L L O W O R L D
>     0 1 2 3 4 5 6 7 8 9

This is known as positive indexing as we have used only positive numbers to refer the indices.

You may ask that "Then, we have negative indicing too??"
Ofc, but in here we do not have zero as the first position as it ain't a negative number.

Negative indexing allows us to access characters from the end of the string i.e., the last character has an index of -1, the second last character has an index of -2, and so on.

>      H  E  L  L  O  W  O  R  L  D
>    -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
word = "HELLOWORLD"

print(word[0])
print(word[5])

H
W

Similarly,

print(word[-1])
print(word[-6])

D
0

That's it about indexing.

Slicing :

Think of slicing a string like cutting a slice of cake from a whole cake. We can specify where to start cutting (index), where to finish (end index), and even how big each slice should be (step). This way, we can create smaller portions of the cake (or string) exactly how we like them!

In Python, slicing a string lets us grab specific parts of it by specifying where to start and where to end within the string.
So, for instance, if message contains "HELLOWORLD", then message[3:7] gives you "LOWO" because it starts at index 3 ('L') and ends just before index 7 ('D'). This way, we can extract any part of a string we need!

- The basic syntax for slicing is,

string[start:stop]
  • The start index is where the slice begins, and this index is inclusive.
  • The stop index is where the slice ends, but this index is exclusive, meaning the character at this index is not included in the slice.
text = "HappyBirthday"

print(text[0:5])  
print(text[5:13])

Happy
Birthday  

When slicing a string in Python, we can simply omit the start or stop index to slice from the beginning or to the end of the string.
It's as straightforward as that!

- Slicing with a step,

To specify the interval between characters when slicing a string in Python, just add a colon followed by the step value:

string[start:stop:step]

This allows to control how we want to skip through the characters of the string when creating a slice.

message = "HELLOWORLD"
print(message[1::2])    

EORL

message[1::2] starts slicing from index 1 ('E') to the end of the string, with a step of 2.
Therefore, it includes characters at indices 1, 3, 5, and 7, giving us "EORL".

Until, we saw about positive slicing and now let's learn about negative slicing.

- Negative Slicing :

  • A negative step allows you to slice the string in reverse order.
  • Let us slice from the second last character to the third character in reverse order
message = "HELLOWORLD"
print(message[-2:2:-1])

ROWOL

Let's look into certain questions.

#Write a function that takes a string and returns a new string consisting of its first and last character.

word = "Python"
end = word[0]+word[5]
print(end)

Pn

#Write a function that reverses a given string.

word = "Python"
print(word[::-1])

nohtyP

#Given a string, extract and return a substring from the 3rd to the 8th character (inclusive).

text = "MichaelJackson"
print(text[3:9])

haelJa

#Given an email address, extract and return the domain.

email = "hello_world@gmail.com"
domain = email[:-10]
print(domain)

hello_world

#Write a function that returns every third character from a given string.

text = "Programming"
print(text[::3])

Pgmn

#Write a function that skips every second character and then reverses the resulting string.

text1 = "Programming"
print(text1[::-2])

gimroP

#Write a function that extracts and returns characters at even indices from a given string.

text = "Programming"
print(text[::2])

Pormig

Allright, that's the basic in here.

.....

Python - Functions

FUNCTIONS, an awesome topic I learnt today. It's a shortcut for all lazy i.e., smart people who don't wanna waste their time typing inputs for several times.

What Is a Function?

In programming, rather than repeatedly writing the same code , we write a function and use it whenever and whereever it is needed.
It helps to improve modularity, code organization and reusability.

So, now let's see how to create a function.
A function contains,

  • function name - an identifier by which a function is called
  • arguments - contains a list of values passed to the function
  • function body - this is executed each time the function is called function body must be intended
  • return value - ends function call and sends data back to the program
def function_name(arguments): # key function name(arguments)
  statement                   # function body
  statement

  return value                # return value

Some examples of how to use functions.

#Write a function greet that takes a name as an argument and prints a greeting message.

def greet(name):
    return(f"Hello, {name}!")
greet("ABY")

Hello, ABY!

Here, we can replace return by print too.

#Write a function sum_two that takes two numbers as arguments and returns their sum.

def sum_two(a,b):
    return a+b

result = add(3,7)
print(result)

10

#Write a function is_even that takes a number as an argument and returns True if the number is even, and False if it is odd.

def is_even(num):
    return num % 2 == 0

num = 5
print(is_even(num))

False

#Write a function find_max that takes two numbers as arguments and returns the larger one.

def find_max(a,b):
    if a > b:
      return a
    else:
      return b

print(find_max(7,9))

9

#Write a function multiplication_table that takes a number n and prints the multiplication table for n from 1 to 10.

def multiplication_table(n):
    for I in range (1,11)
    result = n * i 

print(f"{n} * {i} = {result}")
n = multiplication_table(int(input("Enter a no: ")))

and the result is,

Enter a no: 5 # I've entered 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

#Write a function celsius_to_fahrenheit that takes a temperature in Celsius and returns the temperature in Fahrenheit.

This is how we normally do it..

celsius1 = 27
fahrenheit1 = (celsius1 * 9/5) + 32
print(f"{celsius1}Β°C is {fahrenheit1}Β°F")

celsius2 = 37
fahrenheit2 = (celsius2 * 9/5) + 32
print(f"{celsius2}Β°C is {fahrenheit2}Β°F")

celsius3 = 47
fahrenheit3 = (celsius3 * 9/5) + 32
print(f"{celsius3}Β°C is {fahrenheit3}Β°F")

27Β°C is 80.6Β°F
37Β°C is 98.6Β°F
47Β°C is 116.6Β°F

It's cumbersome right??
Soo, what's the shortcut? Ofc using a function.

def celsius_to_fahrenheit(celsius):
  return (celsius * 9/5) + 32

celsius = float(input("Celsius: "))
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{celsius}Β°C is {fahrenheit}Β°F")

Celsius: 37.5
37.5Β°C is 99.5Β°F

I've used input function to make it more compact...

#Write a function power that takes two arguments, a number and an exponent, and returns the number raised to the given exponent. The exponent should have a default value of 2.

def pow(num,exp = 2):
  return num ** exp


result = pow(5,exp = 2)
print(f"The number {num} raised to power 2 is ",{result})

You can opt to use input fns and variables as well..

By now, it's understandable that for one problem we can use multiple
programs to solve it. It depends which we prefer to use.

.....

My First Blog _Python

Hi All,

This is my very first blog. I'm a Biomath student who has zero knowledge about computer related stuffs.
Later, I was convinced to study a programming language yet confused with how,where and what to start...?

And finally decided to learn python, as people around me implied that it's easy to start with... So, now I'm learning python from an online platform., which teaches me so fine...

I thought of blogging it all, cause people like me will get to know that python isn't overly challenging rather as simple as English grammar.

We can learn python just by using "Google Colaboratory", yet I would let u know how to install python later.

So, join with me...
Let's start to learn PYTHON

PYTHON BASICS

1. Printing a String :

  • To print a text, we use print function - print()

  • Let's begin with "Hello World".

  • By writing certain text within the print function inside double or single quotes, we get :

print("Hello World")

Hello World

2. Similarly, we can Print Variables :

  • Variables are used to store data.
name = "Abys"
print(name)

Abys

  • Here, if we give numbers as values for the variable (ex: age=25) we needn't provide them under double or single quotes as they give the same output but as for texts we should use "" or ''.
age = 25 
print(age)

25

age = "25"
print(age)

25

name = Abys
print(name)

Traceback (most recent call last):
  File "./prog.py", line 4, in <module>
NameError: name 'Abys' is not defined

  • That's the reason for this rule. Hope it's clear.,

3. Printing Multiple Items :

  • We can print multiple items by separating them with commas while python adds space between each item.

  • Formatting strings with f strings is another sub topic where we insert variables directly into the string by prefixing it with an f and using curly braces {} around the variables.

let's see both,

name="Abys"
age=17
city="Madurai"
print("Name:",name , "Age:",age , "City:",city ,end=".")

Name: Abys Age: 17 City: Madurai.


name="Abys"
age=17
city="Madurai"
print(f"Name:{name},Age:{age},City:{city}.")

Name:Abys,Age:17,City:Madurai.

4.Concatenation of Strings :

  • Here, we connect words using + operator.
w1="Sambar"
w2="Vada"
print(w1+" "+w2+"!")

Sambar Vada!

  • Let's also see what is Printing Quotes inside Strings.

  • To print quotes inside a string, we can use either single or double quotes to enclose the string and the other type of quotes inside it.

w1="Sambar"
w2="Vada"
print("I love" , w1+" "+w2+"!")

I love Sambar Vada!

hobby = "Singing"
print("My hobby is" , hobby)

My hobby is Singing

5.Escape Sequences and Raw Strings to Ignore Escape Sequences :

  • Escape sequences allows to include special characters in a string. For example, \n adds a new line.
print("line1\nline2\nline3")

line1
line2
line3

  • r string is used as prefix which treats backslashes as literal characters.
print(r"C:\Users\Name")

C:\Users\Name

6.Printing Results of Mathematical Expressions :

  • We've already seen how to print numbers.
print(26)

26

  • Now, we're going to print certain eqns.
print(5+5)

10

print(3-1)

2

that's how simple it is...

7.Printing Lists and Dictionaries :

  • We can print entire lists and dictionaries.
fruits = ["apple", "banana", "cherry"]
print(fruits)

['apple', 'banana', 'cherry']

8.Using sep and end Parameters :

  • The sep parameter changes the separator between items.

  • The end parameter changes the ending character.

print("Happy", "Holiday's", sep="-", end="!")

Happy-Holiday's!

  • Let's see how to print the same in adjacent lines, here we use either escape sequences (\n) or Multiline Strings.

  • Triple quotes allow you to print multiline strings easily.

print("""Happy
Holiday's""")

print("Happy\nHoliday's")

both gives same output as :

Happy
Holiday's

9.Combining Strings and Variables :

  • Combining strings and variables by using + for simple cases or formatted strings for more complex scenarios.

  • For simple case:

colour = "purple"
print("The colour of the bag is "+colour)

The colour of the bag is purple

  • For complex case :
temperature=22.5
print("The temperature is", str(temperature),"degree Celsius",end=".")

The temperature is 22.5 degree Celsius.

10.Printing with .format() and Using print for Debugging:

  • Use the .format() method for string formatting.
name="Abys"
age=17
city="Madurai"
print("Name:{}, Age:{}, City:{}".format(name,age,city))

Name:Abys, Age:17, City:Madurai

  • We can use print to debug your code by printing variable values at different points.
def add(a, b):
    print(f"Adding {a} and {b}")
    return a + b

result = add(1, 2)
print("Result:", result)

Adding 1 and 2
Result: 3

That's it.
These were the topics I learned in my 1st class.

At the beginning, I was confused by all the terms but as time went I got used to it just like we first started to learn English.

Try it out yourself... as u begin to get the output., it's next level feeling.
I personally felt this;
"Nammalum Oru Aal Than Pola"...

.....

8.Python Loops

Python Loops:

Python has two primitive loop commands:

while loops
for loops

while Loop:

With the while loop we can execute a set of statements as long as a condition is true.

i = 1
while i < 6:
  print(i)
  i += 1

Output :

1
2
3
4
5

For loop:

A "For" Loop is used to repeat a specific block of code a known number of times

`fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

Output :
apple
banana
cherry`

Type of Loops:

For Loop:

A for loop in Python is used to iterate over a sequence (list, tuple, set, dictionary, and string). Flowchart.

While Loop:

The while loop is used to execute a set of statements as long as a condition is true.

*Nested Loop : *

If a loop exists inside the body of another loop, it is called a nested loop.

7.Strings Indexing & Slicing

Slicing Strings:

You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the string.

** Get the characters from position 2 to position 5 (not included):**

b = "Hello, World!"
print(b[2:5])
Output : llo

Slice From the Start
By leaving out the start index, the range will start at the first character:

Get the characters from position 2, and all the way to the end:

b = "Hello, World!"
print(b[:5])
Output = Hello

Negative Indexing
Use negative indexes to start the slice from the end of the string:

**Get the characters:

From: "o" in "World!" (position -5)

To, but not included: "d" in "World!" (position -2):**

`b = "Hello, World!"
print(b[-5:-2])

Output =orl`

Python - Modify Strings

The upper() method returns the string in upper case

a = "Hello, World!"
print(a.upper())
Output =HELLO, WORLD!

The **lower() method returns the string in lower case:**

The lower() method returns the string in lower case:

`a = "Hello, World!"
print(a.lower())

Output) =hello, world!`

The strip() method removes any whitespace from the beginning or the end:

`a = " Hello, World! "
print(a.strip())

Output =Hello, World!`

Replace String
Example
The replace() method replaces a string with another string:

`a = "Hello, World!"
print(a.replace("H", "J"))

Output =Jello, World!
`
Split String

The split() method returns a list where the text between the specified separator becomes the list items.

Example:

The split() method splits the string into substrings if it finds instances of the separator:

'a = "Hello, World!"
print(a.split(","))
['Hello', ' World!']
Output =['Hello', ' World!']'

`Indexing :

fruits = ['apple', 'banana', 'cherry']

x = fruits.index("cherry")

print(x)
Output =2`

6.Functions | py

function

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

def python():
print("Hello world")

Calling a Function:

``def python():
print("Hello world, python ")

Python ()``

Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

`def p_name(name, age):
Print ("name :" +name +"age :" +age)
p_name ("dhoni", "39" )

Output:

Name: Dhoni age: 39`

Tasks:
Image description

Playlist :
https://www.youtube.com/live/dGyoEQsc4iQ?si=9dArLhgssryp-eOl

5.Operators, Conditionals, input()

*arithmetic operators *

The six arithmetic operators in Python are: addition (+), subtraction (-), multiplication (), division (/), modulo (%), and exponentiation (*). These operators allow you to perform mathematical operations on numeric data types such as integers and floating-point numbers.

*comparison operators *

Comparison operators are used to compare two values:

==, !=, <=, >=, >, <.

Logical Operators..

Python logical operators are used to combine conditional statements, allowing you to perform operations based on multiple conditions.
and, or, not

Assignment Operators

Assignment operators are used to assign values to variables:

, +=, /=, *=, -=

Conditionals

Used to execute a block of code only if a specified condition is true.

if condition:
code block

Used to execute a block of code if the condition in the if statement is false.

`if condition:
code block

Else:

code block

`

Short for "else if", used to check multiple conditions.

`if condition:

Elif :

Else:
--`
input

Age=int (input ("Enter your age" ))

Input from input() is always a string; convert it using functions like int(), float(), str().

BODMAS

Brackets (Parentheses ()): Operations inside brackets are performed first.
Orders (Exponentiation **): Next, orders (exponents and roots).
Division and Multiplication (/, *, //, %): From left to right. β€’ Addition and Subtraction (+, -): From left to right.

Task:
Image description
Playlist:

https://youtube.com/playlist?list=PLiutOxBS1Mizte0ehfMrRKHSIQcCImwHL&si=pKTi0wvSUvbXfwUS

4.Operators & Conditionals.py

Python Operators

Operators are used to perform operations on variables and values.

Python language supports various types of operators, which are:
Arithmetic Operators.
Comparison (Relational) Operators.
Assignment Operators.
Logical Operators.
Bitwise Operators.
Membership Operators.
Identity Operators.

*Add Two Numbers '+' *

operand or the values to be added can be integer values or floating-point values. The '+' operator adds the values

Image description

Subtraction '-' ** in Python is as simple as it is in basic arithmetic. To subtract two numbers, **we use the '-' operator.

Image description

*multiply '' **
In Python, the most straightforward way to multiply two numbers is by using the * operator. This operator works with integers, floats,

Image description
Division
1 Integer division is represented by "//" and returns the quotient rounded down to the nearest integer.
2 Floating division is represented by "/" and returns the quotient as a floating-point number.
3Integer division is useful when dealing with quantities that cannot be represented as fractions or decimals.
4.Floating division is useful when dealing with quantities that are not integer values.
5 / 2 #output : 2.5
5 // 2 #output : 2

. *How to get the input from the user *?

In Python, we use the input() function to ask the user for input. As a parameter, we input the text we want to display to the user. Once the user presses β€œenter,” the input value is returned. We typically store user input in a variable so that we can use the information in our program.

Image description
]

input data type & type casting

`# Addition

num1 = float(input("Enter Number 1")
num2 = float(input("Enter Number 2 : ")

result = num1 + num2

print("result is", result)

Enter Number 1: 2

Enter Number 2: 4

result is 6.0`

`# subtract

num1 = float(input("Enter Number 1: ")

num2 = float(input("Enter Number 2: ")

result = num1 num2

print("result is", result)

Enter Number 1: 109

Enter Number 2 23

result is 2507.0`

`# division

num1= float(input("Enter Number 1")

num2 = float(input("Enter Number 2")

result = num1 % num2

print("result is", result)

Enter Number 1: 5

Enter Number 2: 2

result is 1.0`

`# remainder

num1 = float(input("Enter Number 1 : "))
num2 = float(input("Enter Number 2 : "))

result = num1 % num2

print("result is ", result)`

2 **3# 2 pow 3
8

If condition:
`The if-else statement is used to execute both the true part and the false part of a given condition. If the condition is true, the if block code is executed and if the condition is false, the else block code is executed.

`Elif' stands for 'else if' and is used in Python programming to test multiple conditions. It is written following an if statement in Python to check an alternative condition if the first condition is false. The code block under the elif statement will be executed only if its condition is true.

`# Trip to tirunelveli

if BUS_available:
go by bus
elif Train_aviable:
go by train
else
go by bike

if BUS_available:
go by bus
if Train_aviable:
go by train #
if bike avaialble
go by bike`

Let's create a calculator.

Show list of functionalities available
Get user inputs
based on user input, perform functionality.

print("Simple Calculator")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
print("6. Exponentiate")

choice = input("Enter choice(1/2/3/4/5/6): ")
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))

"2"

if choice == "1": # no : 1 unit of work.
result = num1 + num2
print(result)
if choice == "2": # yes: 1 unit of work
result = num1 - num2
print(result)

if choice == "3": # no : 1 unit of work.

result = num1 * num2

print(result)

if choice == "4": # no : 1 unit of work.

result = num1 / num2

print(result)

if choice == "5": # no : 1 unit of work.

result = num1 ** num2

print(result)

"2" elif = else if.

elif choice == "2":
result = num1 - num2
print(result)

print("Simple Calculator")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
print("6. Exponentiate")

choice = input("Enter choice(1/2/3/4/5/6): ")
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))

"2"

if choice == "1": # no : 1 unit of work.
result = num1 + num2
print(result)
elif choice == "2":
result = num1 - num2
print(result)
elif choice == "3":
result = num1 * num2
print(result)
elif choice == "4":
result = num1 / num2
print(result)
elif choice == "5":
result = num1 % num2
print(result)
elif choice == "6":
result = num1 ** num2
print(result)
else:
print("option not available")
total_times = 2

while (condition) # True

# False -> exit.

2 > 0 = True

1 > 0 = True

0 > 0 = False

while total_times > 0:
# 2 - 1 = 1
# 1 - 1 = 0
total_times = total_times - 1
print("Simple Calculator")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
print("6. Exponentiate")
print("7. Close Calculator")

choice = input("Enter choice(1/2/3/4/5/6): ")
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))

#     "2"
if choice == "1": # no : 1 unit of work.
    result = num1 + num2
    print(result)
elif choice == "2":
    result = num1 - num2
    print(result)
elif choice == "3":
    result = num1 * num2
    print(result)
elif choice == "4":
    result = num1 / num2
    print(result)
elif choice == "5":
    result = num1 % num2
    print(result)
elif choice == "6":
    result = num1 ** num2
    print(result)
elif choice == "7":
    break
else:
    print("option not available")
    break

def calculator():
print("Simple Calculator")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
print("6. Exponentiate")

choice = input("Enter choice(1/2/3/4/5/6): ")
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))

if choice == '1':
    print(f"Result: {add(num1, num2)}")
elif choice == '2':       

print(f"Result: {subtract(num1, num2)}")
elif choice == '3':
print(f"Result: {multiply(num1, num2)}")
elif choice == '4':
print(f"Result: {divide(num1, num2)}")
elif choice == '5':
print(f"Result: {remainder(num1, num2)}")
elif choice == '6':
print(f"Result: {power(num1, num2)}")

Simple Calculator
Select operation:

  1. Add
  2. Subtract
  3. Multiply
  4. Divide
  5. Modulus
  6. Exponentiate Enter choice(1/2/3/4/5/6): 1 Enter first number:2 Enter second number:3 Result: 5.0

3.PYTHON-FUNDAMENTALS: CONSTANTS VARIABLES AND DATA TYPES

PYTHON-FUNDAMENTALS:
constants variables and data Types

Variables:

Definition of Variables in Python

A variable is a named memory location in which a value is stored.
Any data type in Python, such as an integer, string, or list, can be used as the value.
Variables are used to store information that will be needed during the program.
In Python, you do not need to define a variable before using it.
When you assign a value to a variable, it is created.
You can change a variable's value at any moment. This will override its previous value.

How to name a variable ?

When naming variables in Python, there are a few rules and best practices to follow:

Start with a letter or an underscore: Variable names must begin with a letter (a-z, A-Z) or an underscore (_).

Followed by letters, digits, or underscores: After the first character, you can use letters, digits (0-9), or underscores.

Case-sensitive: Variable names are case-sensitive. For example, myVariable and myvariable are different variables.

Avoid Python keywords: Do not use Python reserved words or keywords as variable names (e.g., class, def, for, while).

Examples of Valid Variable Names:

my_variable
variable1
_hidden_variable
userName

Examples of Invalid Variable Names:

1variable (starts with a digit)
my-variable (contains a hyphen)
for (a reserved keyword)

Assigning Values to Variables
In Python,

the assignment operator = is used to assign values to variables.
The syntax is straightforward: variable_name = value.

Examples:

# Assigning integer value
age = 25`

Assigning string value

name = "John Doe"

Assigning float value

height = 5.9

Assigning boolean value

is_student = True`

Multiple Assignments:

Python allows you to assign values to multiple variables in a single line. This can make your code more concise and readable.

Example:
# Assigning multiple variables in a single line
a, b, c = 5, 10, 15`

Swapping values of two variables

x, y = y, x`

Unpacking Sequences:

Python also supports unpacking sequences, such as lists or tuples, into variables. This feature is handy when working with collections of data.

Example:

'# Unpacking a tuple
person = ("Alice", 30, "Engineer")
name, age, profession = person

Unpacking a list

numbers = [1, 2, 3]
one, two, three = numbers'

variable typs:

Python is a dynamically typed language, which means you don’t need to declare the type of a variable when assigning a value to it. The type is inferred at runtime based on the assigned value.

Example:

# Dynamic typing
my_variable = 10 # my_variable is an integer
my_variable = "Hello" # my_variable is now a string

You can check the type of a variable using the type() function.

``Example:
my_var = 42
print(type(my_var))

Output:

my_var = "Python"
print(type(my_var))
# Output: `

Constants:

In Python, constants are variables whose values are not meant to change. By convention, constants are typically written in all uppercase letters with underscores separating words.

Note: However, Python does not enforce this, so constants are not truly immutable.

Defining a constant

PI = 3.14159
MAX_USERS = 100

Data Types:

Data types are the different kinds of values that you can store and work with.

Just like in your home, you have different categories of items like clothes, books, and utensils, in Python, you have different categories of data.

  1. Numeric Types Integer (int): Whole numbers

Image description

Float (float): Decimal numbers.

Image description

Complex (complex): Complex numbers.

Image description

2. Text Type

String (str): Sequence of characters.

Image description
3. Boolean Type

Boolean (bool): Represents True or False

Image description

  1. None Type NoneType: Represents the absence of a value

Image description

  1. Sequence Types List (list): Ordered, mutable collection

Image description
Tuple (tuple): Ordered, immutable collection.

Image description
Range (range): Sequence of numbers.

Image description
Mapping Type
Dictionary (dict): Unordered, mutable collection of key-value pairs.

Image description

7, Set Type
Set (set): Unordered collection of unique elements

Image description
Frozenset (frozenset): Immutable set.

Image description

Checking Data Type
Syntax: type(variable_name)

Image description

Why Do Data Types Matter?

Data types are important because they tell Python what kind of operations you can perform with the data. For example:

You can add, subtract, multiply, and divide numbers.
You can join (concatenate) strings together.
You can access, add, remove, and change items in lists.
You can look up values by their keys in dictionaries.
Using the right data type helps your program run smoothly and prevents errors.
Agenda:

Image description

Tasks:

Image description

Playlist:
https://www.youtube.com/live/5G0PoJofxXk?si=Wo82t4JJYeP9WcR2

❌