This section provides a quick overview of:
The input command can be used to obtain inputs from user. Python treats the default inputs as strings.
a = input("Enter first input: ")
b = input("Enter second input:")
print(a+b)
Python treats the default inputs as strings. For example, if you provide string input, the output merges the two strings.
a = input("Enter first input: ")
b = input("Enter second input:")
print(a+b)
If you want to make sure that the inputs are integers.
a = int(input("Enter first input: "))
b = int(input("Enter second input:"))
print(a+b)
If the input is a list.
a = [int(x) for x in input().split()]
print(a)
If the input is a list separated by commas.
a = [int(x) for x in input().split(",")]
print(a)
In many cases, you may have to read the input to your code from a file and write the output to a file. This section provides a quick overview of reading and writing to text files. Create a text file called "input.txt" with the following information and place it in the same directory as the python script or notebook:
From, To, Cost
1, 2, 3.0
1, 3, 4.0
2, 3, 3.0
3, 4, 5.0
2, 4, 4.0
f = open("input.txt", "r")
print(f.read())
f.close()
The open command opens a file and returns a file object. In the example given above, the file object is stored in f. The first argument in the open command specifies the name of the file. The second argument specifies the mode. The common modes are:
Note that whenever you open a file for writing, it creates a completely new file. So if there was a file with information you dont want to be deleted, you want to open the file in append mode.
The f.read() reads the entire file and returns a string containing all the elements of the file. Once you open a file, do not forget to close the file using the close command.
You can also read the file, line by line using the readline() function.
f = open("input.txt", "r")
network = []
line = f.readline() #This line reads the first line comprising of From,To, Cost
line = f.readline()
while len(line):
l = line.split(',')
fromnode = int(l[0])
to = int(l[1])
cost = float(l[2])
line = f.readline()
network.append([fromnode, to, cost])
f.close()
print(network)
The code below demonstrates another way to read the file using for loop.
g = open("input.txt", "r")
g.readline() #This line reads the first line comprising of From,To, Cost
for line in g:
temp = line.split(',')
a = float(temp[0])
b = float(temp[1])
c = float(temp[2])
print(a + b + c)
g.close()
In the above code, we read line by line. Each line is split into components and stored in a list l. The elements of the list are then converted to integer and float values and stored in a multi-dimenstional list called network. Similarly we can use the open and write command to write stuff onto files.
f = open("output.txt", "w")
f.write("Testing output.\n")
f.write("My attempt at writing to file in Python.")
f.close()