“Introduction to Python Programming” Available Units for Reading
Variables in Python
A variable is a container used to store data values. In Python, you don’t need to declare the type of a variable, it is automatically assigned.
Example:
name = "Aman"
age = 20
height = 5.8
print(name)
print(age)
print(height)Rules for naming variables:
- Must start with a letter or underscore (
_) - Cannot start with a number
- Cannot use keywords (like
if,for,while) # will learn about keywords in upcoming topics - Case-sensitive (
Nameandnameare different)
x = 5
5x = 7 # wrong
x5 = 8
_g = 9 Data Types in Python
we will mainly study numbers, strings and list in these “Introduction to Python Programming” Syllabus/notes. Your can learn more about python in detail from our advance courses available on site. or you can search it via search bar on our website.
A data type defines the kind of value a variable can hold. We just need to type the require data with the variables.
1. Numbers
Python supports different types of numbers:
- Integer (
int) → whole numbers - Float (
float) → decimal numbers
Example:
a = 10 # Integer
b = 3.14 # Float
print(a)
print(b)Output :
10
3.142. Strings
A string is a sequence of characters enclosed in single of double quotes.
Example:
name = "Python"
message = 'Hello World'
print(name)
print(message)Python
Hello World3. List
A list in Python is a collection used to store multiple values in a single variable. It can store multiple types of data in it.
x = [3,5,6,7,8]
y = [4,5.7,"Hello",8]
print(x)
print(y)[3, 5, 6, 7, 8]
[4, 5.7, 'Hello', 8]Checking Data Types
You can check the type of any variable using type() function:
x = 10
y = "Hello"
z = [4, 5.7, 'Hello', 8]
print(type(x))
print(type(y))
print(type(z))<class 'int'>
<class 'str'>
<class 'list'>Type Conversion (Type Casting)
Type conversion means changing one data type into another.
1. Convert to Integer
x = "10" # it is string because it is in quotes
y = int(x) # we are using variable x in int( ) function
print(y)
print(type(y))10
<class 'int'>2. Convert to Float
x = 5
y = float(x)
print(y)
print(type(y))5.0
<class 'float'>3. Convert to String
x = 100
y = str(x)
print(y)
print(type(y))100
<class 'str'>Not all conversions are valid:
x = "hello" # converting letters string to integer
y = int(x) # This will cause an errorBut we can do this
x = "100"
y = int(x)
print(y)
print(type(y))