in reply to Help with While Loop

Curly braces are needed around blocks. In the pythonesque code you posted, a left brace is missing whenever the indentation increases, and the right brace is missing whenever it decreases.

Unfortunately, putting the curly braces in doesn't make the code work. The user's input must be repeated in the loop, too, otherwise the code would test the same number again and again.

#! /usr/bin/perl use warnings; use strict; my $im_thinking = int rand 10; print "Pick a number: "; my $guess = -1; while ($guess != $im_thinking) { $guess = <STDIN>; chomp $guess; if ($guess > $im_thinking) { print "You guessed too high!\n"; } elsif ($guess < $im_thinking) { print "You guessed too low!\n"; } } print "You got it right!\n";

Update: You can use last and the ternary operator to make the code even simpler:

#! /usr/bin/perl use warnings; use strict; my $im_thinking = int rand 10; print "Pick a number: "; while () { my $guess = <STDIN>; chomp $guess; last if $guess == $im_thinking; print "You guessed too ", $guess < $im_thinking ? 'low' : 'high', "\nTry again: "; } print "You got it right!\n";
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: OT: Pythonesque C
by AnomalousMonk (Archbishop) on Sep 14, 2015 at 19:15 UTC
    In the pythonesque code you posted...

    Not only Pythonesque, but perhaps also a bit C-ockamamie. The following works, although you have to torture the code to get the syntax right (and the indentation is meaningless). And it still doesn't do anything.

    #include <stdio.h> void main () { int x = 5; int y = 6; while (x != y) if (x > y) printf("guessed %d: high. ", x), printf("next guess %d \n +", x = y); else if (x < y) printf("guessed %d: low. ", x), printf("next guess %d \n" +, x = y+1); else printf("got it! \n"); printf("done guessing \n"); }
    Output:
    c:\@Work\GCC\PerlMonks\gavin100>a guessed 5: low. next guess 7 guessed 7: high. next guess 6 done guessing

    Update: Changed node title. This really is OT.


    Give a man a fish:  <%-{-{-{-<

Re^2: Help with While Loop
by gavin100 (Initiate) on Sep 14, 2015 at 12:46 UTC

    Thats brilliant, thank you for your time and assistance