CSCI 127 Joy and Beauty of Data · Unit 1: Data types · on Exam 1
1.1 Data types and expressions
Study notes for Data types and expressions in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in StudyCat.
Big ideas
- Python has four everyday types: int (whole numbers), float (decimals), str (text in quotes) and bool (
True/False).type(x)tells you which one you have. - Arithmetic:
+ - *as usual,/always gives a float,//is floor division,%is the remainder and**is a power. Normal precedence rules apply; parentheses win. - A variable is a name bound to a value with
=. Assignment is not an equation:x = x + 1means “make x one bigger”. Comparisons use==. input()always returns a string, so convert withint()orfloat()before doing math.str()goes the other way.- f-strings put values inside text:
f"{name} is {age}", with formatting such as{price:.2f}.print()takes many arguments and puts spaces between them.
Code you should know
Types and arithmetic
print(7 // 2, 7 % 2, 7 / 2, 2 ** 10)
print(type(7), type(7 / 2), type("7"), type(True))
print(3 + 4 * 2, (3 + 4) * 2)Output
3 1 3.5 1024 <class 'int'> <class 'float'> <class 'str'> <class 'bool'> 11 14
Input is text until you convert it
name = input("Name? ")
age = int(input("Age? "))
print(f"Next year {name} will be {age + 1}.")
print("Age doubled as text:", str(age) * 2)Output
Next year Nik will be 20. Age doubled as text: 1919
Formatting numbers
price = 4.5
qty = 3
print(f"Total: ${price * qty:.2f}")
print(f"{10 / 3:.3f}", round(10 / 3, 2))Output
Total: $13.50 3.333 3.33
Worked example
Without running it, what does this print?
x = 17 y = 5 print(x // y, x % y, x / y) print(str(x) + str(y), x + y)
Show the solution
3 2 3.4 on the first line: 17 divided by 5 is 3 remainder 2, and / gives the float 3.4. The second line is 175 22: joining two strings glues them, adding two ints adds them.Common mistakes
- Forgetting that
input()gives a string, so"3" + "4"is"34", not 7. - Using
=when you mean==inside a comparison. - Expecting
10 / 2to print5; it prints5.0. Use//when you want an int. - Mixing tabs and spaces, or forgetting the colon and indentation later in the course. Set your editor to 4 spaces now.
Exam tipExam 1 is on paper. Practise predicting output by hand: write the value of every variable after each line, especially for
//, % and string repetition.Keep going in StudyCat
StudyCat is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.