View on GitHub

python-for-kids

Learning and exercise content on Python for Kids

Day 16 - Working with Inputs

So far we have seen how to create files which we can run as a script. This is one way of using Python. However you might want to change certain variable values in that file everytime you run it.

Take an example of your basic calculator. If you write something like below then even if it is using two variables like a and b then also you would using what is there in the file, in our case 10 and 20. What if next time you would like to change them to 22 and 33? You need to change the file and rerun.

# Basic calculator with variables but fixed values

a=10 #variable but fixed values
b=20 #variable but fixed values

result = a + b

print(result)

In the above case we can make it prompted. This means everytime when you call the file you are asked to pass the values. Then calculator will calculate it.

Let’s first see how basic input() works in python.

num1 = input("Enter the first number:")

Now this value is stored in num1 variable but will be asked everytime someone runs this file as py myfile.py. Remeber a Python code needs to be put in a file with extension .py.

num1 = input("Enter the first number:")

print(num1)

Now our modified Calculator.py would look like,

num1 = input("Enter the first number:")
num2 = input("Enter the second number:")

result = num1+num2
print(result)

Next: Day 17 - Modules

Back to Index