Learning Python: Conditions, String Methods, String Formatting, Custom Functions

Learning Python: Conditions, String Methods, String Formatting, Custom Functions

This is a short summary of what I've learned in week 3 of the open university Python course.


In a 'while True' loop, its execution is terminated by a 'break' statement. This type of repetition is ideal for situations where, for example, the user is repeatedly asked for an input and giving a specific type of input (such as an empty string or a specific number) terminates the loop.

while True:
    num = int(input("Enter a number: "))

    if num == 0:
        break
    elif num % 2 == 0:
        print("The number is even.")
    else:
        print("The number is odd.")        

A repetition clause can also be directly written with a more versatile condition that must hold true for the loop to be executed.

num = 1

while num <= 10:
    print(num)
    num += 1        

If any part is incorrect, an unintended perpetual loop can be created.


A string is a sequence of zero, one or more characters. The number of characters found in the string can be returned by the len() function.

>>> str = "Python"
>>> print(len(str))
6        

All characters in a string have an index (i.e. an ordinal number). The index can be used to refer to individual characters in a string. In Python, indexing starts from zero.

A single character can be referred to using square brackets ([]).

>>> print(str[0])
P        

If an attempt is made to reference a character that is not in the string, an error message will result.

>>> print(str[7])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range        

In Python, characters can also be referred to using negative indices. An index of -1 indicates the last character, -2 the second to last character, and so on. Therefore, each character in the string has two indices: positive and negative.

>>> print(str[-1])
n

>>> print(str[-3])
h        

A substring is a string found "inside" the original string.

A substring can be extracted from a string by using the start and end indices within the string. A colon is written between the indices.

NOTE: The character corresponding to the starting index is included in the substring, but the character corresponding to the ending index is not.

>>> str[2:4]
'th'        

A substring of the string can be found using the 'find()' method. The method returns the index where the first occurrence of the substring is found, or -1 if no substring is found. The method call is written in the form 'string.find(substring)'.

>>> str.find("on")
4

>>> str.find("in")
-1        

To only know if a substring is found at all, the easiest option is to use the 'in' operator.

>>> print("on" in str)
True        

The number of occurrences of a substring in a string can be calculated using the 'count()' method. The syntax is 'string.count(substring)'.

>>> word = "obsidian"
>>> word.count("i")
2        

Substitution of a substring by another substring is done with the 'replace()' method. The syntax is 'string.replace(substring1, substring2)'.

>>> word.replace("i", "y")
'obsydyan'        

Python can print several different objects with a single call to the 'print()' function by listing the different objects separated by commas.

>>> print("Current words:", str, word)
Current words: Python obsidian        

For more complex output sentences or string formatting, Python's f-strings are the best choice.

>>> print(f"First word: {str}, second word: {word}")
First word: Python, second word: obsidian        

Python's f-strings can also be used for many other purposes. For example, f-strings can format the output of floating point numbers.

>>> num = 1.23456789

>>> print(f"Whole number: {num}")
Whole number: 1.23456789

>>> print(f"Only two decimals: {num:.2f}")
Only two decimals: 1.23        

A function is an independent part of a program that can be called from within the program. When called, a function is often passed a parameter or multiple parameters and can return a value.

>>> def hello(name):
...   print(f"Hello, {name}!")

>>> hello("Kelvin")
Hello, Kelvin!        

Another typical way to use functions is to use them to split a larger program into smaller entities. This makes the program code clearer and easier to maintain. It is also easier to reuse parts of a program in other programs when it is broken down into smaller units.

>>> def get_area(width, height):
...     return width * height

>>> def get_volume(width, height, length):
...     return width * height * length

>>> get_area(10, 20)
200

>>> get_volume(10, 20, 30)
6000        

Example: Write the function that prints the first n digits of the Fibonacci number sequence.

def fibonacci(n):
    # The first two numbers in the Fibonacci series
    n1 = 1
    n2 = 1
    counter = 0
    while counter < n:
        print(n1)
        sum = n1 + n2
        # Update the values
        n1 = n2
        n2 = sum
        counter += 1        

Example: Write two functions that accept a string as a parameter. The first function prints the characters of the string one by one from first to last. The second function prints the characters of the string one by one from last to first.

>>> def print_char(word):
...     for char in word:
...         print(char)

>>> def reverse_char(word):
...     for char in word[::-1]:
...         print(char)

>>> print_char("Python")
P
y
t
h
o
n

>>> reverse_char("Python")
n
o
h
t
y
P        

Example: Write a program that prints a string in "pyramid format" by starting with one character and adding one more character on each line until the full string is printed.

>>> def pyramid_string(str):
...     index = 0
...     while index < len(str):
...         index += 1
...         print(str[:index])

>>> pyramid_string("Python")
P
Py
Pyt
Pyth
Pytho
Python        

要查看或添加评论,请登录

Riikka Sihvonen的更多文章

社区洞察

其他会员也浏览了