Python

 

PYTHON BASICS - I

Python is an important programming language to know — it's widely used in fields like data science, web development, software engineering, game development, automation. 

Firstly, it’s modular – i.e. it can be easily integrated with other technologies and solutions.

Secondly, it’s open-source. There’s a vibrant community of developers who contribute to the development of the technology, and the Python Software Foundation oversees the quality and the direction in which the language is going.

Thirdly, Python is ‘interpreted’, which means it's translated to machine code right before the program is launched. This facilitates writing portable and universal programs, which are easier to use on different operating systems.


Download Python


Data Types

The most used data types are as follows-

  • Integers (int) - a whole number without a decimal point
  • Floating-point numbers (float) - a number with a decimal point
  • Strings - a sequence of characters

  • Boolean - Boolean values are true or false

Variables

Variables can store data of different types, and different types can do different things.

name = ‘Jessica’

total = 75

percentage = 87.4

is_authorized = True

In the above example, 

name is a variable of data type string, total is a variable of data type integer, percentage is a variable of data type float, is_authorized is a variable of data type boolean.
= is the assignment operator.


Comments

We use comments to add notes or explain assumptions made in our code. It is not executed. 

# This is a comment 


IMPORTANT: Python uses indentation to indicate a block of code. Indentation refers to the spaces at the beginning of a code line.


Input() Function

We can receive input from the user by calling the input() function.

name = input( "Enter your name." )
print( "Hello " +  name +"!" )

Output : Enter your name. "Emma" 
               Hello Emma!


Strings

In Python 3, strings are immutable. If you have already defined one, you cannot change it later on. While you can modify a string with commands such as replace() or join(), they will create a copy of a string and apply the modification to it, rather than write the original one.

You can create a string using single, double, or triple quotes.

Example :

str1 = "This is a string"

str2 = 'This is also a string!'

str3 = '''Another way of writing a string.
             Multi-line string'''

We can access individual characters in a string using square brackets []

str1[0]      #returns the first character --T

str1[-1]     #returns the first character from the end --g

Length

It returns the length of any string, list, tuple, dictionary, or another data type.  

print( len("Hello") )

Output: 5

Count

It returns the number of occurrences of a character. 

str = "Count the number of  an alphabet"

print( str.count('e') )

Output: 3

Find

It returns the index value of the first occurrence of  the character or a string. It returns -1 if not found.

str = "Hello World"

print( str.find("l") )

Output: 2

Slicing 

It is about obtaining a sub-string from the given string by slicing it respectively from start to end.

  • string[start:end:step]

start: Starting index where the slicing of object starts.

stop: Ending index where the slicing of object stops.

step: It is an optional argument that determines the increment between each index for slicing.

word = "ASTRING"

s1 = word[:3]                      #AST

s2 = word[1: 5: 2]              #SR

s3 = word[-1: -12: -2]        #GITA

s4 = word[ : : -1]                #GNIRTSA

Concatenation 

It is a way to add two or more strings using the '+' operator.

str1 = "Welcome!"

str2 = "Let's learn Python."

str3 = str1 + str2  # str3 = "Welcome! Let's learn Python."

Replication 

It allows you to repeat the same string several times. It is done by the '*' operator.

print("ABC" * 3)   

Output: ABCABCABC


Split

It returns a list of strings after breaking the given string by the specified separator.

word = "Hello World"

print(word.split(' '))        # Split on whitespace

Output: ['Hello', 'World']


Upper

It converts the string to uppercase.

str = "This is cool"

print(str.upper( ))

Output: THIS IS COOL


Lower

It converts the string to lowercase.

str = "This is COOL"

print(str.lower( ))

Output: this is cool


Title

It is used to capitalize the first letter of every word.

str = "this is cool"

print(str.title( ))

Output: This is cool


Arithmetic Operations

Operators

Operation

Example

**

Exponent

4 ** 2 = 16

%

Modulus (Remainder)

32 % 3 = 2

//

Integer Division

32 // 3 = 10

/

Division

32 / 3 = 10.66

*

Multiplication

2 * 3 = 6

-

Subtraction

7 - 2 = 5

+

Addition

7 + 2 = 9



Comparison Operators

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

If else statements


The goal of a conditional statement is to check if it's true or false. 

if age < 5:                                    # checks the condition
    ticket_price = 10
elif age > 60:                               # another condition if the previous one was false
    ticket_price = 40
else:                                             # another condition if the previous one(s) was false
    ticket_price = 70


Logical Operators 


Operator

Description

Syntax

AND

True if both the operands are true 

x and y

OR

True if either of the operands is true

x or y

NOT

True if the operand is false

not y



Loops

  • For Loop :

    It is a way for iterating over a sequence such as a string, list, tuple, dictionary, and so on. It can be used to iterate over a range and iterators.

    Example: 
                1.    for x in "basket":                          
                         
print(x)       
                       
                        
Output:  b
                                        a
                                        s
                                        k
                                        e
                                        t


                                                                                                           
                2.    for x in range(4):                         
                          print(x)     
                                                
                        Output:  0 
                                        1
                                        2
                                        3         
                                                          
                                              
  • While Loop :

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

    Example: 
                1.    i = 1
                       while i < 5:
                                  print(i)
                                  if (i == 3):      
                                       break        
                                  i += 1                         # i = i + 1                                                        

                    Output:    1
                                      2
                                      3

     NOTE: 
  1. With the break statement we can stop the loop even if the while condition is true.
  2. Remember to increment the value of i, or else the loop will continue forever.                                            

Comments

  1. Wow! You explained in such an easy and understanding way that I wanna start learning about it RIGHT NOW 😍

    ReplyDelete
  2. Absolutely great efforts in keeping the information up to the mark and to the point👌

    ReplyDelete
  3. Superb!! Very well explained!! 👏

    ReplyDelete

Post a Comment