Inputs in Python
Inputs in Python
Now, you know how to print something on a screen. So, let's learn how to take
input from the user.
Output
Output
'input()' is used to take input from the user. We can also write something
inside input() to make it appear before the input, as done in the previous
example, input("age >>>").
Output
Output
In the above example, we are taking the input from the user as a string with
the input() and then we are using the int() to change it to an integer. So,
if a user will enter 10, then the input() will become '10' (a string) and the
above statement int(input()) will become int('10') and we will get 10 as an
integer.
We can also break the above example in one more step to understand better.
Output
Here, we passed 12. Thus, x became '12' and then int(x) turned it into an
integer.
x = input(">>>")
print(x)
Output
>>>10
10
This code is similar to x = '10'.
We gave 10 to the input(). You can think that input() becomes 10. So, x =
input() will be similar to x = 10 after the input is given.
Similar to taking input of integers, we can use float() to take an input from
the user and change it to a float.
x = float(input())
print(x)
print(type(x))
Output
12.32
12.32
<class 'float'>
print(int(7.4))
Output
This is very useful in some situations, where you want to convert a variable
in the middle of your program.
So, in the initial examples of this chapter, we used int() to convert strings
(the inputs we were taking were strings) into integers and then converted
floats into integers. Let's proceed ahead and learn some mathematical
functions available in Python.
Let your computer do some maths for you.
import math
print(math.sin(30))
print(math.cos(10))
print(math.pow(2,3))
Output
-0.9880316240928618
-0.8390715290764524
8.0
import math → This will include Python's inbuilt directory 'math'. It contains
many mathematical functions for our use. import is a keyword used to import
any available directory.
math.sin() computes sine of a given angle.
math.cos() computes cosine of a given angle.
math.pow(a,b) computes a raised to the power of b (ab).
We have imported 'math' and these functions are inside it, so 'math.sin()'
can be understood as 'sin()' from 'math' directory.