Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Convert this C Program to Python #include <stdio.h> #include <stdlib.h> #include

ID: 3604333 • Letter: C

Question

Convert this C Program to Python

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define StrSize 100

main() {
char Prompt[] = "Please enter a command:";
char Command[StrSize];
char Dummy[StrSize];

float Num1,
Num2;

for (;;)
{
printf(" %s ", Prompt);
gets(Command);

if (! (strstr(Command, "ADD") || strstr(Command, "SUB")))
printf("Illegal Command ");

else
{
sscanf(Command, "%s %f %f", Dummy, &Num1, &Num2);
if (strstr(Command, "ADD"))
printf(" ==> %-4.2f ", Num1 + Num2);
else
printf(" ==> %-4.2f ", Num1 - Num2);
}
} /* infinite for loop */

}

Explanation / Answer

# Define function main
def main():
# Define a string to ask user
prompt = "Please enter a command:"
# infinite while loop
while True:
# Ask user using print statement
print ' ', prompt, ' '
# take input from user
command = raw_input()
# check if the command contains either ADD or SUB
# if does not, print Illegal Command
if not('ADD' in command or 'SUB' in command):
print 'Illegal Command '
else:
# if it is proper, then split the command
# and read the arguments and convert them floats
command_contents = command.split()
num1 = float(command_contents[1])
num2 = float(command_contents[2])
# for ADD command, add and print formatted result
# same holds for SUB commmand
if ('ADD' in command) :
print(' ==> %-4.2f ')%(num1 + num2)
else:
print ' ==> %-4.2f '%(num1 - num2)
  
main()