Create a new file in Cloud9 called lab_4_step_1_positional_arguments.py and add the code below:
lab_4_step_1_positional_arguments.py
import boto3 def translate_text(): client = boto3.client('translate') response = client.translate_text( Text='I am learning to code in AWS', SourceLanguageCode='en', TargetLanguageCode='fr' ) print(response) def main(): translate_text() if __name__=="__main__": main()
The first method we are going to use is called positional arguments. As the name suggests the order that the argument is passed to the function depends on order within the brackets ().
Amend the function so that we have some positional arguments:
import boto3 def translate_text(text, source_language_code, target_language_code): # we define the positional arguments in the () client = boto3.client('translate') response = client.translate_text( Text=text, # we remove the hard coded value SourceLanguageCode=source_language_code, # we used the positional argument instead TargetLanguageCode=target_language_code ) print(response) def main(): translate_text('I am learning to code in AWS','en','fr') # we provide the value for the arguments when we call the function in the correct positional order. if __name__=="__main__": main()
To run the program, enter the following command in the terminal:
python lab_4_step_1_positional_arguments.py
We removed the hard coded parameter values and replaced them with the argument names:
We defined the argument names as inputs in the order of the parameters in between the brackets ().
When we called the function we used the actual values in the correct position.
Try running the program again but this time amend the following line:
translate_text('I am learning to code in AWS','en','fr')
Change the values for:
What happens if you mix up the order?