Getting string input from user in C# vs Python

Very often, we would like to prompt the user of our program for an input. Suppose we want to ask the name of the user and then print a simple message containing that name. This can be achieved by the following program.

C# code

Python code

The program asks the user for their name and then displays the welcome message containing that name. We start by declaring a string variable named prompt and initializing it with the string “Please enter your name:”. Strings must always be enclosed between double quotation marks in C#. Python, on the other hand, allows strings to be enclosed between either double or single quotation marks. Moreover, as we’ve seen previously, Python does not require the use of any keyword to declare a variable’s data-type.

The Console.ReadLine() function in C# and the input() function in Python wait for the user to enter a string and press Enter. The string is then stored in the string variable name on the left hand side of the statement. To prepare the welcome message, we concatenate the string “Welcome, ” with the string stored in the variable name, using the  + operator.

Since the string “Please enter you name:” was used only once in the program and we did not require it for future use, there was no need to store it in a string variable. A better approach would be to put the complete string as it is in the Console.WriteLine() and input() function.



What we learnt

  1. How to get string input from user.
  2. Strings must be enclosed between double quotation marks in C# and between either double or single quotation marks in Python.
  3. The + operator is used for concatenation of strings.
  4. C#: To read a value into or display the value of a variable we use the functions  Console.ReadLine()  and  Console.WriteLine() respectively.
  5. Python: To read a value into or display the value of a variable we use the functions  intput()  and  print() respectively.

< Arithmetic operators               Decision making and branching >

You may also like: