Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

Replication

The * (asterisk) sign, when applied to a string and number (or a number and string, as it remains commutative in this position) becomes a replication operator:

 

string * number
number * string

It replicates the string the same number of times specified by the number.

For example:

  • "James" * 3 gives "JamesJamesJames"
  • 3 * "an" gives "ananan"
  • 5 * "2" (or "2" * 5) gives "22222" (not 10!)

REMEMBER

A number less than or equal to zero produces an empty string.

This simple program "draws" a rectangle, making use of an old operator (+) in a new role:

print("+" + 10 * "-" + "+")
print(("|" + " " * 10 + "|\n") * 5, end="")
print("+" + 10 * "-" + "+")

Note the way in which we've used the parentheses in the second line of the code. 

Try practicing to create other shapes of your own artwork!

 

Type conversion: str() 

You already know how to use the int() and float() functions to convert a string into a number.

This type of conversion is not a one-way street. You can also convert a number into a string, which is way easier and safer - this kind of operation is always possible. 

A function capable of doing that is called str():

str(number)

To be honest, it can do much more than just transform numbers into strings, but that can wait for later. 

The "right-angle triangle" again

Here is our "right-angle triangle" program again:

 

leg_a = float(input("Input first leg length: "))
leg_b = float(input("Input second leg length: "))
print("Hypotenuse length is " + str((leg_a**2 + leg_b**2) ** .5))

We've modified it a bit to show you how the str() function works. Thanks to this, we can pass the whole result to the print() function as one string, forgetting about the commas. 

You've made some serious strides on your way to Python programming. 

You already know the basic data types, and a set of fundamental operators. You know how to organize the output and how to get data from the user. These are very strong foundations for Module 3. But before we move on the next module, let's do a few labs, and recap all that you've learned in this section. 

Replication

David Khieu
Module by David Khieu, updated more than 1 year ago

Description

Replication
No tags specified