Variables, Functions, User input & QUIZ
Variables
Variables can also known as the container, because it contains some characters which will be used in the program, In python programing the variables can can contains integer, character, float etc data types without declaring as int, float, char etc.
code👇
var1 = "Hello world"
var2 = 12
var3 = 32.4
print(var1)
Here the [ var1 ] is a variable and it is print without using double quotes [ "" ], whereas when we print a variable we don't need to use double quote, it mays print the variable as the print statement.
Here var1 is in the double quote because it is an string, whereas var2 is an integer and var3 is a float, Hence we put characters into the double quote/ string because in python it will take character as integer, otherwise it will throw the the error of concatenate value of the variable.
In case we know the type of a variable use [ type ] function.
code👇
var1 = "Hello world"
var2 = 12
var3 = 32.4
print(type(var1))
Output👇
<class 'str'>
But whereas we can add two integer type variable by using the operator signs [+, -, *, /, ^....etc]
code👇
var1 = "Hello world"
var2 = 12
var3 = 32.4
print(var2 + var3)
If we give a variable as [ var4 = "32" ] here 32 is not an integer it turned into string type because it written into the double quote (""). And it can't add with any integer because its a string type data type.
If in case we want to convert our variable into the sting, just use the [ int() ] function
code👇
var1 = "Hello world"
var2 = 12
var3 = 32.4
var4 = "15"
print(int(var4) + var3)
Functions
Here are some functions to switch one data type of a variable to the another:
str()
int()
float()
If we want to print any statement or a variable in given number of times:
code👇
print(10 * "hello world")
printing 10 time an integer by typecasting the result addition of two integer variables
code👇
var2 = 12
var3 = 32.4
var4 = "15"
print(10 * str(int(var2) + int(var3)))
User input
We also can take the input by the user of the program by using [ input() ] function
code👇
print("Enter your number");
var1 = input()
Whereas the input() function in always takes the input by user as a string (no matter if user input some numbers) by default, hence we used to input() function into the typecast function like👇
int() & float().
code👇
print("Enter your number")
var1 = int(input())
print("Enter your number")
var2 = float(input())
Quiz
Here is a quiz for you, you have to make a calculator which aad the two numbers by taking the user input:
first number
second number
and then print the result.
Comments
Post a Comment