How to talk to a computer - zamaniamin/python GitHub Wiki
-
The
print()
function sends data to the console, while theinput()
function gets data from the 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!")
Tip: 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.")
-
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. -
The result of the
input()
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
- You can also multiply (
*
‒ replication) strings, e.g.:
my_input = input("Enter something: ") # Example input: hello
print(my_input * 3) # Expected output: hellohellohello
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. - the
float()
function takes one argument (e.g., a string:float(string)
and tries to convert it into a float. - the
str()
function takes one argument (e.g., a number:str(number)
and tries to convert it into a string.