2.6.1.1 How to talk to a computer Public

2.6.1.1 How to talk to a computer

David Khieu
Course by David Khieu, updated more than 1 year ago Contributors

Description

2.6.1.1 How to talk to a computer

Module Information

Description

The input() function
No tags specified
The input() function We're now going to introduce you to a completely new function, which seems to be a mirro reflection of the good old print() function Why? Well, print() sends data to the console.  The new function gets data from it.  print() has no usable result. The meaning of the new fucntion is to return a very usable result. The function is named input() . The name of the function says everything.  The Input() function is able to read data entered by the user and to return the same data to the running program.  The program can manipulate the data, making the code truly interactive.  Virtually all programs read and process data. A program which doesn't get a user's input is a deaf program. Take a look at our example: print("Tell me anything...") anything = input() print("Hmm...", anything, "... Really?") It shows a very simple case of using the input() function. Note:  The program prompts the user to input some data from the console (most likely using a keyboard, although it is also possible to input data using voice or image); the input() function is invoked without arguments (this is the simplest way of using the function); the function will switch the console to input mode; you'll see a blinking cursor, and you'll be able to input some keystrokes, finishing off by hitting the Enter key; all the inputted data will be sent to your program through the function's result; note: you need to assign the result to a variable; this is crucial - missing out this step will cause the entered data to be lost; then we use the print() function to output the data we get, with some additional remarks. Try to run the code and let the function show you what it can do for you. The program prompts the user to input some data from the console (most likely using a keyboard, although it is also possible to input data using voice or image); the input() function is invoked without arguments (this is the simplest way of using the function); the function will switch the console to input mode; you'll see a blinking cursor, and you'll be able to input some keystrokes, finishing off by hitting the Enter key; all the inputted data will be sent to your program through the function's result; note: you need to assign the result to a variable; this is crucial - missing out this step will cause the entered data to be lost; then we use the print() function to output the data we get, with some additional remarks. Try to run the code and let the function show you what it can do for you.
Show less

Description

The input() function with an argument
No tags specified
The input() function with an argument The input() function can do something else: it can prompt the user without any help from print(). We've modified our example a bit, look at the code: anything = input("Tell me anything...") print("Hmm...", anything, "...Really?") Note: the input()  function is invoked with one argument - it's a string containing a message the message will be displayed on the console before the user is given an opportunity to enter anything input() will do its job The variant of th einput() invocation simplifies the code and makes it clearer.  The result of the input() function  We've said it already, but it must be unambiguously stated once again: the the result of the input() function is a string. A string containing all the characters the user enters from the keyboard. It is not an integer or a float.  This means that you mustn't use it as an argument of any arithmetic operation, e.g., you can't use this data to square it, divide it by anything, or divide anything by it.  anything = input("Enter a number: ") something = anything ** 2.0 print(anything, "to the power of 2 is", something)
Show less

Description

The input() function - prohibited operations
No tags specified
The input() function - prohibited operations Look at the code in the editor. run it, enter any number, and press Enter.  What happens?  Python should give you the following output:  Traceback (most recent call last): File ".main.py", line 4, in <module> something = anything ** 2.0 TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'float' The last line of the sentence explains everything - you tried to apply the ** operator to 'str' (string) accompanied with 'float' This is prohibited.  This should be obvious - can you predict the value of "to be or not to be" raised to the power of 2?  We can't. Python can't either.  Have we fallen into a deadlock? Is there a solution to this issue? Of course there is.
Show less

Description

