Python Tutorial for Beginners #1 : Variables , Data Types, Inputs and Print Functions


Ever wondered how Netflix somehow knows you are in the mood for a thriller at 2 AM? How Instagram recognizes your face in photos before you even tag yourself? The secret behind every digital experience that feels like magic is nothing but Code. And more interestingly 9 out of 10 times , this code is partly or fully written in Python.
Now you might be wondering that writing code might be a very difficult skill but what if I told you that in the next 20 minutes- yes in 20 minutes - you will be able to write your Python Program that does not just display text on screen , but actually converses with you. It will ask your name, remember it , and use it to create personalized messages. You will be literally having conversation with code you wrote for yourself. No intimidating jargon or rocket-science theory required . You don’t need any pre-requisites for learning Python. All you need is you, your computer and the programming language that is beginner friendly. If you don’t have python installed then click here to know how to install python and all its dependencies and then you can come back here.
📋 Table of Contents
The Print Function - Your First Python Command
The print() function in python is like Python’s way of talking to you. It’s how your program communicates with the outside world. If you don’t understand what is function now , don’t worry we have a dedicated section for functions in the later blogs where we will be covering functions in detail. For now you can just remember that whatever you write in between opening and closed parentheses of print(), wrapped in quotation marks is displayed on the screen.
print("Hello Python! My friend IronWill is helping me becoming familiar with you")
Output:
Hello Python! My friend IronWill is helping me becoming familiar with you
You can even add a number or any other special character in print function and it will be displayed on the screen as well. It is not that it works with sentences only. Let’s take an example and see
print("Python was first launched in the early 1990's, still it is an awesome language")
Output:
Python was first launched in the early 1990's, still it is an awesome language
If you were to just print the numbers, then you can just simply type the number in print , it does not need to be in quotation marks.
print(26)
print(37.5)
Output:
26
37.5
Brain Teaser: Is print(26) and print(“26“) same ?
No they are not same, although it would display the same number in this case i.e. 26 but they both are not same. Because the output of print(26) is treated as a number whereas the output of print(“26”) is treated as text.
Let us prove this with the help of an example
print(26+4)
print("26" +"4")
Output:
30
264
See the difference?
With numbers: 26+4=30. This performs mathematical addition.
With text:”26”+”4”="264”. This is text joining or concatenation.
You can perform mathematical operations with the number in print function like addition, subtraction, multiplication, division, power.
print(26+4)
print(7-5)
print(6*4)
print(20/4)
print(5**2)
Output:
30
2
24
5
25
You can print multiple items in a single print statement.
print("Machine","Learning")
print("Number:",2)
Output:
Machine Learning
Number: 2
If you want to print new line then you can use the special character \n and for tab the special character is \t. These are called "escape characters" and they let you include special formatting that you can't normally type in a string.
print("Machine\nLearning")
print("IronWill \t is my buddy")
Output:
Machine
Learning
IronWill is my buddy
One more such important and useful escape character is for printing quotation marks in print().
print("He said,\"Hello\"")
Output:
He said,"Hello"
By default, when you use commas in print(), Python automatically adds a space between each item. But what if you want something different? Python gives you control over this with the sep parameter. The sep parameter lets you decide what goes between your items. By default is space, however you can have your own and even modify in such a way that there is no space as well.
print("Hello","!","Hope","you","are","doing","good")
print("Hello","!","Hope","you","are","doing","good",sep="-")
print("Hello","!","Hope","you","are","doing","good",sep="")
Output:
Hello ! Hope you are doing good
Hello-!-Hope-you-are-doing-good
Hello!Hopeyouaredoinggood
This is extremely useful for representing date format and error format.
If we just write print() without anything in the parenthesis , then it creates new line.
Brain Teaser: What happens when you use a comma (,) vs plus (+) in print( ) ?
For Comma(,): Python automatically adds space between items. This tells print( ) to handle multiple separate items. This is used when you want to print different types of data with automatic spacing.
For Plus(+): In this items stick together with no space. It joints or concatenates items into one single item before printing. It is used only when joining text together. Here it is important to note that both sides must be text.
Let us understand it with the help of an example
print("Hello","Python")
print("Age:",20)
print("Hello"+"Python")
print("Age:"+20)
Output:
Hello Python
Age: 20
HelloPython
Error ( Because for + both the sides should have same data type)
Variables: Giving Your Program Memory
Variables are containers that store data values in your program. Think of them as labelled boxes where you can put the information that your program needs to remember and can be used later.
Let’s try to understand variable with the help of a real world example. We all write a phone number in telephone diary with different names according to our convenience. When we want to dial numbers then instead of recalling the whole number ,we simply recall the name with which we have entered in the telephone diary. This makes the process easy as remembering many phone numbers is a next to impossible task. Similarly variables let you store information in your program and give it a meaningful name so you can find and use it whenever needed.
Imagine trying to write a program that calculates the area of different rectangles, but every time you need to use a length or width value, you have to type the actual number. Variables solve this problem by letting you store values once and reuse them throughout your program.
When you write name = “IronWill“ in your code, you're creating a variable called name that stores the text 'IronWill'. Now whenever your program needs to use that name, it can simply refer to the variable instead of typing 'IronWill' every time.
Variable names are stored in namespaces (which can be on the stack for local variables). But all values, including integers and booleans, are objects stored on the heap. So basically every variable is essentially a reference/pointer to a heap object.
x=26
name="IronWill"
flag= True
In the above code x is a reference to an integer object (26) on the heap, name is a reference to a string object on the heap, flag is a reference to a boolean object on the heap.
Variable Naming Rules
When creating variables in programming, you must follow specific rules to ensure your code works correctly. Here are the essential rules with examples:
Rule 1: Variable names must start with a letter (a-z, A-Z) or underscore (_)
Valid: name, Age, _score, firstName
Invalid: 2name, 9age, $price (starts with number or special character)
# Correct student_name = "Virat" private_var = 100 myAge = 25 # Incorrect - will cause syntax errors 2students = 30 # Error: starts with number
Rule 2: After the first character, you can use letters, numbers, and underscores
Valid: name1, student_age, score2023, my_var_1
Invalid: my-name, student age, price$, user@name (contains spaces or special characters)
# Correct player1_score = 150 total_amount_2024 = 5000 user_id_123 = "USER001" # Incorrect player-1 = 150 # Error: contains hyphen total amount = 5000 # Error: contains space price$ = 29.99 # Error: contains special character
Rule 3: Variable names should be limited to 32 characters
Most programming languages have a limit on variable name length, typically 32 characters.
this_is_a_very_long_variable_name_that_exceeds_limit = 100 #this will be problematic as it is 52 characters
student_total_score = 100 #19 characters - good
max_temperature_celsius = 35 #23 characters - perfect
is_assignment_completed = True #23 characters - perfect
Rule 4: Variable names are case-sensitive
This means Name, name and NAME are three different variables.
name = "Rohit" Name = "Virat" NAME = "Rahul" print(name) # Output: Rohit print(Name) # Output: Virat print(NAME) # Output: Rahul
Rule 5: Cannot use reserved words (keywords)
Reserved words are special words that have specific meanings in the programming language.
Common reserved words: if, else, for, while, def, return, class, import, true, false.
# Incorrect - these will cause errors if = 10 # Error: 'if' is reserved class = "Math" # Error: 'class' is reserved def = "function" # Error: 'def' is reserved # Correct alternatives condition = 10 subject_class = "Maths" function_def = "function"
Rule 6: Use descriptive names
Choose names that clearly describe what the variable stores.
# Poor naming
a = 18
x = "Virat Kohli"
n = 95.5
# Good naming
student_age = 18
full_name = "Virat Kohli"
average_score = 95.5
Basic assignment syntax
In programming, we use the assignment operator(=) to assign a value to the variable. If you are feeling overwhelmed don’t worry in tomorrow’s blog we will covering all the operators in depth. For now you can just remember that this is different from the traditional equals to sign from mathematics
The assignment operator works from right to left and not left to right like reading.
name = "IronWill"
What actually happens is:
First, the computer looks at the right side: “IronWill”
Then it stores that value in the variable name on the left side: name
Now name contains “IronWIll”
Basically, you can think of it as take the value on the right and put it into the variable on the left.
Creating and Using Variables
Lets now create some variables now and use them. You can print the values of these variables.
name="IronWill"
age=22
language="Python"
print(name)
print(age)
print(language)
Output:
IronWill
22
Python
You can even manipulate the variables which means you can perform operations on them, change their values, and use them in calculations. Manipulating variables means, using them in mathematical operations, combining them with other variables, modifying their values based on calculations, using them to create new variables. Lets understand all this with the help of an example
Basic Arithmetic:
price=100
discount=20
#Manipulate them in calculation
final_price=price-discount
print("Final price is:", final_price)
#Use variables in expressions
tax = final_price * 0.08
total_cost = final_price + tax
print("Total cost is:",total_cost)
Output:
Final price is 80
Total cost is 86.4
Modifying variable values
score=80
score=score+10
print("After modifying value of the variable is:",score)
Output:
After modifying value of the variable is 90
Multiple variables in one calculation
homework_score = 85
test_score = 92
project_score = 88
final_grade= (homework_score * 0.3) + (test_score * 0.5) + (project_score * 0.2)
print("Final grade is:",final_grade)
Output:
Final grade is 88.1
Variables depending on other variables
hours_worked = 40
hourly_rate = 15
gross_pay = hours_worked * hourly_rate
tax_rate = 0.2
tax_amount = gross_pay * tax_rate
net_pay = gross_pay - tax_amount
print("Gross Pay is:",gross_pay)
print("Tax amount is:",tax_amount)
print("Net Pay is:",net_pay)
Output:
Gross Pay is: 600
Tax amount is: 120
pNet Pay is: 480
Reassigning Variables
Reassignment means giving a variable a new value after the value has already been created. Unlike in mathematics where x=6 is a permanent statement, in programming variables are flexible containers that can hold different values at different times.
Variables are mutable. Think of variables as a box with label. You can empty the box anytime and store completely different thing inside, but the label remains the same. Variables store only one value at a time. When you assign a new value, it replaces whatever was there before. When you reassign a variable, the previous value is completely erased from memory. The variable does not remember its old values , it only knows the current value.
Step by step process:
Variables get created with initial value
New value is assigned to the same variable
Old value is discarded and replaced
Variable now contains only the new value
temperature = 30
print("Old temperature is:",temperature)
temperature = 40
print("New temperature is:",temperature)
Output:
Old temperature is: 30
New temperature is: 40
What happens in memory?
Step 1: Temperature box contains 30
Step 2: 30 is thrown away, 40 is put in the temperature box
Step 3: temperature now only knows about 30
In real programs, variables often changes as the program runs. For example,
account_balance = 1000
print("Initial account balance is:",account_balance)
#After deposit
account_balance = 1250
print("After deposit account balance is:",account_balance)
#After withdrawal
account_balance = 950
print("After withdrawal account balance is:",account_balance)
Output:
Initial account balance is: 1000
After deposit account balance is: 1250
After withdrawal account balance is: 950
If there are objects in the heap memory that don’t have any valid variable pointing to it, then they are handled by garbage collection. Garbage collection removes or flushes out objects that don't have any variables or references pointing to them. Python uses reference counting as its primary garbage collection mechanism. When an object has zero references pointing to it, it becomes unreachable from your program, there is no way for your code to access that object anymore. At that point, the garbage collector identifies it as unused memory and deallocates it, freeing up that memory space for other uses.
Data Types - How Python Thinks About Information
Just like in real life, information comes in different forms - numbers, text, true or false, list of items. In programming, we call this different forms data types. Each type of data behaves differently and has different capabilities.
Data types define what kind of information a variable can store and what operations you can perform on that information. Understanding data types is crucial as different types of data behave differently. Unlike some other languages, In Python you do not need to explicitly declare the data types. Python automatically determines the type based on the value you assign. This is called dynamic typing. However data types, still matter because they determines how your data behaves and what operations you can perform.
The data types can be classified into two sections:
Basic Data Types
Collection Types
Collection Types handle multiple items and we will covering up it in a separate model, for now let us closely look into basic data types
Basic Data Types
When you write programs you would have to deal with different kinds of information: student’s marks (numbers), names(text), whether someone passed a test (true or false), and shopping list(collection of items). There are 4 basic data types in Python , they are : int (integers), float (decimal numbers), str (string), bool(boolean).
int
int data type is used to represent integers. It is used to represent whole numbers (positive , negative, zero). It does not include decimal point numbers. In Python, you can check the type of data using type() function.Example of integers:
age = 25 temperature = -45 score = 50 year = 2025 print(type(age)) print(type(temperature)) print(type(score)) print(type(year))
The output of the above snippet which is for knowing type of variables in this case will be <class ‘int’>
You can perform basic mathematical operations like addition, subtraction, multiplication, division and exponentiation (power). The biggest advantage of int data type in Python is that unlike other languages( C++ , Java) there is no size limits for storing a value in int variable. It automatically handles big numbers. It is commonly used in counting items, ages, years, quantities, scores, ratings, indexing and positioning.
It is interesting to know that result of arithmetic operations of two integers may or may not give integer. Let me prove this with the help of an example,
```python num1 = 15 num2 = 30 num3 = num1 + num2
num4 = 20 num5 = 6 num6 = num4 / num5
Here num3 will be integer whereas num6 will be decimal number.
* **float**
float data type is used to represent decimal point numbers. We saw above that dividing two numbers sometimes gave us decimal numbers. Those results are called floats, it is Python’s way of handling numbers with decimal points. Example of floats :
```python
height = 1.76
weight = 68.5
pi = 3.14159
cgpa = 8.64
print(type(height))
print(type(weight))
print(type(pi))
print(type(cgpa))
The output of the above snippet which is for knowing type of variables in this case will be <class ‘float’>.
You can perform basic mathematical operations like addition, subtraction, multiplication, division and exponentiation (power). It is interesting to know that result of arithmetic operations of two floats is always float. Let me prove this with the help of an example,
num1 = 3.76
num2 = 5.24
num3 = num1 + num2
print(num3)
print(type(num3))
Output:
9.0
<class 'float'>
It is interesting to know that division of two integers always gives the answer as float, even when the answer is whole number ( integer ). Don’t believe me? Let us see the following code snippet:
num1 = 10
num2 = 5
num3 = num1 / num2
print(num3)
print(type(num3))
Output:
2.0
<class 'float'>
Brain Teaser: Are 5 and 5.0 same ?
Think about this for a moment before reading answer.
No they are not same. Yes in terms of value they are same, but both the values are of different data types. 5 represents int and 5.0 represents float. They are not even same objects, they have different representation in memory.
str
So far we have worked with numbers both integers and floats. But what about text? For that Python uses the str (string) data type to store and manipulate any text-based information. It can be names, messages, addresses or any other text information.
Just in case if you have already learned c++ or java or any other language and wondering that why char (character) is not covered, because of the fact that Python interprets the single character as string only.
String should be enclosed in double quotation or single quotation. Example of string,
name = "IronWill" language = "Python" platform = "Hashnode" number = "2" print(type(name)) print(type(language)) print(type(platform)) print(type(number))
The output of the above snippet which is for knowing type of variables in this case will be <class ‘str’>. You can perform basic operations like concatenation, repetition, length, membership , slicing and indexing. Don’t worry we will be covering them in detail in our string’s blog along with some advanced operations. For now you can just remember that anything which is enclosed within single or double quotation is string. And by anything , I mean anything. It can even include text from any other language or even numbers. Let’s see that with example:
str1 = "2" str2 = "鉄の意志" print(type(str1)) print(type(str2))
Output:
<class 'str'> <class 'str'>
bool
In everyday life we often deal with yes/no questions or true/false statements. Is it raining? Yes or No. Are you hungry? True or False. Python has a special data type to handle exactly these kinds of situations, the boolean (bool) data type. Only two types of value is possible in bool data type , either True or False. Common mistake , don’t just write T or F. In this no quotations are needed unlike strings.
Let’s see some examples of bool:
is_python_fun = True is_python_hard = False print(type(is_python_fun)) print(type(is_python_hard))
The output of the above snippet which is for knowing type of variables in this case will be <class ‘bool’>. Booleans become very important when you deal with conditions and decision making.
complex
There is this another data type which is used to represent complex numbers. However complex numbers are less used in programming as a result of which this data type is not widely used. It has basically two parts: real and imaginary. Example of complex:
num1 = 2+3j
print(type(num1))
The output of the above code snippet will be <class ‘complex’>. Here 2 is real part and 3j is imaginary part.
Getting User Input - Making Programs Interactive
So far, all of our programs have been pretty predictable. They always do the same thing , every time we run them. But what if you want to create programs that can respond to different users or situations. What if we want our program to ask for your name and greet you personally? Wouldn't it be cooler if the program could ask for your name and the you enter it.
For getting the input from user we have input() function. Input function is kind of similar to print() function as what we write in input() function in double quotations is printed on the screen. The text inside inside the parenthesis is called prompt. However the difference between print() and input() is , input() halts the program after encountering it and displaying prompt on the screen. It would continue only after we enter the value for the prompt and press Enter. This way it takes the input dynamically or at run time from the user. input() function always returns string (str). Since input() returns a string , it would be better if we store it in a variable for future use. Let’s see this with the help of an example in following image,
You can even leave the prompt empty, but it is not a good practice because your program will pause and wait for input without giving any indication to the user about what kind of input is expected.
Let us look at the following code snippet,
name = input("Please enter your name: ")
age = input("Please enter your age: ")
after_5_years = age + 5
print("After 5 years your age will be",after_5_years)
Now why did this give error? I entered 22 (number) , then it should give me 27 as answer, right? No,not really because I just missed one trick. I wanted age variable to store a number or to be precise int and input() function returns string. So it interpreted 20 as string and concatenation of string and it is not possible, so it raised an error. Then , what to do in situations when we want to input different data types other than string? In such cases we need to type cast this input string into the desired. For type casting input you just need to wrap the whole input() with your required data type and parenthesis. Basically like data_type(input()). Let us look it with the help of an example,
cost_price = int(input("Please enter the cost_price"))
selling_price = cost_price + (cost_price * 0.20)
print("Selling price is:",selling_price)
Output:
Similarly you can try it with float and bool data type. No need to write str for string as by default it is string for input() function. An interesting thing you will observe when you take the bool input is that even if you enter any character or string , then also it will interpret it as true. If you do not enter value at the run time and then simply just press enter then only consider it as false. Even just a space is considered as true. Don’t believe me? Try it yourself.
Comments - Writing Code Humans Can Read
Comments are important part of the program and make the code more readable. Comments can be any statements in the program that help user or programmer understand the program by providing extra information. They are not interpreted by the Python interpreter and hence they are not converted to target language. Let’s see how to represent comments,
Without Comments:
a = float(input())
b = float(input())
c = a * b * 0.5
print(c)
With Comments:
# Calculate area of a triangle using base and height
# Formula: Area = (base × height) / 2
base = float(input("Enter base of triangle: "))
height = float(input("Enter height of triangle: "))
area = base * height * 0.5
print("Area of triangle:", area)
As you can see the second code snippet is easy to understand for a program as it explains the purpose of the code and also mentions the formula. You can add as many comments as you want in your program but don’t over-comment, like don’t go on explaining the obvious things in the comment which is basically repeating the whole code. You can definitely explain why you are doing it this way, or to represent complex formulas or business logic. You should explain tricky or non obvious parts. There can be two types of comments : single line comments, multi line comments
Single Line Comments
This is used to write a single line comment. A single line comment starts with # symbol , this indicates that from that point till the end of that line, everything is treated as comment. Alternatively if you want to comment a line, then you can just select that whole line or part of the line and then simply press Ctrl + / (Cmd+/ on Mac).
Multi Line Comments
Python doesn't have a built-in multi-line comment syntax like some other languages. Triple quotes (""" or ''') create multiline strings, not comments because they are stored in memory as string objects. For true multi-line comments, you need to use # at the beginning of each line. Alternatively, if you want to comment out multiple lines, you can select those lines and then press Ctrl + / (Cmd + / on Mac). The Ctrl + / shortcut will automatically add # to each line.
Let us understand single line comments and multi line comments with the help of an example,
#This is a single line comment
#This is used to
# represent a
# multi
# line comment
Comments are extremely useful as you will forget why you wrote the code in a certain way after weeks , so comments help you understand your own logic later. Also the other team members can understand your code faster and makes the collaboration much more easier.
Practice Project - Your First Interactive Program
Let us create a Personal Information Calculator that takes user input and performs various calculations based on that information. This project will help you practice everything you've learned about variables, data types, user input, and basic arithmetic operations.
Problem Statement:
Create a program that asks the user for ,their name, current age, height in centimeters.weight in kilograms, favorite number. Your program should calculate and display Age Predictions: How old they'll be in 5, 10, and 20 years, Height Conversion( height in meters and feet), BMI Calculation(Body Mass Index) Favorite Number Magic(Double their favorite number and add their age). Display all results in a nice, formatted way with the person's name.
# Personal Information Calculator
# This program collects user data and performs various calculations
print("=== Welcome to Your Personal Information Calculator ===")
print()
#Let us take user input
name = input("Please enter your name: ")
age = int(input("Please enter your age: "))
height = float(input("Please enter your height in centimeters: "))
weight = float(input("Please enter your weight in kilograms: "))
fav_num = int(input("Please enter your favourite number: "))
#Age predictions
print("-> AGE PREDICTIONS: ")
print("After 5 years you will be",(age+5),"years old")
print("After 10 years you will be",(age+10),"years old")
print("After 20 years you will be",(age+20),"years old")
#Height Conversion
print("-> HEIGHT CONVERSIONS: ")
print("Your height:",height,"cm")
print("In meters:",(height/100),"m")
#For converting cm to feet formula is Value(in feet) = 0.0328 * Value (in cm)
print("In feet:",(0.0328 * height),"feet")
#BMI Calculation
print("-> HEALTH INFO:")
height_in_metre = height/100
BMI = weight / (height_in_metre * height_in_metre)
print("Your BMI:",BMI)
#Favourite Number Magic
print("-> NUMBER MAGIC:")
print("Your favourite number doubled:",fav_num*2)
print("Plus your age:",fav_num*2 + age)
print("=== Thank you for using our calculator! ===")
Conclusion
Today we covered Python fundamentals: print() function for output, variables for storing data, data types (int, float, string, bool), input() function for user interaction, and comments using # for documentation. We learned that input() always returns strings and triple quotes create strings, not comments.
These building blocks transform static programs into interactive applications. Specific mistakes beginners make are Forgetting double quotations in print() and input(), missing parentheses in input() for type casting, adding strings to numbers, poor variable naming , over-commenting obvious code. Practice is essential to master type casting and avoid common string/number confusion bugs. The more you code, the more these concepts become second nature. Regular practice helps you catch these mistakes quickly and write cleaner code.
Tomorrow we'll learn about various operators in Python. We will also learn about operator precedence and associativity.
If you found this blog useful, do like, comment and share it with others. Till then Keep coding, keep practicing, and keep building amazing things! Every expert was once a beginner🚀
Subscribe to my newsletter
Read articles from Raj Patel directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Raj Patel
Raj Patel
Hey there! I'm Raj Patel, a passionate learner and tech enthusiast currently diving deep into Data Science, AI, and Web Development. I enjoy turning complex problems into simple, intuitive solutions—whether it's building real-world ML projects like crop disease detection for farmers or creating efficient web platforms for everyday use. I’m currently sharpening my skills in Python, Machine Learning , Javascript and love sharing what I learn through blogs and open-source contributions. If you're into AI, clean code, or building impactful tech—let’s connect!