Conditional Statements

This topic contains 9 replies, has 2 voices, and was last updated by Profile photo of Brian Henderson Brian Henderson 1 year, 11 months ago.

  • Author
    Posts
  • #23996
    Profile photo of Brian Henderson
    Brian Henderson
    Participant

    Hi,

    I have homework for a powershell class I am taking. The assignment is to create a math quiz, to display the answers, and at the end provide a score. I am able to get the quiz and the answers, but stuck on getting the score (i.e. 100%, 20%, etc...)

    Can someone please take a look at the attache text file and let me know what I am doing wrong. I greatly appreciate the help.

    -Brian

  • #24002
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    You are not capturing the data you need. To determine percentage you would need the total number of questions and the total correct and then multiply that by 100

    (12/14)*100

    It's difficult to put you on the right path without an example, but I'll give you credit since you actually tried to write the script. Take a look at this and see if you understand the concepts. Please don't just copy and paste this, try to understand it and improve it:

    # Create a PSObject, basically a table of information with the question, answer and a column to indicate the answer was correct or not
    # Note that I'm letting Powershell do the math for the answer and the $() tells Powershell to resolve it before create the object
    $test = @()
    $test += New-Object -TypeName PSObject -Property @{Question="What is 1+2?";Answer=$(1+2);ResponseCorrect=$false}
    $test += New-Object -TypeName PSObject -Property @{Question="What is 4*3?";Answer=$(4*3);ResponseCorrect=$false}
    $test += New-Object -TypeName PSObject -Property @{Question="What is 15-7?";Answer=$(15-7);ResponseCorrect=$false}
    $test += New-Object -TypeName PSObject -Property @{Question="What is 25/5?";Answer=$(25/5);ResponseCorrect=$false}
    
    # Create another PSObject to capture the results of the test
    $testResults = @()
    # For every line in the object as $item
    foreach($item in $test) {
        # Get the question from the current line being processed as $item
        $answer = Read-Host -Prompt $item.Question
        # Check if the the Read-Host input matches the answer stored for the same line
        if ($answer -eq $item.Answer) {
            # Only if it is correct, update the $false default value to $true
            $item.ResponseCorrect = $true;
        }
        # Now that you have updated the line indicating the answer was $true or left it for $false, append that line to the $testResults object
        $testResults += $item
    }
    
    #Display the object to see the results
    $testResults
    #Calculate the number of correct answers by querying the object for all $true values in ResponseCorrect.
    #Then divide that number by the total number of questions
    $grade = [@[$testResults | Where{$_.ResponseCorrect -eq $true}].Count / @[$testResults].Count]
    #Use a string format to provide the percentage correct on the test
    "You received a {0:0.0%} on the test!!" -f $grade
    #String format uses an index to assign a value in the placeholder, below would produce "See Skip run with his dog".  The
    #{0:0.0%} is a format string to format as percentage, see https://msdn.microsoft.com/en-us/library/system.string.format[v=vs.110].aspx
    $var1 = "Skip"
    $var2 = "dog"
    "See {0} run with his {1}" -f $var1, $var2

    Again, please use this as an example and learning experience. We'd be happy to further explain anything you don't understand as I'm sure some of this will look like gibberish.

  • #24005
    Profile photo of Brian Henderson
    Brian Henderson
    Participant

    Rob

    Thank you so much for replying. However, you are correct, it looks like gibberish for the most part.

    I am very green to command line world. I have minor experience with basics of linux and that's it.

    Everyone I know doesn't know much about powershell so I wanted to learn.

    Pertaining to the script, I feel I am very close to getting what I want. I suppose instead of a percentage
    stating how I did on the exam, would a 3 out of 5 correct be easier to write?

    -Brian

  • #24006
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    There are a lot of ways to accomplish the same thing. In your posted script, you are basically copying and pasting the same thing and just change a couple of things. While it works, it inefficient and as you write longer scripts much more difficult to troubleshoot. I tried to add a lot of comments to the code to help walk you thru the process and logic, but I understand it's overwhelming, we all had to start learning somewhere though.

    The code tags slaughtered the $grade line, it should have parenthesis, not square brackets:

    $grade = (@($testResults | Where{$_.ResponseCorrect -eq $true}).Count / @($testResults).Count)

    and the return on the screen should be something like this:

    ————– ——– ——
    True What is 1+2? 3
    False What is 4*3? 12
    True What is 15-7? 8
    False What is 25/5? 5

    You received a 50.0% on the test!!
    See Skip run with his dog

    Now, if we break up the $grades line, we are determining the amount of correct answers and the total number of questions. If you wanted to do X out of X correct, you have all of the information there to do it and use the See skip run example to write it to the screen.

  • #24035
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    So, as I was driving to work today I was thinking that what I was showing you was probably way too advanced. Again, you need to calculate the total number of questions and the number of correct answers to determine a grade. If we use basic counters to count the questions and correct answers, we can accomplish what you want. $Correct is set to 0 to start and if in your if logic the answer is correct, we use $Correct++, which increments the value by 1.

    $Correct = 0
    $Questions = 0
    
    
    $myProblem = Read-Host -Prompt "Solve 5 + 3"
    $Questions++
    if[$myProblem -eq 8]
    {
        Write-Host "You are correct!"
        $Correct++
    }
    else
    {
        Write-Host "You are incorrect"
    }
    
    
    $myProblem = Read-Host -Prompt "Solve 12 - 2"
    $Questions++
    if[$myProblem -eq 10]
    {
        Write-Host "You are correct!"
        $Correct++
    }
    else
    {
        Write-Host "You are incorrect"
    }
    
     
    $myProblem = Read-Host -Prompt "Solve 5 * 3"
    $Questions++
    if[$myProblem -eq 15]
    {
        Write-Host "You are correct!"
        $Correct++
    }
    else
    {
        Write-Host "You are incorrect"
    }
    
    $myProblem = Read-Host "Solve 6 / 3"
    $Questions++
    if[$myProblem -eq 2]
    {
        Write-Host "You are correct!"
        $Correct++
    }
    else
    {
        Write-Host "You are incorrect"
    }
    
    
    $myProblem = Read-Host -Prompt "Solve 25 + 5"
    $Questions++
    if[$myProblem -eq 30]
    {
        Write-Host "You are correct!"
        $Correct++
    }
    else
    {
        Write-Host "You are incorrect"
    }
    
    "You have " + $Correct + " out of " + $Questions + " correct!!"
    
    "You received a " + $(($Correct / $Questions) * 100)+ "%"
    

    Above I showed you another method to build a string with variables, although I like the string format method more, this may be easier to understand and learn. Below is the output:

    Solve 5 + 3: 8
    You are correct!
    Solve 12 - 2: 11
    You are incorrect
    Solve 5 * 3: 18
    You are incorrect
    Solve 6 / 3: 1
    You are incorrect
    Solve 25 + 5: 23
    You are incorrect
    You have 1 out of 5 correct!!
    You received a 20%

    Edit: Code tags are still messing with parens. The % line should have parens, not square brackets: "You received a " + $(($Correct / $Questions) * 100) + "%"

  • #24043
    Profile photo of Brian Henderson
    Brian Henderson
    Participant

    You are awesome! and also correct. This is a lot easier to understand.

    Thank you very much Rob, I really appreciate the help.

    I will probably be posting more questions as I have a few weeks of the

    class to go.

  • #24048
    Profile photo of Brian Henderson
    Brian Henderson
    Participant

    The next part is to put the quiz into a loop if the person taking the quiz get anything but 5 out of 5.
    If the person gets less than 5 out of 5 they must retake the quiz and I am having trouble figuring out
    the script to replay the quiz. I have however found a few ways to get into the infinite loop.
    This is what I have come up with so far....

    "You have " + $Correct + " out of " + $Questions + " correct!!"

    "You received a " + $(($Correct / $Questions) * 100)

    $x = + $(($Correct / $Questions) * 100)
    do
    {
    Write-Host $x
    } while($x -eq + ($Correct / $Questions))

  • #24051
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    First, you would wrap the do around the entire quiz. You are using a Do While loop, so think through the logic. Do this while what?

    loop if the person taking the quiz get anything but 5 out of 5.

    You're overcomplicating it with the x= stuff. What variable represents correct answers? $Correct What variable represents questions? $Questions

    If we put some values to these:

    $Correct = 3
    $Questions = 5

    The "While" loop is basically logic of Do this While ([i]your logic[/i]) is True. So, how can we test if your logic is correct?

    $Correct = 3
    $Questions = 5
    
    $Correct -eq $Questions
    

    Return:

    False

    If we say "equals", it returns False, which is correct because 3 does not equal 5. Now we know that if you used that logic in While, it would stop the loop, which isn't what you want. How do you change the logic to NOT equal? Figure that out and you're golden.

  • #24052
    Profile photo of Brian Henderson
    Brian Henderson
    Participant

    I figured the loop out using do until. It's when it comes to jumping back in the loop cause I didn't get them all correct.
    I was thinking using an else statement would make sense but powershell doesn't like that logic.
    The reason I went crazy with the x is because I was trying to follow examples in the book.

  • #24054
    Profile photo of Brian Henderson
    Brian Henderson
    Participant

    I figured it out. I learned that I didn't have scope awareness.

You must be logged in to reply to this topic.