Login

Back

Getting data into Python - Answers

Q1. The p in Print was a capital letter. All keywords in Python are lower case.

print('What is your name?')
name = input()
print ('Your name is',name)

Q2. When input is used, it always reads in a string. In the last line, you cannot add a string to the integer 4 so you get an error. You need to change age = input() to age = int(input())

#Getting data into Python

print('What is your name?')
name = input()
print ('Your name is',name)

print('What is your age?')
age = input()
print ('Your name is',age)

print (age + 4) 

Q3. This program works as long as you enter an integer for your age.

#Getting data into Python

name = input('What is your name?')
print ('Your name is',name)

age = int(input('What is your age?'))
print ('Your name is',age)

print (age + 4)

Q4. Change age = int(input('What is your age?')) to age = float(input('What is your age?')) to cater for floating point numbers.
Q5. When you use the input keyword, the string data type is always read in.
Q6. You must always convert a number that you want to manipulate mathematically, which has been inputted using the input keyword.
Q7. To convert a string into an integer, use int()
Q8. To convert a string into a floating point number, use float()
Q9. In the line, 

name = input('What is your name?')

the cursor waits immediately after the question mark. You could change it to:

name = input('What is your name? >>> ')

name = input('What is your name?\t')

name = input('What is your name?\n')

name = input('What is your name?\n\n')

The backslash (escape sequence) is very useful for laying work out neatly and students should be taught how to use it early on, starting with \t and \n.

Q10.  The question asking for your age gets displayed immediately after your name is displayed. To space it out a little, you could change

age = int(input('What is your age?'))   

to

print(\n)
age = int(input('What is your age?'))

or

age = int(input('\nWhat is your age?'))

Q11. Num1 is an integer that hold 234 and num2 is an integer that holds 567. Write a program that initialises num1 to 234 and num2 to 567 and then displays the fact that they are both integers. Then using these two numbers, display 234567.

num1 = 234
num2 = 567
print(type(num1))
print(type(num1))

print('num1 + num2 equals',num1 + num2) #this isn't what we want.

#convert the integers to strings ....

print('The string num1 concatenated with num2 is',str(num1)+ str(num2))

Q12. Num1 is a float that hold 10.34 and num2 is an float that holds 6.4. Write a program that displays 10.346.4.

num1 = 10.34
num2 = 6.4
print(type(num1))
print(type(num1))

print('num1 + num2 equals',(num1 + num2)) #this isn't what we want.

#convert the floats into strings ....

print('The string num1 concatenated with num2 is',str(num1)+ str(num2))

Q13. Concatenation means adding together two strings?

Back