Python Forum
While loop in Python and C++
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
While loop in Python and C++
#3
Sorry. It's been too long since I've done C++, and your code didn't immediately compile. So I can't tell you why the C++ would accept a character. (I think it shouldn't since x is declared int).

But in the C++ code, cin is returning a value representing success, not the value of the input (that goes to x). So entering a "false" value still enters the loop.

In python, the input returns the value that was entered. This is passed to int() that tries to convert it. So if you enter a zero, it becomes the number zero, and that is false. There is no question of the input failing. It will block, succeed, or throw an exception.

In C++ a character can't be sent to the declared int variable, so the >> operator fails and returns false to the test.

In Python, int() doesn't fail. It either succeeds or throws an exception. You can catch the ValueError exception in a try/except block if you want to continue even when a non-integer is passed in.
Reply


Messages In This Thread
While loop in Python and C++ - by smjt2000 - Jun-18-2020, 07:41 PM
RE: While loop in Python and C++ - by Larz60+ - Jun-18-2020, 08:46 PM
RE: While loop in Python and C++ - by bowlofred - Jun-18-2020, 09:08 PM
RE: While loop in Python and C++ - by deanhystad - Jun-18-2020, 09:14 PM
RE: While loop in Python and C++ - by smjt2000 - Jun-18-2020, 09:16 PM
RE: While loop in Python and C++ - by jefsummers - Jun-19-2020, 01:43 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020