Variables and Data Types
A variable stores data under a name. We study assignment, naming rules, the main data types and operations on numbers, and learn to turn entered text into a number.
All topics (2 of 11)
Chapter 1. Python Basics
Chapter 2. Lists and Strings
Chapter 3. Functions and Modules
Chapter 4. Working with Files
A variable is a name given to a place in memory where a value is stored. In Python, a value is given to a variable with the equals sign: age = 15. This is not an equation from mathematics but a command meaning “store the value on the right under the name on the left”, so the line age = age + 1 increases the value of the variable by 1.
A variable name starts with a letter or an underscore (_), and it may contain letters, digits and _; spaces are not allowed. Names are case-sensitive: age and Age are two different variables. Python keywords such as if and for cannot be used as names.
The main data types are the whole number int (for example, 15), the decimal number float (3.14), the text str ("Ali") and the logical value bool (True or False). The type() function finds out the type of a value. The input() function always returns text, so if you need a number, convert the result like this: int(input("Yoshingiz: ")).
The operations +, -, * and / work on numbers. In addition, // means whole-number division, % gives the remainder of a division, and ** raises to a power: the result of 7 // 2 is 3, of 7 % 2 is 1, and of 2 ** 3 is 8. Ordinary division always gives a decimal number: the result of 7 / 2 is 3.5.
Key takeaways
- A variable is a named place in memory for a value; the value is set with the
=sign. - A name starts with a letter or
_, and uppercase and lowercase letters are different. - The main types are
int,float,strandbool. input()returns text; to get a number, convert it withint()orfloat().- Numbers support
+,-,*,/, as well as whole-number division//and remainder%.
Practice tasks
- For the variables
a = 7andb = 2, write a program that prints the results of+,-,*,/,//and%; guess the results before you run it. - Write a program that asks the user for two numbers and prints their sum and arithmetic mean (use
int(input())). - Use
type()to find the types of the values15,3.14,"15"andTrue, and write down why"15"is not a number.
Review questions
Test yourself: think first, then reveal the answer.
1What results do the expressions 7 // 2 and 7 % 2 give?Show answerHide answer
7 // 2 gives 3 (the whole part), and 7 % 2 gives 1 (the remainder).2What type of value does the input() function return?Show answerHide answer
Always text, a value of type str.3Can 2age be a variable name?Show answerHide answer
No, a variable name cannot start with a digit.
0 of 11 topics completed
Sign in to mark