Python Variables
Dec 22, 2023 by Ankit Srivastava
Categories
Enroll Now to Access Multiple Intensive Courses for Free
Introduction
- Variable is something that could vary.
- Use a variable to write something that could change.
- Python has no command for declaring a variable. It is created the moment you first assign a value to it. Example , a = 10 with this automatically a variable “a” got created and10 integer value got assigned to it.
- As a programmer , we will write variables everyday and it is very simple to write a variable. We will need just 3 things :
- A name
- An equal sign
- A value
- Literals are the constant values whereas variable is something that could vary.
- A variable is like a bucket , where every bucket has a name or label and a value inside it.
- We can set different values multiple times to a variable. Only the last value will stay. Let us work on a code.
Rules for naming variables :-
User Input
- To ask any information in python programming language , just type input().
- While asking for user input , we can add extra information to tell the user what information they should provide.
- Example , name = input(“Enter your name: “)
Input in variable
- We can also store user input in a variable and then use that variable.
- Let us work on a code for better understanding.
Data Type of input()
- By default , user input is taken as a string.
- We can convert the string into a number if there is a need by using a special keyword int or float.
a = int (input(‘What is your age’))
b = float(input(‘Value of pi : ‘))
- int(integer) represents whole numbers (positive or negative) without any fractional part. Examples: -5, 0, 10, 100.
- float (floating-point number) represents real numbers with a fractional part. Examples: -3.14, 0.0, 2.5, 100.67.
- print(“Here is the sum”, a + b) attempts to concatenate the two variables (a and b) and print their sum. However, since b is a string, the operation of adding a string to an integer is not supported in Python, causing a TypeError.
- To fix this, we can convert b to an integer before performing the addition. Here’s an updated version of the code:
- Share:
No comments yet! You be the first to comment.