< Prev  |  Home  |  Next >

Python Text

The first ever program we wrote printed text, which as you’ve probably guessed, has a fancy programming name; a string. If you think of text as like a string of characters joined together, it’ll be helpful to you later.

Here’s another program to try out:

You’ll notice that a string is always enclosed in speech marks (“Hello”) or quotes (‘Hello’). It doesn’t matter which. So “4” is a string, but 4 is an integer, and 4.0 is a floating point number.

Python can add and multiply strings as well as integers and floating point numbers. Hopefully you’re stopping to think about what is being printed. Why did line 3 of the above program print:

Hellollollollollo

and not:

HelloHelloHelloHelloHello

It’s because the multiplication bit (“llo” * 5) is done first, and then added to the string “He”.

Challenge

Can you display your name 5 times, without simply typing it out 5 times?

solution


Output:

Amir Amir Amir Amir Amir

Can you get a program to print “Ha Ha Ho Ho”, but only typing each of the words ‘Ha’ and ‘Ho’ once?

solution


Output:

Ha Ha Ho Ho

Now add this line to your program and run it again:

Ah. That’s awkward. You’ve broken it. What’s the problem here? Does this line even make sense? Let’s go through it step by step.

  1. “Hello” is multiplied by 2, giving “HelloHello”
  2. 2 is added to the string “HelloHello”

Well there’s the problem. Step 2 doesn’t make any sense. You can’t add a number to a string, so you should probably remove it again. Sorry to have put you through that, but it’s useful to see what happens when a line of Python has an error in it.

When printing strings, there are some special characters you can use. What do these lines print?

Hopefully you can see a 2×2, a 3×3 and a 4×4 grid of squares. The \n means print a new line. If you want to actually print a speech mark or a quote, you have to use \” or \’, otherwise Python will think you are trying to end a string when you’re not. Silly Python.

Challenge

Write a program to print an ASCII art triangle made up of stars.

solution


Output:


*
**
***
****

Advanced: Can you print a Christmas tree?

solution


Output:


  *
 ***
*****
 ***
*****
 ***
*****
  *
  *

< Prev  |  Home  |  Next >