DEV Community

Seenivasan A
Seenivasan A

Posted on Edited on

Strings and Loops in Python

String

  1. Strings are sequence of characters written inside quotes. It can include letters, numbers, symbols and spaces. Python does not have a separate character type.
  2. Strings are immutable, meaning their values cannot be changed after creation. Any modification to a string creates a new string instead of altering the original one.

Common String Methods

Python string methods is a collection of in-built Python functions that operates on strings.

  • upper()
  • lower()
  • find()
  • split()
  • strip()
  • format()
  • join()

Discussed problems

  • Reverse a String
  • Password Authentication
  • Parse csv "java","1","2","3".."6"
  • Convert uppercase to lowercase

Examples

  • Parse csv "java","1","2","3".."6"
data = input("Enter CSV data: ")
values = data.split(",")
total = 0
for i in values:
    i = i.strip('"')
    if i.isdigit():
        total += int(i)

print("Total =", total)
Enter fullscreen mode Exit fullscreen mode

Input-"java","1","2","3","4","5","6"

Output-Total = 21

Loop

  1. Loops are used to execute a block of code repeatedly until a condition is met or all items in a sequence are processed. The main types are For loops (iterating over sequences) and While loops (executing code based on a condition).
  2. break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the "for" or "while" statement.

While Loop Syntax

while condition:
statement

For Loop Syntax

for variable in range(start, stop, step):
statement

Discussed problems

  • Sum of (N) numbers
  • Multiplication table
  • Print even numbers

Examples
Sum of (N) numbers

def sum_of_numbers(n):
    i=1
    sum=0
    while i<=n:
        sum+=i
        i+=1
    print("The sum of first",n,"numbers is:",sum)

n=int(input("Enter the number of terms: "))
sum_of_numbers(n)
Enter fullscreen mode Exit fullscreen mode

Input-> N=10

Output-> Sum=55

Algorithms Discussed

Merge Sort

Binary Search And Linear Search

References
https://www.geeksforgeeks.org/dsa/merge-sort/

https://tutorialhorizon.com/algorithms/linear-search-vs-binary-search/

Top comments (0)