Simple Arithmetic, Input and Output in Python
int() and input() Functions
The int()
function converts the sequence of number characters into a number, known as (integer) type casting.
y = int(input("Enter a number please: ") )
x = 2 * y
print(x)
The terminal prompt will be expecting a user input, type any number you wish. e.g. 23
Output will be 2*23 = 46
. In this case the interpreter uses the same *
operator to multiply numbers, as the variable y
contains a numeric value, and the result stored in the x
variable is also a numeric value.
The int()
function is independent of the input()
function:
text_variable = "25"
z = int(text_variable)
print(2 * z);
and it can convert a text consisting of a legitimate number representation to an integer value, as in values passed to remote web services, etc.
y = int(input("Enter a number please: ") )
x = 2 * y
print(x)
text_variable = "25"
z = int(text_variable)
print(2 * z)
Some more examples:
age = input("Enter your age please: ")
print(age)
This will output your age as a string literal "17"
print(age * 2)
This will output your age as a string literal "1717"
age = int (input("Enter a number please: ") )
print(age)
This will output your age as the number 17, as a number without the quotation marks
print(age * 2)
This will output your age as the number 34
The prompt message of the input()
function is a string literal that we can generate by concatenating other strings and variables.
name = input("Enter your name please: ")
print("Hello",name)
age = int ( input("Hi " + name + " Please enter your age : "))
print(age)
The basic type casting methods can be listed as: