In this unit we will learn how to work with different data types - e.g. text, integers, double (numbers with decimal points), boolean (true/false).
Here's a simple program that will ask the user for two numbers to add (it will save the user's response in the number1
and number2
variables and then will display the sum.
number1=input("Type in the first number");
number2=input("Type in the second number");
sum=number1+number2;
print("The sum of these two numbers is "+sum);
This program will not work correctly. Why?
Python takes anything input by the user using the keyboard as text by default. In order to perform mathematical operations, such as additions, we need to convert these two values to the correct data type - such as integer. If we don't do the conversion, Python will think we just want to concatenate (paste together) two strings of text.
This is how we need to modify the program for it to work correctly:
number1=input("Type in the first number");
number2=input("Type in the second number");
total=int(number1)+int(number2);
print("The sum of these two numbers is "+str(total));
We had to convert number1
and number2
to the integer data type using the int()
function before we could do integer division. Conversely, when using the print() function, we need to make sure we are concatenating (putting together) pieces of information of the same data type - we thus need to convert the total
to a string, using the str()
function, so we can put it together with a literal string.
Let's now expand our adder program to include all four operations - addition, subtraction, multiplication and division. We will convert the user input to integers right at the beginning (highlighted in bold):
number1=int(input("Type in the first number"));
number2=int(input("Type in the second number"));
total=number1+number2;
difference=number1-number2;
product=number1*number2;
quotient=number1/number2;
print("The sum of these two numbers is "+str(total));
print("The difference of these two numbers is ", difference);
print("The product of these two numbers is ",product);
print("The quotient of these two numbers is ",quotient);
Create a program that will ask the user to input a sentence and then it will display it 10 times.
Bonus: ask the user how many times they want to repeat the sentence.
Sample output:
text=input("Type in the sentence to repeat and press Enter");
print(text*10)
The bonus:
text=input("Type in the sentence to repeat and press Enter");
repeats=input("How many times to repeat?")
repeats=int(repeats)
print(text*repeats)