Python Programming/Variables and Strings/Solutions

From Wikibooks, open books for an open world
< Python Programming‎ | Variables and Strings
Jump to: navigation, search

< Back to Problems

1. Write a program that asks the user to type in a string, and then tells the user how long that string was.

We will save the string in question as "string1". The str() command converts the user input into a string. Then we have the program print the length. Note that the print statement doesn't require extra spaces - these are added automatically.

string1 = str(raw_input("Type in a string: "))
print ("The string is", len(string1), "characters long.")

2. Ask the user for a string, and then for a number. Print out that string, that many times. (For example, if the string is hello and the number is 3 you should print out hellohellohello.)

Ask the user for some text and use the str() command to turn it into a string (we will save it as "text"). Then ask the user for a number and use the int() command to turn it into an integer. We'll save this as "number".

Lastly print "text" times "number".

text = str(raw_input("Type in some text: "))
number = int(raw_input("How many times should it be printed? "))
print (text * number)

3. What would happen if a mischievous user typed in a word when you ask for a number? Try it.

Let's try it! You can use a simple program such as this one:

number = int(raw_input("Type in a number: "))
doubled = number * 2
print (doubled)

When we run it with text we get an error:

Type in a number: I am not a number!  

Traceback (most recent call last):
  File "C:/Documents and Settings/D Irwin/Desktop/test2.py", line 1, in <module>
    number = int(raw_input("Type in a number: "))
ValueError: invalid literal for int() with base 10: 'I am not a number!  '

The program calmly reminds us that 'I am not a number! ' is not a number!