Python Programming/Variables and Strings/Solutions

< 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 " ". The  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.

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  and the number is   you should print out  .)''

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

Lastly print  times.

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:

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    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  is not a number!