Type casting
No tags specified
Type Casting Python offers two simple functions to specify a type of data and solve this problem -here they are: int() and float()  Their names are self-commenting: the int() function takes one argument (e.g., a string: int(string)) and tries to convert it into an integer; if it fails, the whole program will fail too (there is a workaround for this situation, but we'll show you this a little later the float() function takes one argument (e.g., a string: float(string)) and tries to convert it into a float (the rest is the same). This is very simple and very effective. Moreover, you can invoke any of the functions by passing the input() results directly to them. There's no need to use any variable as an intermediate storage.  We've implemented the idea in the editor - take a look at the code.  Can you imagine how the string entered by the user flows from input() into print()?  Try to run the modified code. Don't forget to enter a valid number. Check some different values, small and big, negative and positive. Zero is a good input, too.
Show less

Description

More about input() and type casting
No tags specified
More about input() and type casting Having a team consisting of the trio input() - int() - float() opens up a lot of new possibilities.  You'll eventually be able to write complete programs, accepting data in the form of numbers, processing them and displaying the results.  Of course, these programs will be very primitive and not very usable, as they cannot make decisions, and consequently are not able to react differently to different situations.  This is not really a problem, though; we'll show you how to overcome it soon.  Our next example refers to the earlier program to find the length of a hypotenuse. Let's rewrite it and make it able to read the lengths of the legs from the console.  Check out the editor window - this is how it looks now.  The program asks the user twice for both legs, lengths, evaluates the hypotenuse and prints the result.  Run it and try to input some negative values.  The program - unfortunately - does not react to this obvious error.  Let's ignore this weakness for now. We'll come back to it soon.  Note that in the program that you can see in the editor, they hypo variable is used for only one purpose -t save the calculated value between the execution of the adjoining line of code.  As the print() function accepts an expression as its argument, you can remove the variable from the code. Just like this:  leg_a = float(input("Input first leg length: ")) leg_b = float(input("Input second leg length: ")) print("Hypotenuse length is", (leg_a**2 + leg_b**2) ** .5)
Show less

Description

String operators - introduction
No tags specified
String operators - introduction It's time to return to these two arithmetic operators + and *  We want to show you that they have a second function. They are able to do something more than just add and multiply We've seen them in action where their arguments are numbers (floats or integers, it doesn't matter). Now we're going to show you that they can handle strings, too, albeit in a very specific way.  Concatenation The + (plus) sign, when applied to two strings, becomes a concatenation operator: string + string It simply concatenates (glues) two strings into one. Of course, like its arithmetic sibling, it can be used more than once in one expression, and in such a context it behaves according to left-sided binding.  In contrast to its arithmetic sibling, the concatenation operator is not commutative, i.e., "ab" + "ba" is not the same as "ba" + "ab" Don't forget - if you want the + sign to be a concatenator, not an adder, you must ensure that both its arguments are strings. You cannot mix types here.  This simple program shows the + sign in its second use: fnam = input("May I have your first name, please? ") lnam = input("May I have your last name, please? ") print("Thank you.") print("\nYour name is " + fnam + " " + lnam + ".") Note: using+ to concatenate strings lets you construct the output in a more precise way than with a pure print() function, even if enriched with the end= and sep= keyword arguments.  Run the code and see if the output matches your predictions.
Show less

Description

Replication
No tags specified
Replication The * (asterisk) sign, when applied to a string and number (or a number and string, as it remains commutative in this position) becomes a replication operator:   string * number number * string It replicates the string the same number of times specified by the number. For example: "James" * 3 gives "JamesJamesJames" 3 * "an" gives "ananan" 5 * "2" (or "2" * 5) gives "22222" (not 10!) REMEMBER A number less than or equal to zero produces an empty string. This simple program "draws" a rectangle, making use of an old operator (+) in a new role: print("+" + 10 * "-" + "+") print(("|" + " " * 10 + "|\n") * 5, end="") print("+" + 10 * "-" + "+") Note the way in which we've used the parentheses in the second line of the code.  Try practicing to create other shapes of your own artwork!
Show less

Description

Type conversion: str()
No tags specified
Type conversion: str()  You already know how to use the int() and float() functions to convert a string into a number. This type of conversion is not a one-way street. You can also convert a number into a string, which is way easier and safer - this kind of operation is always possible.  A function capable of doing that is called str(): str(number) To be honest, it can do much more than just transform numbers into strings, but that can wait for later.  The "right-angle triangle" again Here is our "right-angle triangle" program again:   leg_a = float(input("Input first leg length: ")) leg_b = float(input("Input second leg length: ")) print("Hypotenuse length is " + str((leg_a**2 + leg_b**2) ** .5)) We've modified it a bit to show you how the str() function works. Thanks to this, we can pass the whole result to the print() function as one string, forgetting about the commas.  You've made some serious strides on your way to Python programming.  You already know the basic data types, and a set of fundamental operators. You know how to organize the output and how to get data from the user. These are very strong foundations for Module 3. But before we move on the next module, let's do a few labs, and recap all that you've learned in this section.
Show less

LAB

Description

LAB
No tags specified
Objectives becoming familiar with the inputting and outputting the data in Python evaluating simple expressions Scenario Your task is to complete the code in order to evaluate the results of four basic arithmetic operations.  The results have to be printed to the console.  You may not be able to protect the code from a user who wants to divide by zero. That's okay, don't worry about it for now.  Test your code - does it produce the results you expect ? We won't show you any test data - that would be too simple.  What I wrote: vara = float(input("Input variable a number here: " ))# input a float value for variable a here varb = float(input("Input variable b number here: "))# input a float value for variable b here print("Variable a plus Variable b is", vara + varb)# output the result of addition here print("Variable a minus Variable b is", vara - varb)# output the result of subtraction here print("Variable a multiplied by Variable b is", vara * varb)# output the result of multiplication here print("Variable a divided by Variable b is", vara / varb)# output the result of division here print("\nThat's all, folks!")
Show less

LAB

Description

LAB
No tags specified
LAB Objectives becoming familiar with the concepts of numbers, operators and arithmetic operations in Python understanding the precedence and associativity of Python operators, as well as the proper use of parentheses.  Scenario Your task is to complete the code in order to evaluate the following expression: The result should be assigned to y. Be careful - watch the operators and keep their priorities in mind. Don't hesitate to use as many parentheses as you need.  You can use additional variables to shorten the expression (but it's not necessary). Test your code carefully.  Test Data Sample input: 1 expected output:    y = 0.6000000000000001 Sample input: 10 Expected output:   y = 0.009999000199950014 Sample input: -5 Expected output:   y = -0.19258202567760344 Code I wrote: x = float(input("Enter value for x: ")) y=1/(x+(1/(x+(1/(x+(1/x))))))# Write your code here. print("y =", y)
Show less

LAB

Description

LAB
No tags specified
LAB Objectives improving the ability to use numbers, operators, and arithmetic operations in Python using the print() function's formatting capabilities  learning to express everyday-life phenomena in terms of programming language Scenario Your task is to prepare a simple code able to evaluate the end time of a period of time, given as a number of minutes (it could be arbitrarily large). The start time is given as a pair of hours (0..23) and minutes (0..59). The result has to be printed to the console.  For example, if an event starts at 12:17 and lasts 59 minutes,  it will end at 13:16. Don't worry about any imperfections in your code - it's okay if it accepts the invalid time - the most important thing is that the code produce valid results for valid input dat.  Test Data Sample input: 12 17 59 Expected output: 13:16 Sample input: 23 58 642 Expected output: 10:40 Sample input: 0 1 2939 Expected output: 1:0 Used ChatGPT for code: start_hour = int(input("Enter the starting hour (0-23): ")) start_minute = int(input("Enter the starting minute (0-59): ")) duration_minutes = int(input("Enter the duration in minutes: ")) start_total_minutes = start_hour * 60 + start_minute end_total_minutes = (start_total_minutes + duration_minutes) % 1440 end_hour = end_total_minutes // 60 end_minute = end_total_minutes % 60 print("End time: {:02d}:{:02d}".format(end_hour, end_minute))   Explanation: The input() function is used to prompt the user for the starting hour, starting minute, and duration in minutes. The start_total_minutes variable is calculated by converting the starting hour to minutes and adding it to the starting minute. The end_total_minutes variable is calculated by adding the start_total_minutes and the duration_minutes, and then taking the modulo 1440 (the number of minutes in a day) to handle cases where the end time is on the next day. The end_hour and end_minute variables are calculated by converting the end_total_minutes to hours and minutes, respectively, using integer division and modulo. Finally, the end time is printed in the format hh:mm, with leading zeros added if necessary using the {:02d} format specifier.
Show less

Description

Key takeaways
No tags specified
Key takeaways The print() function sends data to the console, while the input() function gets data from console. The input() function comes with an optional parameter: the prompt string. It allows you to write a message before the user input, e.g.: name = input("Enter your name: ") print("Hello, " + name + ". Nice to meet you!") When the input() function is called, the program's flow is stopped, the prompt symbol keeps blinking (it prompts the user to take action when the console is switched to input mode) until the user has entered an input and/or pressed the Enter key.  NOTE You can test the functionality of the input() function in its full scope locally on your machine. For resource optimization reasons, we have limited the maximum program execution time in Edube to a few seconds. Go to the Sandbox, copy-paste the above snippet, run the program, and do nothing - just wait a few seconds to see what happens. Your program should be stopped automatically after a short moment. Now open IDLE, and run the same program there - can you see the difference?  Tip: the above-mentioned feature of the input() function can be used to prompt the user to end a program. Look at the code below: name = input("Enter your name: ") print("Hello, " + name + ". Nice to meet you!") print("\nPress Enter to end the program.") input() print("THE END.") 4. The result of th einput() function is a string. You can add strings to each other using the concatenation (+) operator. Check out this code: num_1 = input("Enter the first number: ") # Enter 12 num_2 = input("Enter the second number: ") # Enter 21 print(num_1 + num_2) # the program returns 1221 5. You can also multiply (* - replication) strings, e.g.: my_input = input("Enter something: ") # Example input: hello print(my_input * 3) # Expected output: hellohellohello Exercise 1 What is the output of the following snippet? x = int(input("Enter a number: ")) # The user enters 2 print(x * "5") 55 If the user enters 2 as the input, the output of the snippet will be the string "55". Here's why: The input() function is used to prompt the user for a number. In this case, the user enters 2. The int() function is used to convert the user's input (which is initially a string) to an integer. So, x now has the value 2. The expression x * "5" is evaluated. Since x is an integer and "5" is a string, this expression will repeat the string "5" x times. So, the output will be the string "55". Exercise 2 What is the expected output of the following snippet? x = input("Enter a number: ") # The user enters 2 print(type(x)) <class 'str'> Here's why: The input() function is used to prompt the user for a number. In this case, the user enters 2. The value entered by the user is treated as a string and assigned to the variable x. The type() function is then used to determine the data type of x. Since the value of x is a string (even though it represents a numerical value), the output will be <class 'str'>.
Show less

Description

Congratulations! You have completed Module 2.
No tags specified
Congratulations! You have completed Module 2. Well done! You've reached the end of Module 2 and completed a major milestone in your Python programming education.  Here's a short summary of the objectives you've covered and got familiar in Module 2: the basic methods of formatting and outputting data offered in Python, together with the primary kinds of data and numerical operators, their mutual relations and bindings the concept of variables and variable naming conventions  the assignment operator, the rules governing the building of expressions the inputting and converting of data You are now ready to take the module quiz and attempt the final challenge: Module 2 test, which will help gauge what you've learned so far.
Show less
Show full summary Hide full summary