Sunday, June 7, 2020

Python Input

Up until now, our programs were static. The value of variables was defined or hard coded into the source code.
To allow flexibility, we might want to take the input from the user. In Python, we have the input() function to allow this. The syntax for input() is:
input([prompt])
where prompt is the string we wish to display on the screen. It is optional.
>>> num = input('Enter a number: ')
Enter a number: 10
>>> num
'10'
Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can use int() or float() functions.
>>> int('10')
10
>>> float('10')
10.0
This same operation can be performed using the eval() function. But eval takes it further. It can evaluate even expressions, provided the input is a string
>>> int('2+3')
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5

No comments:

Post a Comment