DEV Community

mahdin1209
mahdin1209

Posted on

INTRODUCTION TO PYTHON (For and while loops and STRINGS)

While loops:

With the while loop we can execute a set of statements as long as a condition is true.
Image description
break statement:
It is a loop control statement. Suppose you want to terminate a loop and skip to the next code after the loop; break will help you do that. It is used after the loop statements.
Image description
continue statement
With the continue statement we can stop the current iteration, and continue with the next.
Image description

for loops:

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
Image description
Range() function
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
range(start,stop,step)
start: Optional. An integer number specifying at which position to start. Default is 0
stop: Required. An integer number specifying at which position to stop (not included).
step: Optional. An integer number specifying the incrementation. Default is 1.
Image description

STRINGS

A string (str) in Python is a single character or a collection of characters. Strings in python usually represented by double or single quotation.
Image description

If we want to print multiple lines of strings, we just have to follow these steps:
Image description

len() function
The len() function returns the length of a string:
Image description
Indexing
We can access every element in strings by indexing. There are two types of indexing one is positive indexing and another one is negative indexing.
Positive indexing:
Positive indexing starts from 0 and ends at (length of a string -1).
Image description
Negative indexing:
Negative indexing starts from -1 and -length of string.
Image description
Image description
_Strings are immutable. Once a string is created the characters on it can't be changed or deleted. _

Top comments (0)