Skip to main content

Posts

Showing posts with the label Python

Python while and for Loop Statments

Loops are indeed very powerful as it allows us to do a repetitive task that is to execute statement or group of statements multiple times. Python provides following types of loops to handle repetitive tasks: for and while loops. The semantics of the while loop: while condition: body containing (statment / s) The semantics of the for loop: for item in list : statement / s Example 1 (for): #Program to print each character in a string (which is a sequence of characters) string = "Python" #for each charachter in a string do this: print(char,end = '') for char in string: print (char,end = '' ) #Output:Python Example 2 (for): #Program to print the first 5 positive even numbers #Note:loops runs from 0-9 increment by 1 for number in range ( 0 , 10 ): #even if evenly divisible by 2 if ( number % 2 == 0 ): print (number, ' is even' ) #Alternative way, the range function also takes ...

Python Common String Operations

A string is most popular type in Python. A string can be created by enclosing a sequence of characters in a single or double quotes (' ' or " "). A string module contains a number of powerful methods/function to perform operations on a string. NOTE: string in Python is IMMUTABLE (it cannot be changed of the string) as in many other languages (Java). Length of a string Range slice Accessing a character of a string Converting all string characters to all uppercase letters Converting all string characters to all lowercase letters Capitalizing string String concatenation Fining the index where the sub-string begins/occurs in a string  Check if string contains sub-string String comparison (Equality, less than, greater than, not equal) Breaking a string by ",", "-","  " (space), etc.                              ...