How do I take manual inputs in python for a for loop?

Viewed 133

I'm trying to take manual inputs and use those inputs inside a for loop to spit out results within a CSV file and I can't get it to work.

I tried to make an input variable outside the for loop which takes in an int value which doesn't seem to get passed into the for loop. I'm also trying to manually enter the amount of memory, and the OS name. The goal is to spit out the server name.

CSV file:

Name,CPU,Memory,OS
server1,2,4gb,windows 7
server2,4,2gb,arch linux
server3,8,4gb,ubuntu linux
server4,4,2gb,windows server
server5,2,4gb,windows 7

Python code:

import csv


entercpu = int (input("Enter number of CPU: "))
#enteros = input("Enter the OS: ")
#entermemory = input("Enter the amount of memory: ")


with open('test.csv', 'rb') as csv_file:
    dict_reader = csv.DictReader(csv_file)

    for d in dict_reader:

        if d['NumCpu'] == 'entercpu' and d['Guest OS'] == 'windows 7' and d['MemoryGB'] == '8':
            print('Name: {Name}, CPU: {NumCpu}, Memory: {MemoryGB}, OS: {Guest OS}'.format(**d))

The output should be: Name: Name: Server 1, CPU: 4, Memory: 8, OS: windows 7 and
Name: Server 5, CPU: 4, Memory: 8, OS: windows 7

1 Answers

Try using this:

if d['NumCpu'] == str(entercpu) and d['Guest OS'] == 'windows 7' and d['MemoryGB'] == '8':
            print('Name: {Name}, CPU: {NumCpu}, Memory: {MemoryGB}, OS: {Guest OS}'.format(**d))

You need to make sure that your types are the same when you compare them. For example 4 == "4" returns False but str(4) == "4" gives True

I think when you typed 'entercpu' that's what you meant to do, but when trying to cast from one type or another you call the constructor (i.e. str(4) or int("4")).

Hope this helps!

Ash

Related